JAL-3032 adds Java 8 functionality (2/2)
authorhansonr <hansonr@STO24954W.ad.stolaf.edu>
Fri, 20 Jul 2018 16:47:58 +0000 (11:47 -0500)
committerhansonr <hansonr@STO24954W.ad.stolaf.edu>
Fri, 20 Jul 2018 16:47:58 +0000 (11:47 -0500)
 the "::" operator
 lambda expressions
 java.util.function.*
 java.util.stream.*
 default methods in interfaces

360 files changed:
.classpath
build-libjs.xml
build-site.xml
libjs/MiGLayout-site.zip
libjs/VARNA-site.zip
libjs/jsonsimple-site.zip
libjs/log4j-site.zip [deleted file]
src/net/miginfocom/layout/BoundSize.java [deleted file]
src2/README_SWINGJS.txt
src2/fr/orsay/lri/varna/README_SWINGJS.txt [new file with mode: 0644]
src2/fr/orsay/lri/varna/VARNA.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/VARNAPanel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/AlignmentDemo.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/BasicINI.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/FileNameExtensionFilter.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/NussinovDemo.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/NussinovDesignDemo.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/SecStrConsensus.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/SuperpositionDemo.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/VARNAConsoleDemo.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/VARNAEditor.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/VARNAGUI.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/VARNAOnlineDemo.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/VARNAPrinter.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/VARNAcmd.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqAnnotationDataModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqCellEditor.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqCellRenderer.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqFileModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqGUI.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqNode.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqRNASecStrModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqTree.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/FragSeqTreeModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/fragseq/Watcher.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUI.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUICellEditor.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUIModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUIRenderer.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUITree.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUITreeModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/newGUI/Watcher.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/Connection.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/Couple.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/GraphicalTemplateElement.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/Helix.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/MouseControler.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEditor.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEditorPanelUI.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEdits.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/TemplatePanel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/applications/templateEditor/UnpairedRegion.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/ActionEditor.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/ActionRenderer.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/AnnotationTableModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/BaseSpecialColorEditor.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/BaseTableModel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/ColorRenderer.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/GradientEditorPanel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/ReorderableJList.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/VARNAConsole.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/components/ZoomWindow.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurBPHeightIncrement.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurBaseSpecialColorEditor.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurBlinkingThread.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurBorder.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurClicMovement.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurDemoTextField.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurDraggedMolette.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurGlobalRescale.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurGlobalRotation.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurInterpolator.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurJCheckBoxMenuItem.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurMenu.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurMolette.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurNumPeriod.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurScriptParser.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurSelectionHighlight.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurSliderLabel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurSpaceBetweenBases.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurTableAnnotations.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurVARNAPanelKeys.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurVueAnnotation.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/controlers/ControleurZoom.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionDrawingAlgorithm.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionEdgeEndpointAlreadyConnected.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionExportFailed.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionFileFormatOrSyntax.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionInvalidRNATemplate.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionJPEGEncoding.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionLoadingFailed.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionModeleStyleBaseSyntaxError.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionNAViewAlgorithm.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionNonEqualLength.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionParameterError.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionPermissionDenied.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionUnmatchedClosingParentheses.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionWritingForbidden.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionXMLGeneration.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/ExceptionXmlLoading.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/exceptions/MappingException.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/factories/RNAAlignment.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/factories/RNAFactory.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/factories/StockholmIO.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/interfaces/InterfaceParameterLoader.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/interfaces/InterfaceParseExport.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/interfaces/InterfaceVARNABasesListener.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/interfaces/InterfaceVARNAListener.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/interfaces/InterfaceVARNAObservable.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/interfaces/InterfaceVARNARNAListener.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/interfaces/InterfaceVARNASelectionListener.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/BaseList.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/FullBackup.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/VARNAConfig.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/VARNAConfigLoader.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/VARNAEdits.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/annotations/ChemProbAnnotation.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/annotations/HighlightRegionAnnotation.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/annotations/TextAnnotation.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/ArcCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/CircleCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/ColorCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/FillCircleCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/FillPolygonCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/FontCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/GraphicElement.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/LineCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/PSExport.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/PolygonCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/RectangleCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/SVGExport.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/SecStrDrawingProducer.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/SecStrProducerGraphics.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/SwingGraphics.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/TextCommand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/TikzExport.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/VueVARNAGraphics.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/export/XFIGExport.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/geom/ComputeArcCenter.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/geom/ComputeEllipseAxis.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/geom/CubicBezierCurve.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/geom/HalfEllipse.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/geom/LinesIntersect.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/geom/MiscGeom.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/naView/Base.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/naView/Connection.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/naView/Loop.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/naView/NAView.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/naView/Radloop.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/naView/Region.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/DrawRNATemplate.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/Mapping.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModelBaseStyle.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleBP.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleBPStyle.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleBackbone.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleBackboneElement.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleBase.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleBaseNucleotide.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleBasesComparison.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleColorMap.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/ModeleStrand.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/RNA.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/StructureTemp.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/VARNAPoint.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/rna/VARNASecDraw.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/BatchBenchmark.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/BatchBenchmarkPrepare.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/Benchmark.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/DrawRNATemplateCurveMethod.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/DrawRNATemplateMethod.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNANodeValue2TemplateDistance.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplate.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateBasePair.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateBrokenBasePair.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateSequence.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNATemplate.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNATemplateAlign.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNATemplateDrawingAlgorithmException.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNATemplateMapping.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/RNATemplateMappingException.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/templates/TODO.txt [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/AlignedNode.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/ExampleDistance2.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/ExampleDistance3.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/GraphvizDrawableNodeValue.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/RNANodeValue.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/RNANodeValue2.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/RNANodeValue2WrongTypeException.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/RNATree.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/RNATree2.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/RNATree2Exception.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/Tree.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/TreeAlign.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/TreeAlignException.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/TreeAlignLabelDistanceAsymmetric.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/TreeAlignLabelDistanceSymmetric.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/TreeAlignResult.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/models/treealign/TreeGraphviz.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/utils/RNAMLParser.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/utils/TranslateFormatRNaseP.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/utils/VARNASessionParser.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/utils/XMLUtils.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/Imprimer.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/PrintTest.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueAboutPanel.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueAnnotation.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueBPHeightIncrement.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueBPList.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueBPThickness.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueBPType.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueBaseValues.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueBases.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueBorder.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueChemProbAnnotation.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueColorMapStyle.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueFont.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueGlobalRescale.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueGlobalRotation.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueHighlightRegionEdit.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueJPEG.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueListeAnnotations.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueLoadColorMapValues.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueManualInput.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueMenu.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueNumPeriod.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueRNAList.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueSpaceBetweenBases.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueStyleBP.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueUI.java [new file with mode: 0644]
src2/fr/orsay/lri/varna/views/VueZoom.java [new file with mode: 0644]
src2/javajs/J2SIgnoreImport.java [new file with mode: 0644]
src2/javajs/J2SRequireImport.java [new file with mode: 0644]
src2/javajs/_README.txt [new file with mode: 0644]
src2/javajs/api/BytePoster.java [new file with mode: 0644]
src2/javajs/api/EigenInterface.java [new file with mode: 0644]
src2/javajs/api/GenericBinaryDocument.java [new file with mode: 0644]
src2/javajs/api/GenericBinaryDocumentReader.java [new file with mode: 0644]
src2/javajs/api/GenericCifDataParser.java [new file with mode: 0644]
src2/javajs/api/GenericColor.java [new file with mode: 0644]
src2/javajs/api/GenericImageDialog.java [new file with mode: 0644]
src2/javajs/api/GenericImageEncoder.java [new file with mode: 0644]
src2/javajs/api/GenericLineReader.java [new file with mode: 0644]
src2/javajs/api/GenericOutputChannel.java [new file with mode: 0644]
src2/javajs/api/GenericZipInputStream.java [new file with mode: 0644]
src2/javajs/api/GenericZipTools.java [new file with mode: 0644]
src2/javajs/api/Interface.java [new file with mode: 0644]
src2/javajs/api/JSFunction.java [new file with mode: 0644]
src2/javajs/api/JSInterface.java [new file with mode: 0644]
src2/javajs/api/JSONEncodable.java [new file with mode: 0644]
src2/javajs/api/ResettableStream.java [new file with mode: 0644]
src2/javajs/api/ZInputStream.java [new file with mode: 0644]
src2/javajs/api/js/J2SObjectInterface.java [new file with mode: 0644]
src2/javajs/api/js/JSInterface.java [new file with mode: 0644]
src2/javajs/export/PDFCreator.java [new file with mode: 0644]
src2/javajs/export/PDFObject.java [new file with mode: 0644]
src2/javajs/img/BMPDecoder.java [new file with mode: 0644]
src2/javajs/img/CRCEncoder.java [new file with mode: 0644]
src2/javajs/img/GifEncoder.java [new file with mode: 0644]
src2/javajs/img/ImageEncoder.java [new file with mode: 0644]
src2/javajs/img/Jpg64Encoder.java [new file with mode: 0644]
src2/javajs/img/JpgEncoder.java [new file with mode: 0644]
src2/javajs/img/PdfEncoder.java [new file with mode: 0644]
src2/javajs/img/PngEncoder.java [new file with mode: 0644]
src2/javajs/img/PpmEncoder.java [new file with mode: 0644]
src2/javajs/util/A4.java [new file with mode: 0644]
src2/javajs/util/AU.java [new file with mode: 0644]
src2/javajs/util/AjaxURLConnection.java [new file with mode: 0644]
src2/javajs/util/AjaxURLStreamHandler.java [new file with mode: 0644]
src2/javajs/util/AjaxURLStreamHandlerFactory.java [new file with mode: 0644]
src2/javajs/util/ArrayDataReader.java [new file with mode: 0644]
src2/javajs/util/BArray.java [new file with mode: 0644]
src2/javajs/util/BC.java [new file with mode: 0644]
src2/javajs/util/BS.java [new file with mode: 0644]
src2/javajs/util/Base64.java [new file with mode: 0644]
src2/javajs/util/BinaryDocument.java [new file with mode: 0644]
src2/javajs/util/CU.java [new file with mode: 0644]
src2/javajs/util/CifDataParser.java [new file with mode: 0644]
src2/javajs/util/CompoundDocDirEntry.java [new file with mode: 0644]
src2/javajs/util/CompoundDocHeader.java [new file with mode: 0644]
src2/javajs/util/CompoundDocument.java [new file with mode: 0644]
src2/javajs/util/DF.java [new file with mode: 0644]
src2/javajs/util/DataReader.java [new file with mode: 0644]
src2/javajs/util/DebugJS.java [new file with mode: 0644]
src2/javajs/util/Eigen.java [new file with mode: 0644]
src2/javajs/util/Encoding.java [new file with mode: 0644]
src2/javajs/util/JSAudioThread.java [new file with mode: 0644]
src2/javajs/util/JSJSONParser.java [new file with mode: 0644]
src2/javajs/util/JSONException.java [new file with mode: 0644]
src2/javajs/util/JSThread.java [new file with mode: 0644]
src2/javajs/util/LimitedLineReader.java [new file with mode: 0644]
src2/javajs/util/ListDataReader.java [new file with mode: 0644]
src2/javajs/util/Lst.java [new file with mode: 0644]
src2/javajs/util/M3.java [new file with mode: 0644]
src2/javajs/util/M34.java [new file with mode: 0644]
src2/javajs/util/M4.java [new file with mode: 0644]
src2/javajs/util/Matrix.java [new file with mode: 0644]
src2/javajs/util/Measure.java [new file with mode: 0644]
src2/javajs/util/MessagePackReader.java [new file with mode: 0644]
src2/javajs/util/OC.java [new file with mode: 0644]
src2/javajs/util/P3.java [new file with mode: 0644]
src2/javajs/util/P3i.java [new file with mode: 0644]
src2/javajs/util/P4.java [new file with mode: 0644]
src2/javajs/util/PT.java [new file with mode: 0644]
src2/javajs/util/Quat.java [new file with mode: 0644]
src2/javajs/util/Rdr.java [new file with mode: 0644]
src2/javajs/util/SB.java [new file with mode: 0644]
src2/javajs/util/StringDataReader.java [new file with mode: 0644]
src2/javajs/util/T3.java [new file with mode: 0644]
src2/javajs/util/T3d.java [new file with mode: 0644]
src2/javajs/util/T3i.java [new file with mode: 0644]
src2/javajs/util/T4.java [new file with mode: 0644]
src2/javajs/util/V3.java [new file with mode: 0644]
src2/javajs/util/V3d.java [new file with mode: 0644]
src2/javajs/util/XmlUtil.java [new file with mode: 0644]
src2/javajs/util/ZipData.java [new file with mode: 0644]
src2/javajs/util/ZipTools.java [new file with mode: 0644]
src2/net/miginfocom/README_SWINGJS.txt [moved from src/net/miginfocom/README_SWINGJS.txt with 100% similarity]
src2/net/miginfocom/layout/AC.java [moved from src/net/miginfocom/layout/AC.java with 96% similarity]
src2/net/miginfocom/layout/AnimSpec.java [moved from src/net/miginfocom/layout/AnimSpec.java with 100% similarity]
src2/net/miginfocom/layout/BoundSize.java [new file with mode: 0644]
src2/net/miginfocom/layout/CC.java [moved from src/net/miginfocom/layout/CC.java with 99% similarity]
src2/net/miginfocom/layout/ComponentWrapper.java [moved from src/net/miginfocom/layout/ComponentWrapper.java with 100% similarity]
src2/net/miginfocom/layout/ConstraintParser.java [moved from src/net/miginfocom/layout/ConstraintParser.java with 100% similarity]
src2/net/miginfocom/layout/ContainerWrapper.java [moved from src/net/miginfocom/layout/ContainerWrapper.java with 100% similarity]
src2/net/miginfocom/layout/DimConstraint.java [moved from src/net/miginfocom/layout/DimConstraint.java with 96% similarity]
src2/net/miginfocom/layout/Grid.java [moved from src/net/miginfocom/layout/Grid.java with 100% similarity]
src2/net/miginfocom/layout/InCellGapProvider.java [moved from src/net/miginfocom/layout/InCellGapProvider.java with 100% similarity]
src2/net/miginfocom/layout/LC.java [moved from src/net/miginfocom/layout/LC.java with 98% similarity]
src2/net/miginfocom/layout/LayoutCallback.java [moved from src/net/miginfocom/layout/LayoutCallback.java with 100% similarity]
src2/net/miginfocom/layout/LayoutUtil.java [moved from src/net/miginfocom/layout/LayoutUtil.java with 82% similarity]
src2/net/miginfocom/layout/LinkHandler.java [moved from src/net/miginfocom/layout/LinkHandler.java with 100% similarity]
src2/net/miginfocom/layout/PlatformDefaults.java [moved from src/net/miginfocom/layout/PlatformDefaults.java with 100% similarity]
src2/net/miginfocom/layout/ResizeConstraint.java [moved from src/net/miginfocom/layout/ResizeConstraint.java with 78% similarity]
src2/net/miginfocom/layout/UnitConverter.java [moved from src/net/miginfocom/layout/UnitConverter.java with 100% similarity]
src2/net/miginfocom/layout/UnitValue.java [moved from src/net/miginfocom/layout/UnitValue.java with 91% similarity]
src2/net/miginfocom/swing/MigLayout.java [moved from src/net/miginfocom/swing/MigLayout.java with 93% similarity]
src2/net/miginfocom/swing/SwingComponentWrapper.java [moved from src/net/miginfocom/swing/SwingComponentWrapper.java with 100% similarity]
src2/net/miginfocom/swing/SwingContainerWrapper.java [moved from src/net/miginfocom/swing/SwingContainerWrapper.java with 100% similarity]
src2/org/json/simple/ItemList.java [new file with mode: 0644]
src2/org/json/simple/JSONArray.java [new file with mode: 0644]
src2/org/json/simple/JSONAware.java [new file with mode: 0644]
src2/org/json/simple/JSONObject.java [new file with mode: 0644]
src2/org/json/simple/JSONStreamAware.java [new file with mode: 0644]
src2/org/json/simple/JSONValue.java [new file with mode: 0644]
src2/org/json/simple/README.txt [new file with mode: 0644]
src2/org/json/simple/parser/ContainerFactory.java [new file with mode: 0644]
src2/org/json/simple/parser/ContentHandler.java [new file with mode: 0644]
src2/org/json/simple/parser/JSONParser.java [new file with mode: 0644]
src2/org/json/simple/parser/ParseException.java [new file with mode: 0644]
src2/org/json/simple/parser/Yylex.java [new file with mode: 0644]
src2/org/json/simple/parser/Yytoken.java [new file with mode: 0644]
srcjar2/README_SWINGJS.txt [new file with mode: 0644]
swingjs/README.txt
swingjs/SwingJS-site.zip
swingjs/net.sf.j2s.core.jar
swingjs/ver/3.1.1/SwingJS-site.zip [new file with mode: 0644]
swingjs/ver/3.2.1/SwingJS-site.zip [new file with mode: 0644]
swingjs/ver/3.2.1/net.sf.j2s.core_3.2.1.jar

index 5cb0080..b7d213b 100644 (file)
@@ -69,5 +69,6 @@
        <classpathentry kind="lib" path="lib/htsjdk-2.12.0.jar"/>
        <classpathentry kind="lib" path="lib/groovy-all-2.4.12-indy.jar"/>
        <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
+       <classpathentry exported="true" kind="con" path="GROOVY_DSL_SUPPORT"/>
        <classpathentry kind="output" path="classes"/>
 </classpath>
index 69b0510..ef8847a 100644 (file)
@@ -15,7 +15,7 @@
        <property name="j2sDir" value="${site}/swingjs/j2s"/>
        <property name="libjsDir" value="libjs"/>
 
-       <target name="zipall" depends="zipvarna,zipmig,ziplog4j,zipjson">
+       <target name="zipall" depends="zipvarna,zipmig,zipjson">
                
                
   </target>
@@ -24,7 +24,7 @@
     <!-- VARNA -->
            <property name="varna.zip" value="${libjsDir}/VARNA-site.zip" />                    
                <echo> Zipping up ${varna.zip} </echo>
-               <zip destfile="${varna.zip}" basedir="${site}" includes="fr_*,swingjs/j2s/fr/**" />
+               <zip destfile="${varna.zip}" basedir="${site}" includes="fr_*.html,swingjs/j2s/fr/**" />
        </target>
 
        <target name="zipmig">
                        <zip destfile="${mig.zip}" basedir="${site}" includes="swingjs/j2s/net/miginfocom/**" />
        </target>
 
+       <!-- log4j minimal implementation is in jalview/javascript
+             and is mapped from org.apache.log4j by the following .j2s line:
+             
+             j2s.class.replacements=org.apache.log4j.->jalview.javascript.log4j.
+              
        <target name="ziplog4j">
-                 <!-- org.apache.log4j -->
+                 <!- org.apache.log4j ->
                    <property name="log4j.zip" value="${libjsDir}/log4j-site.zip" />                    
                        <echo> Zipping up ${log4j.zip} </echo>
                        <zip destfile="${log4j.zip}" basedir="${site}" includes="swingjs/j2s/org/apache/log4j/**" />
        </target>
-
+    -->
        <target name="zipjson">
                  <!-- org.json.simple -->
                    <property name="json.zip" value="${libjsDir}/jsonsimple-site.zip" />                        
index 82061d3..fa4a5c4 100644 (file)
@@ -23,8 +23,8 @@
        <!-- packages -->
     <property name="varna.zip" value="${libjsDir}/VARNA-site.zip" />
     <property name="mig.zip" value="${libjsDir}/MiGLayout-site.zip" />                 
-    <property name="log4j.zip" value="${libjsDir}/log4j-site.zip" />                   
     <property name="json.zip" value="${libjsDir}/jsonsimple-site.zip" />                       
+    <!-- property name="log4j.zip" value="${libjsDir}/log4j-site.zip" / -->                    
 
        <!-- output directories -->
        <property name="site" value="site"/>
        <echo> Unzipping ${mig.zip} into ${site} </echo> 
        <unzip src="${mig.zip}" dest="${site}" overwrite="true"/>       
        
-       <!-- log4j -->
+       <!-- 
 
        <echo> Unzipping ${log4j.zip} into ${site} </echo> 
        <unzip src="${log4j.zip}" dest="${site}" overwrite="true"/>     
+       log4j -->
        
        <!-- json -->
 
index 0c3f63b..54fcc37 100644 (file)
Binary files a/libjs/MiGLayout-site.zip and b/libjs/MiGLayout-site.zip differ
index 53d36df..7d7aeae 100644 (file)
Binary files a/libjs/VARNA-site.zip and b/libjs/VARNA-site.zip differ
index 937da11..d43476a 100644 (file)
Binary files a/libjs/jsonsimple-site.zip and b/libjs/jsonsimple-site.zip differ
diff --git a/libjs/log4j-site.zip b/libjs/log4j-site.zip
deleted file mode 100644 (file)
index 21364ee..0000000
Binary files a/libjs/log4j-site.zip and /dev/null differ
diff --git a/src/net/miginfocom/layout/BoundSize.java b/src/net/miginfocom/layout/BoundSize.java
deleted file mode 100644 (file)
index 35301c1..0000000
+++ /dev/null
@@ -1,375 +0,0 @@
-package net.miginfocom.layout;
-
-//import java.beans.Encoder;
-//import java.beans.Expression;
-//import java.beans.PersistenceDelegate;
-import java.io.Serializable;
-/*
- * License (BSD):
- * ==============
- *
- * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (miglayout (at) miginfocom (dot) com)
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification,
- * are permitted provided that the following conditions are met:
- * Redistributions of source code must retain the above copyright notice, this list
- * of conditions and the following disclaimer.
- * 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.
- * Neither the name of the MiG InfoCom AB nor the names of its contributors may be
- * used to endorse or promote products derived from this software without specific
- * prior written permission.
- *
- * 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 OWNER 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.
- *
- * @version 1.0
- * @author Mikael Grev, MiG InfoCom AB
- *         Date: 2006-sep-08
- */
-
-/**
- * A size that contains minimum, preferred and maximum size of type
- * {@link UnitValue}.
- * <p>
- * This class is a simple value container and it is immutable.
- * <p>
- * If a size is missing (i.e., <code>null</code>) that boundary should be
- * considered "not in use".
- * <p>
- * You can create a BoundSize from a String with the use of
- * {@link ConstraintParser#parseBoundSize(String, boolean, boolean)}
- */
-public class BoundSize implements Serializable
-{
-  public static final BoundSize NULL_SIZE = new BoundSize(null, null);
-
-  public static final BoundSize ZERO_PIXEL = new BoundSize(UnitValue.ZERO,
-          "0px");
-
-  private final transient UnitValue min;
-
-  private final transient UnitValue pref;
-
-  private final transient UnitValue max;
-
-  private final transient boolean gapPush;
-
-  /**
-   * Constructor that use the same value for min/preferred/max size.
-   * 
-   * @param minMaxPref
-   *          The value to use for min/preferred/max size.
-   * @param createString
-   *          The string used to create the BoundsSize.
-   */
-  public BoundSize(UnitValue minMaxPref, String createString)
-  {
-    this(minMaxPref, minMaxPref, minMaxPref, createString);
-  }
-
-  /**
-   * Constructor. <b>This method is here for serialization only and should
-   * normally not be used.</b> Use
-   * {@link ConstraintParser#parseBoundSize(String, boolean, boolean)} instead.
-   * 
-   * @param min
-   *          The minimum size. May be <code>null</code>.
-   * @param preferred
-   *          The preferred size. May be <code>null</code>.
-   * @param max
-   *          The maximum size. May be <code>null</code>.
-   * @param createString
-   *          The string used to create the BoundsSize.
-   */
-  public BoundSize(UnitValue min, UnitValue preferred, UnitValue max,
-          String createString) // Bound to old delegate!!!!!
-  {
-    this(min, preferred, max, false, createString);
-  }
-
-  /**
-   * Constructor. <b>This method is here for serialization only and should
-   * normally not be used.</b> Use
-   * {@link ConstraintParser#parseBoundSize(String, boolean, boolean)} instead.
-   * 
-   * @param min
-   *          The minimum size. May be <code>null</code>.
-   * @param preferred
-   *          The preferred size. May be <code>null</code>.
-   * @param max
-   *          The maximum size. May be <code>null</code>.
-   * @param gapPush
-   *          If the size should be hinted as "pushing" and thus want to occupy
-   *          free space if no one else is claiming it.
-   * @param createString
-   *          The string used to create the BoundsSize.
-   */
-  public BoundSize(UnitValue min, UnitValue preferred, UnitValue max,
-          boolean gapPush, String createString)
-  {
-    this.min = min;
-    this.pref = preferred;
-    this.max = max;
-    this.gapPush = gapPush;
-
-    LayoutUtil.putCCString(this, createString); // this escapes!!
-  }
-
-  /**
-   * Returns the minimum size as sent into the constructor.
-   * 
-   * @return The minimum size as sent into the constructor. May be
-   *         <code>null</code>.
-   */
-  public final UnitValue getMin()
-  {
-    return min;
-  }
-
-  /**
-   * Returns the preferred size as sent into the constructor.
-   * 
-   * @return The preferred size as sent into the constructor. May be
-   *         <code>null</code>.
-   */
-  public final UnitValue getPreferred()
-  {
-    return pref;
-  }
-
-  /**
-   * Returns the maximum size as sent into the constructor.
-   * 
-   * @return The maximum size as sent into the constructor. May be
-   *         <code>null</code>.
-   */
-  public final UnitValue getMax()
-  {
-    return max;
-  }
-
-  /**
-   * If the size should be hinted as "pushing" and thus want to occupy free
-   * space if no one else is claiming it.
-   * 
-   * @return The value.
-   */
-  public boolean getGapPush()
-  {
-    return gapPush;
-  }
-
-  /**
-   * Returns if this bound size has no min, preferred and maximum size set (they
-   * are all <code>null</code>)
-   * 
-   * @return If unset.
-   */
-  public boolean isUnset()
-  {
-    // Most common case by far is this == ZERO_PIXEL...
-    return this == ZERO_PIXEL || (pref == null && min == null && max == null
-            && gapPush == false);
-  }
-
-  /**
-   * Makes sure that <code>size</code> is within min and max of this size.
-   * 
-   * @param size
-   *          The size to constrain.
-   * @param refValue
-   *          The reference to use for relative sizes.
-   * @param parent
-   *          The parent container.
-   * @return The size, constrained within min and max.
-   */
-  public int constrain(int size, float refValue, ContainerWrapper parent)
-  {
-    if (max != null)
-      size = Math.min(size, max.getPixels(refValue, parent, parent));
-    if (min != null)
-      size = Math.max(size, min.getPixels(refValue, parent, parent));
-    return size;
-  }
-
-  /**
-   * Returns the minimum, preferred or maximum size for this bounded size.
-   * 
-   * @param sizeType
-   *          The type. <code>LayoutUtil.MIN</code>,
-   *          <code>LayoutUtil.PREF</code> or <code>LayoutUtil.MAX</code>.
-   * @return
-   */
-  final UnitValue getSize(int sizeType)
-  {
-    switch (sizeType)
-    {
-    case LayoutUtil.MIN:
-      return min;
-    case LayoutUtil.PREF:
-      return pref;
-    case LayoutUtil.MAX:
-      return max;
-    default:
-      throw new IllegalArgumentException("Unknown size: " + sizeType);
-    }
-  }
-
-  /**
-   * Convert the bound sizes to pixels.
-   * <p>
-   * <code>null</code> bound sizes will be 0 for min and preferred and
-   * {@link net.miginfocom.layout.LayoutUtil#INF} for max.
-   * 
-   * @param refSize
-   *          The reference size.
-   * @param parent
-   *          The parent. Not <code>null</code>.
-   * @param comp
-   *          The component, if applicable, can be <code>null</code>.
-   * @return An array of length three (min,pref,max).
-   */
-  final int[] getPixelSizes(float refSize, ContainerWrapper parent,
-          ComponentWrapper comp)
-  {
-    return new int[] {
-        min != null ? min.getPixels(refSize, parent, comp) : 0,
-        pref != null ? pref.getPixels(refSize, parent, comp) : 0,
-        max != null ? max.getPixels(refSize, parent, comp)
-                : LayoutUtil.INF };
-  }
-
-  /**
-   * Returns the a constraint string that can be re-parsed to be the exact same
-   * UnitValue.
-   * 
-   * @return A String. Never <code>null</code>.
-   */
-  String getConstraintString()
-  {
-    String cs = LayoutUtil.getCCString(this);
-    if (cs != null)
-      return cs;
-
-    if (min == pref && pref == max)
-      return min != null ? (min.getConstraintString() + "!") : "null";
-
-    StringBuilder sb = new StringBuilder(16);
-
-    if (min != null)
-      sb.append(min.getConstraintString()).append(':');
-
-    if (pref != null)
-    {
-      if (min == null && max != null)
-        sb.append(":");
-      sb.append(pref.getConstraintString());
-    }
-    else if (min != null)
-    {
-      sb.append('n');
-    }
-
-    if (max != null)
-      sb.append(sb.length() == 0 ? "::" : ":")
-              .append(max.getConstraintString());
-
-    if (gapPush)
-    {
-      if (sb.length() > 0)
-        sb.append(':');
-      sb.append("push");
-    }
-
-    return sb.toString();
-  }
-
-  void checkNotLinked()
-  {
-    if (isLinked())
-      throw new IllegalArgumentException("Size may not contain links");
-  }
-
-  boolean isLinked()
-  {
-    return min != null && min.isLinkedDeep()
-            || pref != null && pref.isLinkedDeep()
-            || max != null && max.isLinkedDeep();
-  }
-
-  boolean isAbsolute()
-  {
-    return (min == null || min.isAbsoluteDeep())
-            && (pref == null || pref.isAbsoluteDeep())
-            && (max == null || max.isAbsoluteDeep());
-  }
-
-  public String toString()
-  {
-    return "BoundSize{" + "min=" + min + ", pref=" + pref + ", max=" + max
-            + ", gapPush=" + gapPush + '}';
-  }
-
-//  static
-//  {
-//    if (LayoutUtil.HAS_BEANS)
-//    {
-//      LayoutUtil.setDelegate(BoundSize.class, new PersistenceDelegate()
-//      {
-//        @Override
-//        protected Expression instantiate(Object oldInstance, Encoder out)
-//        {
-//          BoundSize bs = (BoundSize) oldInstance;
-//          if (Grid.TEST_GAPS)
-//          {
-//            return new Expression(oldInstance, BoundSize.class, "new",
-//                    new Object[]
-//                    { bs.getMin(), bs.getPreferred(), bs.getMax(),
-//                        bs.getGapPush(), bs.getConstraintString() });
-//          }
-//          else
-//          {
-//            return new Expression(oldInstance, BoundSize.class, "new",
-//                    new Object[]
-//                    { bs.getMin(), bs.getPreferred(), bs.getMax(),
-//                        bs.getConstraintString() });
-//          }
-//        }
-//      });
-//    }
-//  }
-
-  // // ************************************************
-  // // Persistence Delegate and Serializable combined.
-  // // ************************************************
-  //
-  // private static final long serialVersionUID = 1L;
-  //
-  // protected Object readResolve() throws ObjectStreamException
-  // {
-  // return LayoutUtil.getSerializedObject(this);
-  // }
-  //
-  // private void writeObject(ObjectOutputStream out) throws IOException
-  // {
-  // if (getClass() == BoundSize.class)
-  // LayoutUtil.writeAsXML(out, this);
-  // }
-  //
-  // private void readObject(ObjectInputStream in) throws IOException,
-  // ClassNotFoundException
-  // {
-  // LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
-  // }
-}
index 1df9391..4a1240f 100644 (file)
@@ -8,5 +8,7 @@ After transpiling:
 2) edit README_SWINGJS.txt in main directory of the code
 3) add a zip-up target in build-zip-jars.xml (to libjs directory)
 4) add an unzip target in build-site.xml (from libjs to site directory)
+5) run build-zip-jars.xml
+6) run build-site.xml
 
 BH 2018.07.03
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/README_SWINGJS.txt b/src2/fr/orsay/lri/varna/README_SWINGJS.txt
new file mode 100644 (file)
index 0000000..32f0ad6
--- /dev/null
@@ -0,0 +1,163 @@
+
+Status
+======
+
+7/3/2018
+
+VARNA is running in Jalview in a browser. 
+
+The only capability not enabled is the "duplicate" menu item. 
+This is because SwingJS does not implement serialization.
+1/10/2018
+
+fixes VueUI handling of JFileChooser and JColorChooser callbacks not using revised SelectedFile and SelectedColor property names
+implements blinking iterator when dragging to reposition RNA blob
+implements annotations 
+
+1/7/2018
+
+JTable implemented, including editing; needs better efficiency 
+Modal dialogs are working, including file open.
+Drag-and-drop of Files is working 
+ - note that the dropped File object has bytes field with data
+Animated interpolation working; switched to simple JTimer mechanism for Java and JavaScript
+
+1/2/2018
+
+Varna is running.
+modal JOptionPane implemented fully
+JColorChooser implemented fully
+JTable implemented; still some minor issues
+
+Modal dialogs are working, except for FileOpen.
+Popup menu is working.
+
+
+Issues
+======
+
+- JTable has minor issues:
+ - Headings are not shaded
+ - needs attention to higher efficiency 
+
+- DnD only implemented for files. 
+  - probably x,y coord are off - untested
+  - needs checking for isolated frames (works in applet)
+  
+
+Modifications for SwingJS
+=========================
+
+Search for "@j2sNative", "BH", or "SwingJS"
+
+
+VARNA.java 
+----------
+
+moved to fr.orsay.lri.varna (all SwingJS project files must be in packages)
+
+adds default RNA JavaScript:
+
+         if (!thisApplet.__Info.sequenceDBN) {
+          thisApplet.__Info.sequenceDBN = "GGGGCCAAUAUGGCCAUCC";
+          thisApplet.__Info.structureDBN = "((((((.....))))..))";
+          thisApplet.__Info.title = prompt("Title?","Hello RNA world, from SwingJS!");
+         } 
+
+
+
+fr.orsay.lri.varna.factories.RNAFactory
+---------------------------------------
+
+Cannot depend upon Java ArrayIndexOutOfBounds for trapping when testing formats
+
+JAVA fix: Removing unnecessary exception print stack traces during testing for formats
+JAVA fix: RNAFactory was not closing file reader
+
+
+
+fr.orsay.lri.varna.applications.VARNAEditor
+-------------------------------------------
+
+switched to RNAFactory.loadSecStr((File) o) for drag-drop allows passing byte data
+
+
+fr.orsay.lri.varna.applications.VARNAGUI
+----------------------------------------
+
+switched to RNAFactory.loadSecStr((File) o) for drag-drop allows passing byte data
+
+
+fr.orsay.lri.varna.controlers.ControleurBaseSpecialColorEditor
+--------------------------------------------------------------
+
+Since the editor is not modal, we have to catch the window hiding event 
+before closing the editor.
+
+
+
+fr.orsay.lri.varna.controlers.ControleurInterpolator
+----------------------------------------------------
+
+switch to JTimer for interpolation
+JavaScript uses 2-second delay; Java uses 15-second delay
+
+
+
+fr.orsay.lri.varna.views.PrinterTest.java
+-----------------------------------------
+
+simpler test that does not use java.awt.font.TextLayout, which is not implemented.
+
+
+
+fr.orsay.lri.varna.VarnaPanel.java
+----------------------------------
+
+now implements PropertyChangeListener for asynchronous callback.
+
+
+
+fr.orsay.lri.varna.views.VueUI.java
+------------------------------------
+
+All JOptionPane, JFileChooser, and JColorChooser action made asynchronous. 
+Basically, the results OK, CANCEL, YES, NO, CLOSED, and custom button index
+are delivered to instances of runnable via a PropertyChangeListener callback
+to the indicated parent frame. 
+
+Simple ERROR_OPTION and WARN_OPTION messages are handled via JavaScript Alert;
+fall back options for simple showConfirmDialog and showInputDialog are used
+automatically if the parent frame does not implement PropertyChangeListener. 
+
+Initial JavaScript-only return is:
+
+ for int-returning methods, NaN, 
+   testable as value != Math.floor(value), where value is an int, and
+ for Object-returning methods, an Object that implements UIResource,  
+   testable as event.getNewValue() instanceof UIResource. 
+This allows full compatibility in Java and JavaScript.
+
+
+See notes in fr.orsay.lri.varna.views.VueUI.java.
+
+
+fr.orsay.lri.varna.views.VueMenu.java
+-------------------------------------
+
+changes JLabel to JMenuItem - not 100% sure why that is necessary. 
+changes JSeparator to JPopupMenu.Separator
+
+
+
+fr.orsay.lri.varna.views.VueAbout.java
+--------------------------------------
+
+added simple JTimer for asynchronous animation
+added asynchronous callback modal option for JavaScript
+
diff --git a/src2/fr/orsay/lri/varna/VARNA.java b/src2/fr/orsay/lri/varna/VARNA.java
new file mode 100644 (file)
index 0000000..1f98d50
--- /dev/null
@@ -0,0 +1,260 @@
+package fr.orsay.lri.varna;
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+import java.awt.Component;
+import java.awt.GridLayout;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.JApplet;
+import javax.swing.JOptionPane;
+
+import fr.orsay.lri.varna.controlers.ControleurScriptParser;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.interfaces.InterfaceParameterLoader;
+import fr.orsay.lri.varna.models.VARNAConfigLoader;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+// @j2s issues -- see README_SWINGJS.txt
+
+public class VARNA extends JApplet implements InterfaceParameterLoader,DropTargetListener {
+       ArrayList<VARNAPanel> _vpl = null;
+       static{
+               /**
+                * 
+                * @j2sNative
+                * 
+                * 
+                * if (!thisApplet.__Info.sequenceDBN) {
+                *  thisApplet.__Info.sequenceDBN = "GGGGCCAAUAUGGCCAUCC";
+                *  thisApplet.__Info.structureDBN = "((((((.....))))..))";
+                *  thisApplet.__Info.title = "Hello RNA world, from SwingJS!";//prompt("Title?","Hello RNA world!");
+                * } 
+                * 
+                * 
+                * 
+                */             
+       }
+
+       
+//     private static final_long serialVersionUID = -2598221520127067670L;
+
+       public VARNA() {
+               super();
+       }
+
+       public void init() {
+               try {
+                       VARNAConfigLoader VARNAcfg = new VARNAConfigLoader(this);
+                       
+                       try {
+                               _vpl = VARNAcfg.createVARNAPanels();
+                               for (int i=0;i<_vpl.size();i++)
+                               {
+                                   new DropTarget(_vpl.get(i), this);
+                               }
+                       } catch (IOException e) {
+                               JOptionPane.showMessageDialog(this, e.getMessage(),
+                                               "VARNA Error", JOptionPane.ERROR_MESSAGE);
+                       } catch (ExceptionFileFormatOrSyntax e) {
+                               JOptionPane.showMessageDialog(this, e.getMessage(),
+                                               "VARNA Error", JOptionPane.ERROR_MESSAGE);
+                       } catch (ExceptionLoadingFailed e) {
+                               JOptionPane.showMessageDialog(this, e.getMessage(),
+                                               "VARNA Error", JOptionPane.ERROR_MESSAGE);
+                       }
+                       setLayout(new GridLayout(VARNAcfg.getNbColumns(), VARNAcfg
+                                       .getNbRows()));
+                       for (int i = 0; i < _vpl.size(); i++) {
+                               getContentPane().add(_vpl.get(i));
+                       }
+               } catch (ExceptionParameterError e) {
+                       VARNAPanel.errorDialogStatic(e, this);
+               } catch (ExceptionModeleStyleBaseSyntaxError e) {
+                       VARNAPanel.errorDialogStatic(e, this);
+               } catch (ExceptionNonEqualLength e) {
+                       VARNAPanel.errorDialogStatic(e, this);
+               }
+
+       }
+
+       public void start() {
+               //setVisible(true);
+               //repaint();
+               //getContentPane().setVisible(true);            
+               //getContentPane().repaint();           
+       }
+       
+       public void update() {
+               System.out.println("update");
+       }
+       
+       public String getParameterValue(String key, String def) {
+               if (getParameter(key) == null) {
+                       return def;
+               } else {
+                       return getParameter(key);
+               }
+       }
+
+       public String[][] getParameterInfo() {
+               return VARNAConfigLoader.getParameterInfo();
+       }
+       
+       public ArrayList<VARNAPanel> getPanels()
+       {
+               return _vpl;
+       }
+       
+       public String getSelection()
+       {
+               return getSelection(0);
+       }
+       
+       public String getSelection(int panel)
+       {
+               String result = "[";
+               VARNAPanel v = _vpl.get(panel);
+               List<Integer> l = v.getSelectionIndices();
+               for(int i=0;i<l.size();i++)
+               {
+                       int n = l.get(i);
+                       if (i>0)
+                       {result += ",";}
+                       result += n;
+                       
+               }
+               result += "]";
+               return result;
+       }
+
+       public void runScript(String script)
+       {
+               if (_vpl.size()>0)
+               { 
+                       VARNAPanel _vp = _vpl.get(0);
+                       try {
+                               ControleurScriptParser.executeScript(_vp, script);
+                       } catch (Exception e) {
+                               e.printStackTrace();
+                       }
+               }
+       }
+       
+       
+       public void setRNA(String seq, String str) 
+       {
+               if (_vpl.size()>0)
+               { 
+                       try {
+                               _vpl.get(0).drawRNA(seq, str);
+                       } catch (ExceptionNonEqualLength e) {
+                               e.printStackTrace();
+                       } 
+               }
+       }
+
+       public void setSmoothedRNA(String seq, String str) 
+       {
+               if (_vpl.size()>0)
+               { 
+                       try {
+                                 
+                                 _vpl.get(0).drawRNAInterpolated(seq, str);
+                                 _vpl.get(0).repaint();
+                       } catch (ExceptionNonEqualLength e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       } 
+               }
+       }
+
+       public void dragEnter(DropTargetDragEvent arg0) {
+       }
+
+       public void dragExit(DropTargetEvent arg0) {
+       }
+
+       public void dragOver(DropTargetDragEvent arg0) {
+       }
+
+       public void drop(DropTargetDropEvent dtde) 
+       {
+         try 
+         {
+           Transferable tr = dtde.getTransferable();
+           DataFlavor[] flavors = tr.getTransferDataFlavors();
+           for (int i = 0; i < flavors.length; i++) 
+           {
+             if (flavors[i].isFlavorJavaFileListType()) 
+             {
+                 dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
+                 List list = (List) tr.getTransferData(flavors[i]);
+                 for (int j = 0; j < list.size(); j++) 
+                 {
+                         Object o = list.get(j);
+                         if (dtde.getSource() instanceof DropTarget)
+                         {
+                                 DropTarget dt = (DropTarget) dtde.getSource();
+                                 Component c = dt.getComponent();
+                                 if (c instanceof VARNAPanel)
+                                 {
+                                         VARNAPanel vp = (VARNAPanel) c;
+                                         // BH -- in JavaScript, the File object has a .bytes 
+                                         // property that we need to maintain.
+                                         //String path = o.toString();
+                                         vp.loadFile((File) o,true);
+                                         //vp.repaint(); BH unnecessary
+                                 }
+                         }
+                 }
+                 dtde.dropComplete(true);
+                 return;
+             }
+           }
+        dtde.rejectDrop();
+        } 
+        catch (Exception e) 
+        {
+                e.printStackTrace();
+            dtde.rejectDrop();
+         }
+       }
+
+       public void dropActionChanged(DropTargetDragEvent arg0) {
+       }
+
+       
+}
+
diff --git a/src2/fr/orsay/lri/varna/VARNAPanel.java b/src2/fr/orsay/lri/varna/VARNAPanel.java
new file mode 100644 (file)
index 0000000..3ab14b7
--- /dev/null
@@ -0,0 +1,4528 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2012  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.9.
+ VARNA version 3.9 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.9 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+
+/*
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+ software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+ to take away your freedom to share and change the works.  By contrast,
+ the GNU General Public License is intended to guarantee your freedom to
+ share and change all versions of a program--to make sure it remains free
+ software for all its users.  We, the Free Software Foundation, use the
+ GNU General Public License for most of our software; it applies also to
+ any other work released this way by its authors.  You can apply it to
+ your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+ price.  Our General Public Licenses are designed to make sure that you
+ have the freedom to distribute copies of free software (and charge for
+ them if you wish), that you receive source code or can get it if you
+ want it, that you can change the software or use pieces of it in new
+ free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+ these rights or asking you to surrender the rights.  Therefore, you have
+ certain responsibilities if you distribute copies of the software, or if
+ you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+ gratis or for a fee, you must pass on to the recipients the same
+ freedoms that you received.  You must make sure that they, too, receive
+ or can get the source code.  And you must show them these terms so they
+ know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+ (1) assert copyright on the software, and (2) offer you this License
+ giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+ that there is no warranty for this free software.  For both users' and
+ authors' sake, the GPL requires that modified versions be marked as
+ changed, so that their problems will not be attributed erroneously to
+ authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+ modified versions of the software inside them, although the manufacturer
+ can do so.  This is fundamentally incompatible with the aim of
+ protecting users' freedom to change the software.  The systematic
+ pattern of such abuse occurs in the area of products for individuals to
+ use, which is precisely where it is most unacceptable.  Therefore, we
+ have designed this version of the GPL to prohibit the practice for those
+ products.  If such problems arise substantially in other domains, we
+ stand ready to extend this provision to those domains in future versions
+ of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+ States should not allow patents to restrict development and use of
+ software on general-purpose computers, but in those that do, we wish to
+ avoid the special danger that patents applied to a free program could
+ make it effectively proprietary.  To prevent this, the GPL assures that
+ patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+ modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+ works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+ License.  Each licensee is addressed as "you".  "Licensees" and
+ "recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+ in a fashion requiring copyright permission, other than the making of an
+ exact copy.  The resulting work is called a "modified version" of the
+ earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+ on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+ permission, would make you directly or secondarily liable for
+ infringement under applicable copyright law, except executing it on a
+ computer or modifying a private copy.  Propagation includes copying,
+ distribution (with or without modification), making available to the
+ public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+ parties to make or receive copies.  Mere interaction with a user through
+ a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+ to the extent that it includes a convenient and prominently visible
+ feature that (1) displays an appropriate copyright notice, and (2)
+ tells the user that there is no warranty for the work (except to the
+ extent that warranties are provided), that licensees may convey the
+ work under this License, and how to view a copy of this License.  If
+ the interface presents a list of user commands or options, such as a
+ menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+ for making modifications to it.  "Object code" means any non-source
+ form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+ standard defined by a recognized standards body, or, in the case of
+ interfaces specified for a particular programming language, one that
+ is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+ than the work as a whole, that (a) is included in the normal form of
+ packaging a Major Component, but which is not part of that Major
+ Component, and (b) serves only to enable use of the work with that
+ Major Component, or to implement a Standard Interface for which an
+ implementation is available to the public in source code form.  A
+ "Major Component", in this context, means a major essential component
+ (kernel, window system, and so on) of the specific operating system
+ (if any) on which the executable work runs, or a compiler used to
+ produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+ the source code needed to generate, install, and (for an executable
+ work) run the object code and to modify the work, including scripts to
+ control those activities.  However, it does not include the work's
+ System Libraries, or general-purpose tools or generally available free
+ programs which are used unmodified in performing those activities but
+ which are not part of the work.  For example, Corresponding Source
+ includes interface definition files associated with source files for
+ the work, and the source code for shared libraries and dynamically
+ linked subprograms that the work is specifically designed to require,
+ such as by intimate data communication or control flow between those
+ subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+ can regenerate automatically from other parts of the Corresponding
+ Source.
+
+ The Corresponding Source for a work in source code form is that
+ same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+ copyright on the Program, and are irrevocable provided the stated
+ conditions are met.  This License explicitly affirms your unlimited
+ permission to run the unmodified Program.  The output from running a
+ covered work is covered by this License only if the output, given its
+ content, constitutes a covered work.  This License acknowledges your
+ rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+ convey, without conditions so long as your license otherwise remains
+ in force.  You may convey covered works to others for the sole purpose
+ of having them make modifications exclusively for you, or provide you
+ with facilities for running those works, provided that you comply with
+ the terms of this License in conveying all material for which you do
+ not control copyright.  Those thus making or running the covered works
+ for you must do so exclusively on your behalf, under your direction
+ and control, on terms that prohibit them from making any copies of
+ your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+ the conditions stated below.  Sublicensing is not allowed; section 10
+ makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+ measure under any applicable law fulfilling obligations under article
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
+ similar laws prohibiting or restricting circumvention of such
+ measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+ circumvention of technological measures to the extent such circumvention
+ is effected by exercising rights under this License with respect to
+ the covered work, and you disclaim any intention to limit operation or
+ modification of the work as a means of enforcing, against the work's
+ users, your or third parties' legal rights to forbid circumvention of
+ technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+ receive it, in any medium, provided that you conspicuously and
+ appropriately publish on each copy an appropriate copyright notice;
+ keep intact all notices stating that this License and any
+ non-permissive terms added in accord with section 7 apply to the code;
+ keep intact all notices of the absence of any warranty; and give all
+ recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+ and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+ produce it from the Program, in the form of source code under the
+ terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7.  This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy.  This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged.  This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+ works, which are not by their nature extensions of the covered work,
+ and which are not combined with it such as to form a larger program,
+ in or on a volume of a storage or distribution medium, is called an
+ "aggregate" if the compilation and its resulting copyright are not
+ used to limit the access or legal rights of the compilation's users
+ beyond what the individual works permit.  Inclusion of a covered work
+ in an aggregate does not cause this License to apply to the other
+ parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+ of sections 4 and 5, provided that you also convey the
+ machine-readable Corresponding Source under the terms of this License,
+ in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source.  This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge.  You need not require recipients to copy the
+ Corresponding Source along with the object code.  If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source.  Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+ from the Corresponding Source as a System Library, need not be
+ included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+ tangible personal property which is normally used for personal, family,
+ or household purposes, or (2) anything designed or sold for incorporation
+ into a dwelling.  In determining whether a product is a consumer product,
+ doubtful cases shall be resolved in favor of coverage.  For a particular
+ product received by a particular user, "normally used" refers to a
+ typical or common use of that class of product, regardless of the status
+ of the particular user or of the way in which the particular user
+ actually uses, or expects or is expected to use, the product.  A product
+ is a consumer product regardless of whether the product has substantial
+ commercial, industrial or non-consumer uses, unless such uses represent
+ the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+ procedures, authorization keys, or other information required to install
+ and execute modified versions of a covered work in that User Product from
+ a modified version of its Corresponding Source.  The information must
+ suffice to ensure that the continued functioning of the modified object
+ code is in no case prevented or interfered with solely because
+ modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+ specifically for use in, a User Product, and the conveying occurs as
+ part of a transaction in which the right of possession and use of the
+ User Product is transferred to the recipient in perpetuity or for a
+ fixed term (regardless of how the transaction is characterized), the
+ Corresponding Source conveyed under this section must be accompanied
+ by the Installation Information.  But this requirement does not apply
+ if neither you nor any third party retains the ability to install
+ modified object code on the User Product (for example, the work has
+ been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+ requirement to continue to provide support service, warranty, or updates
+ for a work that has been modified or installed by the recipient, or for
+ the User Product in which it has been modified or installed.  Access to a
+ network may be denied when the modification itself materially and
+ adversely affects the operation of the network or violates the rules and
+ protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+ in accord with this section must be in a format that is publicly
+ documented (and with an implementation available to the public in
+ source code form), and must require no special password or key for
+ unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+ License by making exceptions from one or more of its conditions.
+ Additional permissions that are applicable to the entire Program shall
+ be treated as though they were included in this License, to the extent
+ that they are valid under applicable law.  If additional permissions
+ apply only to part of the Program, that part may be used separately
+ under those permissions, but the entire Program remains governed by
+ this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+ remove any additional permissions from that copy, or from any part of
+ it.  (Additional permissions may be written to require their own
+ removal in certain cases when you modify the work.)  You may place
+ additional permissions on material, added by you to a covered work,
+ for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+ add to a covered work, you may (if authorized by the copyright holders of
+ that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+ restrictions" within the meaning of section 10.  If the Program as you
+ received it, or any part of it, contains a notice stating that it is
+ governed by this License along with a term that is a further
+ restriction, you may remove that term.  If a license document contains
+ a further restriction but permits relicensing or conveying under this
+ License, you may add to a covered work material governed by the terms
+ of that license document, provided that the further restriction does
+ not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+ must place, in the relevant source files, a statement of the
+ additional terms that apply to those files, or a notice indicating
+ where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+ form of a separately written license, or stated as exceptions;
+ the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+ provided under this License.  Any attempt otherwise to propagate or
+ modify it is void, and will automatically terminate your rights under
+ this License (including any patent licenses granted under the third
+ paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+ license from a particular copyright holder is reinstated (a)
+ provisionally, unless and until the copyright holder explicitly and
+ finally terminates your license, and (b) permanently, if the copyright
+ holder fails to notify you of the violation by some reasonable means
+ prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+ reinstated permanently if the copyright holder notifies you of the
+ violation by some reasonable means, this is the first time you have
+ received notice of violation of this License (for any work) from that
+ copyright holder, and you cure the violation prior to 30 days after
+ your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+ licenses of parties who have received copies or rights from you under
+ this License.  If your rights have been terminated and not permanently
+ reinstated, you do not qualify to receive new licenses for the same
+ material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+ run a copy of the Program.  Ancillary propagation of a covered work
+ occurring solely as a consequence of using peer-to-peer transmission
+ to receive a copy likewise does not require acceptance.  However,
+ nothing other than this License grants you permission to propagate or
+ modify any covered work.  These actions infringe copyright if you do
+ not accept this License.  Therefore, by modifying or propagating a
+ covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+ receives a license from the original licensors, to run, modify and
+ propagate that work, subject to this License.  You are not responsible
+ for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+ organization, or substantially all assets of one, or subdividing an
+ organization, or merging organizations.  If propagation of a covered
+ work results from an entity transaction, each party to that
+ transaction who receives a copy of the work also receives whatever
+ licenses to the work the party's predecessor in interest had or could
+ give under the previous paragraph, plus a right to possession of the
+ Corresponding Source of the work from the predecessor in interest, if
+ the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+ rights granted or affirmed under this License.  For example, you may
+ not impose a license fee, royalty, or other charge for exercise of
+ rights granted under this License, and you may not initiate litigation
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
+ any patent claim is infringed by making, using, selling, offering for
+ sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+ License of the Program or a work on which the Program is based.  The
+ work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+ owned or controlled by the contributor, whether already acquired or
+ hereafter acquired, that would be infringed by some manner, permitted
+ by this License, of making, using, or selling its contributor version,
+ but do not include claims that would be infringed only as a
+ consequence of further modification of the contributor version.  For
+ purposes of this definition, "control" includes the right to grant
+ patent sublicenses in a manner consistent with the requirements of
+ this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+ patent license under the contributor's essential patent claims, to
+ make, use, sell, offer for sale, import and otherwise run, modify and
+ propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+ agreement or commitment, however denominated, not to enforce a patent
+ (such as an express permission to practice a patent or covenant not to
+ sue for patent infringement).  To "grant" such a patent license to a
+ party means to make such an agreement or commitment not to enforce a
+ patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+ and the Corresponding Source of the work is not available for anyone
+ to copy, free of charge and under the terms of this License, through a
+ publicly available network server or other readily accessible means,
+ then you must either (1) cause the Corresponding Source to be so
+ available, or (2) arrange to deprive yourself of the benefit of the
+ patent license for this particular work, or (3) arrange, in a manner
+ consistent with the requirements of this License, to extend the patent
+ license to downstream recipients.  "Knowingly relying" means you have
+ actual knowledge that, but for the patent license, your conveying the
+ covered work in a country, or your recipient's use of the covered work
+ in a country, would infringe one or more identifiable patents in that
+ country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+ arrangement, you convey, or propagate by procuring conveyance of, a
+ covered work, and grant a patent license to some of the parties
+ receiving the covered work authorizing them to use, propagate, modify
+ or convey a specific copy of the covered work, then the patent license
+ you grant is automatically extended to all recipients of the covered
+ work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+ the scope of its coverage, prohibits the exercise of, or is
+ conditioned on the non-exercise of one or more of the rights that are
+ specifically granted under this License.  You may not convey a covered
+ work if you are a party to an arrangement with a third party that is
+ in the business of distributing software, under which you make payment
+ to the third party based on the extent of your activity of conveying
+ the work, and under which the third party grants, to any of the
+ parties who would receive the covered work from you, a discriminatory
+ patent license (a) in connection with copies of the covered work
+ conveyed by you (or copies made from those copies), or (b) primarily
+ for and in connection with specific products or compilations that
+ contain the covered work, unless you entered into that arrangement,
+ or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+ any implied license or other defenses to infringement that may
+ otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+ otherwise) that contradict the conditions of this License, they do not
+ excuse you from the conditions of this License.  If you cannot convey a
+ covered work so as to satisfy simultaneously your obligations under this
+ License and any other pertinent obligations, then as a consequence you may
+ not convey it at all.  For example, if you agree to terms that obligate you
+ to collect a royalty for further conveying from those to whom you convey
+ the Program, the only way you could satisfy both those terms and this
+ License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+ permission to link or combine any covered work with a work licensed
+ under version 3 of the GNU Affero General Public License into a single
+ combined work, and to convey the resulting work.  The terms of this
+ License will continue to apply to the part which is the covered work,
+ but the special requirements of the GNU Affero General Public License,
+ section 13, concerning interaction through a network will apply to the
+ combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+ the GNU General Public License from time to time.  Such new versions will
+ be similar in spirit to the present version, but may differ in detail to
+ address new problems or concerns.
+
+ Each version is given a distinguishing version number.  If the
+ Program specifies that a certain numbered version of the GNU General
+ Public License "or any later version" applies to it, you have the
+ option of following the terms and conditions either of that numbered
+ version or of any later version published by the Free Software
+ Foundation.  If the Program does not specify a version number of the
+ GNU General Public License, you may choose any version ever published
+ by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+ versions of the GNU General Public License can be used, that proxy's
+ public statement of acceptance of a version permanently authorizes you
+ to choose that version for the Program.
+
+ Later license versions may give you additional or different
+ permissions.  However, no additional obligations are imposed on any
+ author or copyright holder as a result of your choosing to follow a
+ later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+ APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+ IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+ above cannot be given local legal effect according to their terms,
+ reviewing courts shall apply local law that most closely approximates
+ an absolute waiver of all civil liability in connection with the
+ Program, unless a warranty or assumption of liability accompanies a
+ copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+ */
+
+package fr.orsay.lri.varna;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.Shape;
+import java.awt.Stroke;
+import java.awt.event.MouseEvent;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Hashtable;
+import java.util.Set;
+
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.undo.UndoManager;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.sax.SAXTransformerFactory;
+import javax.xml.transform.sax.TransformerHandler;
+import javax.xml.transform.stream.StreamResult;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.controlers.ControleurBlinkingThread;
+import fr.orsay.lri.varna.controlers.ControleurClicMovement;
+import fr.orsay.lri.varna.controlers.ControleurDraggedMolette;
+import fr.orsay.lri.varna.controlers.ControleurInterpolator;
+import fr.orsay.lri.varna.controlers.ControleurMolette;
+import fr.orsay.lri.varna.controlers.ControleurVARNAPanelKeys;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNABasesListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNARNAListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNASelectionListener;
+import fr.orsay.lri.varna.models.BaseList;
+import fr.orsay.lri.varna.models.FullBackup;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.export.SwingGraphics;
+import fr.orsay.lri.varna.models.export.VueVARNAGraphics;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBackbone;
+import fr.orsay.lri.varna.models.rna.ModeleBackboneElement.BackboneType;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleBasesComparison;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.utils.VARNASessionParser;
+import fr.orsay.lri.varna.views.VueMenu;
+import fr.orsay.lri.varna.views.VueUI;
+
+/**
+ * 
+ * BH j2s SwingJS Added PropertyChangeListener for returns from VueUI.  
+ * 
+ *  
+ *  
+ * 
+ * The RNA 2D Panel is a lightweight component that allows for an automatic
+ * basic drawing of an RNA secondary structures. The drawing algorithms do not
+ * ensure a non-overlapping drawing of helices, thus it is possible to "spin the
+ * helices" through a click-and-drag approach. A typical usage of the class from
+ * within the constructor of a <code>JFrame</code> would be the following:<br/>
+ * <code>
+ * &nbsp;&nbsp;VARNAPanel _rna = new VARNAPanel("CCCCAUAUGGGGACC","((((....))))...");<br />
+ * &nbsp;&nbsp;this.getContentPane().add(_rna);
+ * </code>
+ * 
+ * @version 3.4
+ * @author Yann Ponty & Kevin Darty
+ * 
+ */
+
+public class VARNAPanel extends JPanel implements PropertyChangeListener {
+       
+       /**
+        * SwingJS uses a PropertyChangeEvent to signal that a pseudo-modal dialog has been closed.
+        *   
+        * @param event
+        */
+       @Override
+       public void propertyChange(PropertyChangeEvent event) {
+               Object val = event.getNewValue();
+               switch (event.getPropertyName()) {
+               case "value":
+                       _UI.onDialogReturn(val == null ? JOptionPane.CLOSED_OPTION : ((Integer) val).intValue());
+                       return;
+               case "SelectedFile":
+               case "SelectedColor":
+               case "inputValue":
+                       _UI.onDialogReturn(val);
+                       break;
+               }
+       }
+
+       
+       private static final long serialVersionUID = 8194421570308956001L;
+
+       private RNA _RNA = new RNA();
+
+       private boolean _debug = false;
+
+       private VARNAConfig _conf = new VARNAConfig();
+
+       private ArrayList<InterfaceVARNAListener> _VARNAListeners = new ArrayList<InterfaceVARNAListener>();
+       private ArrayList<InterfaceVARNASelectionListener> _selectionListeners = new ArrayList<InterfaceVARNASelectionListener>();
+       private ArrayList<InterfaceVARNARNAListener> _RNAListeners = new ArrayList<InterfaceVARNARNAListener>();
+       private ArrayList<InterfaceVARNABasesListener> _basesListeners = new ArrayList<InterfaceVARNABasesListener>();
+
+       UndoManager _manager;
+
+       // private boolean _foldMode = true;
+
+       private Point2D.Double[] _realCoords = new Point2D.Double[0];
+       private Point2D.Double[] _realCenters = new Point2D.Double[0];
+       private double _scaleFactor = 1.0;
+       private Point2D.Double _offsetPanel = new Point2D.Double();
+       private Point2D.Double _offsetRNA = new Point2D.Double();
+
+       private double _offX;
+       private double _offY;
+
+       private ControleurBlinkingThread _blink;
+       private BaseList _selectedBases = new BaseList("selection");
+       private ArrayList<ModeleBase> _backupSelection = new ArrayList<ModeleBase>();
+       private Integer _nearestBase = null;
+       private Point2D.Double _lastSelectedCoord = new Point2D.Double(0.0, 0.0);
+
+       private Point2D.Double _linkOrigin = null;
+       private Point2D.Double _linkDestination = null;
+
+       private Rectangle _selectionRectangle = null;
+
+       private boolean _highlightAnnotation = false;
+
+       private int _titleHeight;
+       private Dimension _border = new Dimension(0, 0);
+
+       private boolean _drawBBox = false;
+       private boolean _drawBorder = false;
+
+       // private Point _positionRelativeSouris;
+       private Point _translation;
+       private boolean _horsCadre;
+       private boolean _premierAffichage;
+
+       private ControleurInterpolator _interpolator;
+       /**
+        * If comparison mode is TRUE (ON), then the application will be used to
+        * display a super-structure resulting on an RNA secondary structure
+        * comparison. Else, the application is used by default.
+        */
+
+       private VueMenu _popup = new VueMenu(this);
+
+       private VueUI _UI = new VueUI(this);
+
+       private TextAnnotation _selectedAnnotation;
+
+       /**
+        * Creates an RNA 2D panel with initially displays the empty structure.
+        * 
+        * @throws ExceptionNonEqualLength
+        * 
+        */
+       public VARNAPanel() {
+               init();
+               drawRNA();
+       }
+
+       /**
+        * Creates an RNA 2D panel, and creates and displays an RNA coupled with its
+        * secondary structure formatted as a well-balanced parenthesis with dots
+        * word (DBN format).
+        * 
+        * @param seq
+        *            The raw nucleotide sequence
+        * @param str
+        *            The secondary structure in DBN format
+        * @throws ExceptionNonEqualLength
+        */
+
+       public VARNAPanel(String seq, String str) throws ExceptionNonEqualLength {
+               this(seq, str, RNA.DRAW_MODE_RADIATE);
+       }
+
+       /**
+        * Creates a VARNAPanel instance, and creates and displays an RNA coupled
+        * with its secondary structure formatted as a well-balanced parenthesis
+        * with dots word (DBN format). Allows the user to choose the drawing
+        * algorithm to be used.
+        * 
+        * @param seq
+        *            The raw nucleotide sequence
+        * @param str
+        *            The secondary structure in DBN format
+        * @param drawMode
+        *            The drawing mode
+        * @throws ExceptionNonEqualLength
+        * @see RNA#DRAW_MODE_RADIATE
+        * @see RNA#DRAW_MODE_CIRCULAR
+        * @see RNA#DRAW_MODE_NAVIEW
+        */
+       public VARNAPanel(String seq, String str, int drawMode)
+                       throws ExceptionNonEqualLength {
+               this(seq, str, drawMode, "");
+       }
+
+       public VARNAPanel(Reader r) throws ExceptionNonEqualLength,
+                       ExceptionFileFormatOrSyntax {
+               this(r, RNA.DRAW_MODE_RADIATE);
+       }
+
+       public VARNAPanel(Reader r, int drawMode) throws ExceptionNonEqualLength,
+                       ExceptionFileFormatOrSyntax {
+               this(r, drawMode, "");
+       }
+
+       public VARNAPanel(Reader r, int drawMode, String title)
+                       throws ExceptionNonEqualLength, ExceptionFileFormatOrSyntax {
+               init();
+               drawRNA(r, drawMode);
+               setTitle(title);
+       }
+
+       public void setOriginLink(Point2D.Double p) {
+               _linkOrigin = (p);
+       }
+
+       public void setDestinationLink(Point2D.Double p) {
+               _linkDestination = (p);
+       }
+
+       public void removeLink() {
+               _linkOrigin = null;
+               _linkDestination = null;
+       }
+
+       /**
+        * Creates a VARNAPanel instance, and displays an RNA.
+        * 
+        * @param r
+        *            The RNA to be displayed within this panel
+        */
+
+       public VARNAPanel(RNA r) {
+               showRNA(r);
+               init();
+       }
+
+       /**
+        * Creates a VARNAPanel instance, and creates and displays an RNA coupled
+        * with its secondary structure formatted as a well-balanced parenthesis
+        * with dots word (DBN format). Allows the user to choose the drawing
+        * algorithm to be used. Additionally, sets the panel's title.
+        * 
+        * @param seq
+        *            The raw nucleotide sequence
+        * @param str
+        *            The secondary structure in DBN format
+        * @param drawMode
+        *            The drawing mode
+        * @param title
+        *            The panel title
+        * @throws ExceptionNonEqualLength
+        * @see RNA#DRAW_MODE_CIRCULAR
+        * @see RNA#DRAW_MODE_RADIATE
+        * @see RNA#DRAW_MODE_NAVIEW
+        */
+
+       public VARNAPanel(String seq, String str, int drawMode, String title)
+                       throws ExceptionNonEqualLength {
+               drawRNA(seq, str, drawMode);
+               init();
+               setTitle(title);
+               // VARNASecDraw._vp = this;
+       }
+
+       public VARNAPanel(String seq1, String struct1, String seq2, String struct2,
+                       int drawMode, String title) {
+               _conf._comparisonMode = true;
+               drawRNA(seq1, struct1, seq2, struct2, drawMode);
+               init();
+               setTitle(title);
+       }
+
+       private void init() {
+               setBackground(VARNAConfig.DEFAULT_BACKGROUND_COLOR);
+               _manager = new UndoManager();
+               _manager.setLimit(10000);
+               _UI.addUndoableEditListener(_manager);
+
+               _blink = new ControleurBlinkingThread(this,
+                               ControleurBlinkingThread.DEFAULT_FREQUENCY, 0, 1.0, 0.0, 0.2);
+               _blink.start();
+
+               _premierAffichage = true;
+               _translation = new Point(0, 0);
+
+               _horsCadre = false;
+               this.setFont(_conf._fontBasesGeneral);
+
+               // ajout des controleurs au VARNAPanel
+               ControleurClicMovement controleurClicMovement = new ControleurClicMovement(
+                               this);
+               this.addMouseListener(controleurClicMovement);
+               this.addMouseMotionListener(controleurClicMovement);
+               this.addMouseWheelListener(new ControleurMolette(this));
+
+               ControleurDraggedMolette ctrlDraggedMolette = new ControleurDraggedMolette(
+                               this);
+               this.addMouseMotionListener(ctrlDraggedMolette);
+               this.addMouseListener(ctrlDraggedMolette);
+
+               ControleurVARNAPanelKeys ctrlKey = new ControleurVARNAPanelKeys(this);
+               this.addKeyListener(ctrlKey);
+               this.addFocusListener(ctrlKey);
+
+               _interpolator = new ControleurInterpolator(this);
+               /**
+                * 
+                * BH SwingJS do not start this thread
+                * 
+                * @j2sNative 
+                */
+               {
+               _interpolator.start();
+               }
+
+       }
+
+       public void undo() {
+               if (_manager.canUndo())
+                       _manager.undo();
+       }
+
+       public void redo() {
+               if (_manager.canRedo())
+                       _manager.redo();
+       }
+
+       /**
+        * Sets the new style of the title font.
+        * 
+        * @param newStyle
+        *            An int that describes the new font style ("PLAIN","BOLD",
+        *            "BOLDITALIC", or "ITALIC")
+        */
+       public void setTitleFontStyle(int newStyle) {
+               _conf._titleFont = _conf._titleFont.deriveFont(newStyle);
+               updateTitleHeight();
+       }
+
+       /**
+        * Sets the new size of the title font.
+        * 
+        * @param newSize
+        *            The new size of the title font
+        */
+       public void setTitleFontSize(float newSize) {
+               //System.err.println("Applying title size "+newSize);
+               _conf._titleFont = _conf._titleFont.deriveFont(newSize);
+               updateTitleHeight();
+       }
+
+       /**
+        * Sets the new font family to be used for the title. Available fonts are
+        * system-specific, yet it seems that "Arial", "Dialog", and "MonoSpaced"
+        * are almost always available.
+        * 
+        * @param newFamily
+        *            New font family used for the title
+        */
+       public void setTitleFontFamily(String newFamily) {
+               _conf._titleFont = new Font(newFamily, _conf._titleFont.getStyle(),
+                               _conf._titleFont.getSize());
+               updateTitleHeight();
+       }
+
+       /**
+        * Sets the color to be used for the title.
+        * 
+        * @param newColor
+        *            A color used to draw the title
+        */
+       public void setTitleFontColor(Color newColor) {
+               _conf._titleColor = newColor;
+               updateTitleHeight();
+       }
+
+       /**
+        * Sets the font size for displaying bases
+        * 
+        * @param size
+        *            Font size for base caption
+        */
+
+       public void setBaseFontSize(Float size) {
+               _conf._fontBasesGeneral = _conf._fontBasesGeneral.deriveFont(size);
+       }
+
+       /**
+        * Sets the font size for displaying base numbers
+        * 
+        * @param size
+        *            Font size for base numbers
+        */
+
+       public void setNumbersFontSize(Float size) {
+               _conf._numbersFont = _conf._numbersFont.deriveFont(size);
+       }
+
+       /**
+        * Sets the font style for displaying bases
+        * 
+        * @param style
+        *            An int that describes the new font style ("PLAIN","BOLD",
+        *            "BOLDITALIC", or "ITALIC")
+        */
+
+       public void setBaseFontStyle(int style) {
+               _conf._fontBasesGeneral = _conf._fontBasesGeneral.deriveFont(style);
+       }
+
+       private void updateTitleHeight() {
+               if (!getTitle().equals("")) {
+                       _titleHeight = (int) (_conf._titleFont.getSize() * 1.5);
+               } else {
+                       _titleHeight = 0;
+               }
+               if (Math.abs(this.getZoom() - 1) < .02) {
+                       _translation.y = (int) (-getTitleHeight() / 2.0);
+               }
+       }
+
+       /**
+        * Sets the panel's title, giving a short description of the RNA secondary
+        * structure.
+        * 
+        * @param title
+        *            The new title
+        */
+       public void setTitle(String title) {
+               _RNA.setName(title);
+               updateTitleHeight();
+       }
+
+       /**
+        * Sets the distance between consecutive base numbers. Please notice that :
+        * <ul>
+        * <li>The first and last base are always numbered</li>
+        * <li>The numbering is based on the base numbers, not on the indices. So
+        * base numbers may appear more frequently than expected if bases are
+        * skipped</li>
+        * <li>The periodicity is measured starting from 0. This means that for a
+        * period of 10 and bases numbered from 1 to 52, the base numbers
+        * [1,10,20,30,40,50,52] will be drawn.</li>
+        * </ul>
+        * 
+        * @param n
+        *            New numbering period
+        */
+       public void setNumPeriod(int n) {
+               _conf._numPeriod = n;
+       }
+
+       /**
+        * Returns the current numbering period. Please notice that :
+        * <ul>
+        * <li>The first and last base are always numbered</li>
+        * <li>The numbering is based on the base numbers, not on the indices. So
+        * base numbers may appear more frequently than expected if bases are
+        * skipped</li>
+        * <li>The periodicity is measured starting from 0. This means that for a
+        * period of 10 and bases numbered from 1 to 52, the base numbers
+        * [1,10,20,30,40,50,52] will be drawn.</li>
+        * </ul>
+        * 
+        * @return Current numbering period
+        */
+       public int getNumPeriod() {
+               return _conf._numPeriod;
+       }
+
+       private void setScaleFactor(double d) {
+               _scaleFactor = d;
+       }
+
+       private double getScaleFactor() {
+               return _scaleFactor;
+       }
+
+       private void setAutoFit(boolean fit) {
+               _conf._autoFit = fit;
+               repaint();
+       }
+
+       public void lockScrolling() {
+               setAutoFit(false);
+               setAutoCenter(false);
+       }
+
+       public void unlockScrolling() {
+               setAutoFit(true);
+               setAutoCenter(true);
+       }
+
+       private void drawStringOutline(VueVARNAGraphics g2D, String res, double x,
+                       double y, double margin) {
+               Dimension d = g2D.getStringDimension(res);
+               x -= (double) d.width / 2.0;
+               y += (double) d.height / 2.0;
+               g2D.setColor(Color.GRAY);
+               g2D.setSelectionStroke();
+               g2D.drawRect((x - margin), (y - d.height - margin),
+                               (d.width + 2.0 * margin), (d.height + 2.0 * margin));
+       }
+
+       private void drawSymbol(VueVARNAGraphics g2D, double posx, double posy,
+                       double normx, double normy, double radius, boolean isCIS,
+                       ModeleBP.Edge e) {
+               Color bck = g2D.getColor();
+               switch (e) {
+               case WC:
+                       if (isCIS) {
+                               g2D.setColor(bck);
+                               g2D.fillCircle((posx - (radius) / 2.0),
+                                               (posy - (radius) / 2.0), radius);
+                               g2D.drawCircle((posx - (radius) / 2.0),
+                                               (posy - (radius) / 2.0), radius);
+                       } else {
+                               g2D.setColor(Color.white);
+                               g2D.fillCircle(posx - (radius) / 2.0, (posy - (radius) / 2.0),
+                                               (radius));
+                               g2D.setColor(bck);
+                               g2D.drawCircle((posx - (radius) / 2.0),
+                                               (posy - (radius) / 2.0), (radius));
+                       }
+                       break;
+               case HOOGSTEEN: {
+                       GeneralPath p2 = new GeneralPath();
+                       radius /= 1.05;
+                       p2.moveTo((float) (posx - radius * normx / 2.0 - radius * normy
+                                       / 2.0), (float) (posy - radius * normy / 2.0 + radius
+                                       * normx / 2.0));
+                       p2.lineTo((float) (posx + radius * normx / 2.0 - radius * normy
+                                       / 2.0), (float) (posy + radius * normy / 2.0 + radius
+                                       * normx / 2.0));
+                       p2.lineTo((float) (posx + radius * normx / 2.0 + radius * normy
+                                       / 2.0), (float) (posy + radius * normy / 2.0 - radius
+                                       * normx / 2.0));
+                       p2.lineTo((float) (posx - radius * normx / 2.0 + radius * normy
+                                       / 2.0), (float) (posy - radius * normy / 2.0 - radius
+                                       * normx / 2.0));
+                       p2.closePath();
+
+                       if (isCIS) {
+                               g2D.setColor(bck);
+                               g2D.fill(p2);
+                               g2D.draw(p2);
+                       } else {
+                               g2D.setColor(Color.white);
+                               g2D.fill(p2);
+                               g2D.setColor(bck);
+                               g2D.draw(p2);
+                       }
+               }
+                       break;
+               case SUGAR: {
+                       double ix = radius * normx / 2.0;
+                       double iy = radius * normy / 2.0;
+                       double jx = radius * normy / 2.0;
+                       double jy = -radius * normx / 2.0;
+
+                       GeneralPath p2 = new GeneralPath();
+                       p2.moveTo((float) (posx - ix + jx), (float) (posy - iy + jy));
+                       p2.lineTo((float) (posx + ix + jx), (float) (posy + iy + jy));
+                       p2.lineTo((float) (posx - jx), (float) (posy - jy));
+                       p2.closePath();
+
+                       if (isCIS) {
+                               g2D.setColor(bck);
+                               g2D.fill(p2);
+                               g2D.draw(p2);
+                       } else {
+                               g2D.setColor(Color.white);
+                               g2D.fill(p2);
+                               g2D.setColor(bck);
+                               g2D.draw(p2);
+                       }
+               }
+                       break;
+               }
+               g2D.setColor(bck);
+       }
+
+       private void drawBasePairArc(VueVARNAGraphics g2D, int i, int j,
+                       Point2D.Double orig, Point2D.Double dest, double scaleFactor,
+                       ModeleBP style, double newRadius) {
+               double distance, coef;
+               if (j - i == 1)
+                       coef = getBPHeightIncrement() * 1.75;
+               else
+                       coef = getBPHeightIncrement();
+               distance = dest.x - orig.x;
+               switch (_conf._mainBPStyle) {
+               case LW: {
+                       double radiusCircle = ((RNA.BASE_PAIR_DISTANCE - _RNA.BASE_RADIUS) / 5.0)
+                                       * scaleFactor;
+                       if (style.isCanonical()) {
+                               if (style.isCanonicalGC()) {
+                                       if ((orig.x != dest.x) || (orig.y != dest.y)) {
+                                               g2D.drawArc((dest.x + orig.x) / 2., dest.y
+                                                               - scaleFactor * _RNA.BASE_RADIUS / 2.0,
+                                                               (distance - scaleFactor * _RNA.BASE_RADIUS
+                                                                               / 3.0), (distance * coef - scaleFactor
+                                                                               * _RNA.BASE_RADIUS / 3.0), 0, 180);
+                                               g2D.drawArc((dest.x + orig.x) / 2., dest.y
+                                                               - scaleFactor * _RNA.BASE_RADIUS / 2.0,
+                                                               (distance + scaleFactor * _RNA.BASE_RADIUS
+                                                                               / 3.0), (distance * coef + scaleFactor
+                                                                               * _RNA.BASE_RADIUS / 3.0), 0, 180);
+                                       }
+                               } else if (style.isCanonicalAU()) {
+                                       g2D.drawArc((dest.x + orig.x) / 2., dest.y - scaleFactor
+                                                       * _RNA.BASE_RADIUS / 2.0, (distance),
+                                                       (distance * coef), 0, 180);
+                               } else if (style.isWobbleUG()) {
+                                       Point2D.Double midtop = new Point2D.Double(
+                                                       (dest.x + orig.x) / 2., dest.y - distance * coef
+                                                                       / 2. - scaleFactor * _RNA.BASE_RADIUS / 2.0);
+                                       g2D.drawArc(midtop.x, dest.y - scaleFactor
+                                                       * _RNA.BASE_RADIUS / 2.0, (distance),
+                                                       (distance * coef), 0, 180);
+                                       drawSymbol(g2D, midtop.x, midtop.y, 1., 0., radiusCircle,
+                                                       false, ModeleBP.Edge.WC);
+                               } else {
+                                       Point2D.Double midtop = new Point2D.Double(
+                                                       (dest.x + orig.x) / 2., dest.y - distance * coef
+                                                                       / 2. - scaleFactor * _RNA.BASE_RADIUS / 2.0);
+                                       g2D.drawArc(midtop.x, dest.y - scaleFactor
+                                                       * _RNA.BASE_RADIUS / 2.0, (distance),
+                                                       (distance * coef), 0, 180);
+                                       drawSymbol(g2D, midtop.x, midtop.y, 1., 0., radiusCircle,
+                                                       style.isCIS(), style.getEdgePartner5());
+                               }
+                       } else {
+                               ModeleBP.Edge p1 = style.getEdgePartner5();
+                               ModeleBP.Edge p2 = style.getEdgePartner3();
+                               Point2D.Double midtop = new Point2D.Double(
+                                               (dest.x + orig.x) / 2., dest.y - distance * coef / 2.
+                                                               - scaleFactor * _RNA.BASE_RADIUS / 2.0);
+                               g2D.drawArc(midtop.x, dest.y - scaleFactor * _RNA.BASE_RADIUS
+                                               / 2.0, (distance), (distance * coef), 0, 180);
+                               if (p1 == p2) {
+                                       drawSymbol(g2D, midtop.x, midtop.y, 1., 0., radiusCircle,
+                                                       false, style.getEdgePartner5());
+                               } else {
+                                       drawSymbol(g2D, midtop.x - scaleFactor * _RNA.BASE_RADIUS,
+                                                       midtop.y, 1., 0., radiusCircle, style.isCIS(), p1);
+                                       drawSymbol(g2D, midtop.x + scaleFactor * _RNA.BASE_RADIUS,
+                                                       midtop.y, -1., 0., radiusCircle, style.isCIS(), p2);
+                               }
+                       }
+               }
+                       break;
+               case LW_ALT: {
+                       double radiusCircle = ((RNA.BASE_PAIR_DISTANCE - _RNA.BASE_RADIUS) / 5.0)
+                                       * scaleFactor;
+                       double distFromBaseCenter = DISTANCE_FACT*scaleFactor;
+                       orig = new Point2D.Double(orig.x,orig.y-(distFromBaseCenter+newRadius));
+                       dest = new Point2D.Double(dest.x,dest.y-(distFromBaseCenter+newRadius));
+                       if (style.isCanonical()) {
+                               if (style.isCanonicalGC()) {
+                                       if ((orig.x != dest.x) || (orig.y != dest.y)) {
+                                               g2D.drawArc((dest.x + orig.x) / 2., dest.y
+                                                               - scaleFactor * _RNA.BASE_RADIUS / 2.0,
+                                                               (distance - scaleFactor * _RNA.BASE_RADIUS
+                                                                               / 3.0), (distance * coef - scaleFactor
+                                                                               * _RNA.BASE_RADIUS / 3.0), 0, 180);
+                                               g2D.drawArc((dest.x + orig.x) / 2., dest.y
+                                                               - scaleFactor * _RNA.BASE_RADIUS / 2.0,
+                                                               (distance + scaleFactor * _RNA.BASE_RADIUS
+                                                                               / 3.0), (distance * coef + scaleFactor
+                                                                               * _RNA.BASE_RADIUS / 3.0), 0, 180);
+                                       }
+                               } else if (style.isCanonicalAU()) {
+                                       g2D.drawArc((dest.x + orig.x) / 2., dest.y - scaleFactor
+                                                       * _RNA.BASE_RADIUS / 2.0, (distance),
+                                                       (distance * coef), 0, 180);
+                               }
+                       } else {
+                               ModeleBP.Edge p1 = style.getEdgePartner5();
+                               ModeleBP.Edge p2 = style.getEdgePartner3();
+                               Point2D.Double midtop = new Point2D.Double(
+                                               (dest.x + orig.x) / 2., dest.y - distance * coef / 2.
+                                                               - scaleFactor * _RNA.BASE_RADIUS / 2.0);
+                               g2D.drawArc(midtop.x, dest.y - scaleFactor * _RNA.BASE_RADIUS
+                                               / 2.0, (distance), (distance * coef), 0, 180);
+                               drawSymbol(g2D, orig.x,
+                                                       orig.y-radiusCircle*.95, 1., 0., radiusCircle, style.isCIS(), p1);
+                               drawSymbol(g2D, dest.x,
+                                                       dest.y-radiusCircle*.95, -1., 0., radiusCircle, style.isCIS(), p2);
+                       }
+               }
+                       break;
+               default:
+                       g2D.drawArc((dest.x + orig.x) / 2., dest.y - scaleFactor
+                                       * _RNA.BASE_RADIUS / 2.0, (distance), (distance * coef), 0,
+                                       180);
+                       break;
+               }
+
+       }
+
+       public static double DISTANCE_FACT = 2.;
+
+       
+       private void drawBasePair(VueVARNAGraphics g2D, Point2D.Double orig,
+                       Point2D.Double dest, ModeleBP style, double newRadius,
+                       double scaleFactor) {
+
+               double dx = dest.x - orig.x;
+               double dy = dest.y - orig.y;
+               double dist = Math.sqrt((dest.x - orig.x) * (dest.x - orig.x)
+                               + (dest.y - orig.y) * (dest.y - orig.y));
+               dx /= dist;
+               dy /= dist;
+               double nx = -dy;
+               double ny = dx;
+               orig = new Point2D.Double(orig.x + newRadius * dx, orig.y + newRadius
+                               * dy);
+               dest = new Point2D.Double(dest.x - newRadius * dx, dest.y - newRadius
+                               * dy);
+               switch (_conf._mainBPStyle) {
+               case LW: {
+                       double radiusCircle = ((RNA.BASE_PAIR_DISTANCE - _RNA.BASE_RADIUS) / 5.0)
+                                       * scaleFactor;
+                       if (style.isCanonical()) {
+                               if (style.isCanonicalGC()) {
+                                       if ((orig.x != dest.x) || (orig.y != dest.y)) {
+                                               nx *= scaleFactor * _RNA.BASE_RADIUS / 4.0;
+                                               ny *= scaleFactor * _RNA.BASE_RADIUS / 4.0;
+                                               g2D.drawLine((orig.x + nx), (orig.y + ny),
+                                                               (dest.x + nx), (dest.y + ny));
+                                               g2D.drawLine((orig.x - nx), (orig.y - ny),
+                                                               (dest.x - nx), (dest.y - ny));
+                                       }
+                               } else if (style.isCanonicalAU()) {
+                                       g2D.drawLine(orig.x, orig.y, dest.x, dest.y);
+                               } else if (style.isWobbleUG()) {
+                                       double cx = (dest.x + orig.x) / 2.0;
+                                       double cy = (dest.y + orig.y) / 2.0;
+                                       g2D.drawLine(orig.x, orig.y, dest.x, dest.y);
+                                       drawSymbol(g2D, cx, cy, nx, ny, radiusCircle, false,
+                                                       ModeleBP.Edge.WC);
+                               } else {
+                                       double cx = (dest.x + orig.x) / 2.0;
+                                       double cy = (dest.y + orig.y) / 2.0;
+                                       g2D.drawLine(orig.x, orig.y, dest.x, dest.y);
+                                       drawSymbol(g2D, cx, cy, nx, ny, radiusCircle,
+                                                       style.isCIS(), style.getEdgePartner5());
+                               }
+                       } else {
+                               ModeleBP.Edge p1 = style.getEdgePartner5();
+                               ModeleBP.Edge p2 = style.getEdgePartner3();
+                               double cx = (dest.x + orig.x) / 2.0;
+                               double cy = (dest.y + orig.y) / 2.0;
+                               g2D.drawLine(orig.x, orig.y, dest.x, dest.y);
+                               if (p1 == p2) {
+                                       drawSymbol(g2D, cx, cy, nx, ny, radiusCircle,
+                                                       style.isCIS(), p1);
+
+                               } else {
+                                       double vdx = (dest.x - orig.x);
+                                       double vdy = (dest.y - orig.y);
+                                       vdx /= 6.0;
+                                       vdy /= 6.0;
+                                       drawSymbol(g2D, cx + vdx, cy + vdy, -nx, -ny, radiusCircle,
+                                                       style.isCIS(), p2);
+                                       drawSymbol(g2D, cx - vdx, cy - vdy, nx, ny, radiusCircle,
+                                                       style.isCIS(), p1);
+                               }
+                       }
+               }
+                       break;
+               case LW_ALT: {
+                       double radiusCircle = ((RNA.BASE_PAIR_DISTANCE - _RNA.BASE_RADIUS) / 5.0)
+                                       * scaleFactor;
+                       double distFromBaseCenter = DISTANCE_FACT*scaleFactor;
+                       Point2D.Double norig = new Point2D.Double(orig.x+(distFromBaseCenter+.5*newRadius)*dx,orig.y+(distFromBaseCenter+.5*newRadius)*dy);
+                       Point2D.Double ndest = new Point2D.Double(dest.x-(distFromBaseCenter+.5*newRadius)*dx,dest.y-(distFromBaseCenter+.5*newRadius)*dy);
+                       if (style.isCanonical()) {
+                               if (style.isCanonicalGC()) {
+                                       if ((norig.x != ndest.x) || (norig.y != ndest.y)) {
+                                               nx *= scaleFactor * _RNA.BASE_RADIUS / 4.0;
+                                               ny *= scaleFactor * _RNA.BASE_RADIUS / 4.0;
+                                               g2D.drawLine((norig.x + nx), (norig.y + ny),
+                                                               (ndest.x + nx), (ndest.y + ny));
+                                               g2D.drawLine((norig.x - nx), (norig.y - ny),
+                                                               (ndest.x - nx), (ndest.y - ny));
+                                       }
+                               } else if (style.isCanonicalAU()) {
+                                       g2D.drawLine(norig.x, norig.y, ndest.x, ndest.y);
+                               } else if (style.isWobbleUG()) {
+                                       double cx = (ndest.x + norig.x) / 2.0;
+                                       double cy = (ndest.y + norig.y) / 2.0;
+                                       g2D.drawLine(norig.x, norig.y, ndest.x, ndest.y);
+                                       drawSymbol(g2D, cx, cy, nx, ny, radiusCircle, false,
+                                                       ModeleBP.Edge.WC);
+                               } else {
+                                       double cx = (ndest.x + norig.x) / 2.0;
+                                       double cy = (ndest.y + norig.y) / 2.0;
+                                       g2D.drawLine(norig.x, norig.y, ndest.x, ndest.y);
+                                       drawSymbol(g2D, cx, cy, nx, ny, radiusCircle,
+                                                       style.isCIS(), style.getEdgePartner5());
+                               }
+                       } else {
+                               ModeleBP.Edge p1 = style.getEdgePartner5();
+                               ModeleBP.Edge p2 = style.getEdgePartner3();
+                               double cx = (ndest.x + norig.x) / 2.0;
+                               double cy = (ndest.y + norig.y) / 2.0;
+                               g2D.drawLine(norig.x, norig.y, ndest.x, ndest.y);
+                               if (p1 == p2) {
+                                       drawSymbol(g2D, cx, cy, nx, ny, radiusCircle,
+                                                       style.isCIS(), p1);
+
+                               } else {
+                                       double fac = .4;
+                                       drawSymbol(g2D, ndest.x - fac*radiusCircle*dx, ndest.y - fac*radiusCircle*dy, -nx, -ny, radiusCircle,
+                                                       style.isCIS(), p2);
+                                       drawSymbol(g2D, norig.x + fac*radiusCircle*dx, norig.y + fac*radiusCircle*dy, nx, ny, radiusCircle,
+                                                       style.isCIS(), p1);
+                               }
+                       }
+               }
+                       break;
+               case SIMPLE:
+                       g2D.drawLine(orig.x, orig.y, dest.x, dest.y);
+                       break;
+               case RNAVIZ:
+                       double xcenter = (orig.x + dest.x) / 2.0;
+                       double ycenter = (orig.y + dest.y) / 2.0;
+                       double radius = Math.max(4.0 * scaleFactor, 1.0);
+                       g2D.fillCircle((xcenter - radius), (ycenter - radius),
+                                       (2.0 * radius));
+                       break;
+               case NONE:
+                       break;
+               }
+       }
+
+       private Color getHighlightedVersion(Color c1, Color c2) {
+               int r1 = c1.getRed();
+               int g1 = c1.getGreen();
+               int b1 = c1.getBlue();
+               int r2 = c2.getRed();
+               int g2 = c2.getGreen();
+               int b2 = c2.getBlue();
+               double val = _blink.getVal();
+               int nr = Math.max(0,
+                               Math.min((int) ((r1 * val + r2 * (1.0 - val))), 255));
+               int ng = Math.max(0,
+                               Math.min((int) ((g1 * val + g2 * (1.0 - val))), 255));
+               int nb = Math.max(0,
+                               Math.min((int) ((b1 * val + b2 * (1.0 - val))), 255));
+               return new Color(nr, ng, nb);
+       }
+
+       private Color highlightFilter(int index, Color initialColor, Color c1,
+                       Color c2, boolean localView) {
+               if (_selectedBases.contains(_RNA.getBaseAt(index)) && localView) {
+                       return getHighlightedVersion(c1, c2);
+               } else
+                       return initialColor;
+       }
+
+       public static Point2D.Double computeExcentricUnitVector(int i,
+                       Point2D.Double[] points, Point2D.Double[] centers) {
+               double dist = points[i].distance(centers[i]);
+               Point2D.Double byCenter = new Point2D.Double(
+                               (points[i].x - centers[i].x) / dist,
+                               (points[i].y - centers[i].y) / dist);
+               if ((i > 0) && (i < points.length - 1)) {
+                       Point2D.Double p0 = points[i - 1];
+                       Point2D.Double p1 = points[i];
+                       Point2D.Double p2 = points[i + 1];
+                       double dist1 = p2.distance(p1);
+                       Point2D.Double v1 = new Point2D.Double((p2.x - p1.x) / dist1,
+                                       (p2.y - p1.y) / dist1);
+                       Point2D.Double vn1 = new Point2D.Double(v1.y, -v1.x);
+                       double dist2 = p1.distance(p0);
+                       Point2D.Double v2 = new Point2D.Double((p1.x - p0.x) / dist2,
+                                       (p1.y - p0.y) / dist2);
+                       Point2D.Double vn2 = new Point2D.Double(v2.y, -v2.x);
+                       Point2D.Double vn = new Point2D.Double((vn1.x + vn2.x) / 2.0,
+                                       (vn1.y + vn2.y) / 2.0);
+                       double D = vn.distance(new Point2D.Double(0.0, 0.0));
+                       vn.x /= D;
+                       vn.y /= D;
+                       if (byCenter.x * vn.x + byCenter.y * vn.y < 0) {
+                               vn.x = -vn.x;
+                               vn.y = -vn.y;
+                       }
+                       return vn;
+               } 
+               else if (((i==0) || (i==points.length-1)) && (points.length>1)) {
+                       int a = (i==0)?0:points.length-1;
+                       int b = (i==0)?1:points.length-2;
+                       double D = points[a].distance(points[b]);
+                       return new Point2D.Double(
+                                       (points[a].x - points[b].x) / D,
+                                       (points[a].y - points[b].y) / D);
+               }
+               else {
+                       return byCenter;
+               }
+       }
+
+       private void drawBase(VueVARNAGraphics g2D, int i, Point2D.Double[] points,
+                       Point2D.Double[] centers, double newRadius, double _scaleFactor,
+                       boolean localView) {
+               Point2D.Double p = points[i];
+               ModeleBase mb = _RNA.get_listeBases().get(i);
+               g2D.setFont(_conf._fontBasesGeneral);
+               Color baseInnerColor = highlightFilter(i,
+                               _RNA.getBaseInnerColor(i, _conf), Color.white,
+                               _RNA.getBaseInnerColor(i, _conf), localView);
+               Color baseOuterColor = highlightFilter(i,
+                               _RNA.getBaseOuterColor(i, _conf),
+                               _RNA.getBaseOuterColor(i, _conf), Color.white, localView);
+               Color baseNameColor = highlightFilter(i,
+                               _RNA.getBaseNameColor(i, _conf),
+                               _RNA.getBaseNameColor(i, _conf), Color.white, localView);
+               if ( RNA.whiteLabelPreferrable(baseInnerColor))
+               {
+                       baseNameColor=Color.white;
+               }
+
+               if (mb instanceof ModeleBaseNucleotide) {
+                       ModeleBaseNucleotide mbn = (ModeleBaseNucleotide) mb;
+                       String res = mbn.getBase();
+                       if (_hoveredBase == mb && localView && isModifiable()) {
+                               g2D.setColor(_conf._hoverColor);
+                               g2D.fillCircle(p.getX() - 1.5 * newRadius, p.getY() - 1.5
+                                               * newRadius, 3.0 * newRadius);
+                               g2D.setColor(_conf._hoverColor.darker());
+                               g2D.drawCircle(p.getX() - 1.5 * newRadius, p.getY() - 1.5
+                                               * newRadius, 3.0 * newRadius);
+                               g2D.setPlainStroke();
+                       }
+                       if (_conf._fillBases) {
+                               // Filling inner circle
+                               g2D.setColor(baseInnerColor);
+                               g2D.fillCircle(p.getX() - newRadius, p.getY() - newRadius,
+                                               2.0 * newRadius);
+                       }
+
+                       if (_conf._drawOutlineBases) {
+                               // Drawing outline
+                               g2D.setColor(baseOuterColor);
+                               g2D.setStrokeThickness(_conf._baseThickness * _scaleFactor);
+                               g2D.drawCircle(p.getX() - newRadius, p.getY() - newRadius,
+                                               2.0 * newRadius);
+                       }
+                       // Drawing label
+                       g2D.setColor(baseNameColor);
+                       g2D.drawStringCentered(String.valueOf(res), p.getX(), p.getY());
+               } else if (mb instanceof ModeleBasesComparison) {
+
+                       ModeleBasesComparison mbc = (ModeleBasesComparison) mb;
+
+                       // On lui donne l'aspect voulue (on a un trait droit)
+                       g2D.setPlainStroke(); // On doit avoir un trait droit, sans arrondit
+                       g2D.setStrokeThickness(_conf._baseThickness * _scaleFactor);
+
+                       // On dessine l'étiquette, rectangle aux bords arrondies.
+                       g2D.setColor(baseInnerColor);
+                       g2D.fillRoundRect((p.getX() - 1.5 * newRadius),
+                                       (p.getY() - newRadius), (3.0 * newRadius),
+                                       (2.0 * newRadius), 10 * _scaleFactor, 10 * _scaleFactor);
+
+                       /* Dessin du rectangle exterieur (bords) */
+                       g2D.setColor(baseOuterColor);
+                       g2D.drawRoundRect((p.getX() - 1.5 * newRadius),
+                                       (p.getY() - newRadius), (3 * newRadius), (2 * newRadius),
+                                       10 * _scaleFactor, 10 * _scaleFactor);
+
+                       // On le dessine au centre de l'étiquette.
+                       g2D.drawLine((p.getX()), (p.getY() + newRadius) - 1, (p.getX()),
+                                       (p.getY() - newRadius) + 1);
+
+                       /* Dessin du nom de la base (A,C,G,U,etc...) */
+                       // On créer le texte des Ã©tiquettes
+                       String label1 = String.valueOf(mbc.getBase1());
+                       String label2 = String.valueOf(mbc.getBase2());
+
+                       // On leur donne une couleur
+                       g2D.setColor(getRNA().get_listeBases().get(i).getStyleBase()
+                                       .getBaseNameColor());
+
+                       // Et on les dessine.
+                       g2D.drawStringCentered(label1, p.getX() - (.75 * newRadius),
+                                       p.getY());
+                       g2D.drawStringCentered(label2, p.getX() + (.75 * newRadius),
+                                       p.getY());
+               }
+
+               // Drawing base number
+               if (_RNA.isNumberDrawn(mb, getNumPeriod())) {
+
+                       Point2D.Double vn = computeExcentricUnitVector(i, points, centers);
+                       g2D.setColor(mb.getStyleBase().getBaseNumberColor());
+                       g2D.setFont(_conf._numbersFont);
+                       double factorMin = Math.min(.5, _conf._distNumbers);
+                       double factorMax = Math.min(_conf._distNumbers - 1.5,
+                                       _conf._distNumbers);
+                       g2D.drawLine(p.x + vn.x * ((1 + factorMin) * newRadius), p.y + vn.y
+                                       * ((1 + factorMin) * newRadius), p.x + vn.x
+                                       * ((1 + factorMax) * newRadius), p.y + vn.y
+                                       * ((1 + factorMax) * newRadius));
+                       g2D.drawStringCentered(mb.getLabel(), p.x + vn.x
+                                       * ((1 + _conf._distNumbers) * newRadius), p.y + vn.y
+                                       * ((1 + _conf._distNumbers) * newRadius));
+
+               }
+       }
+
+       void drawChemProbAnnotation(VueVARNAGraphics g2D, ChemProbAnnotation cpa,
+                       Point2D.Double anchor, double scaleFactor) {
+               g2D.setColor(cpa.getColor());
+               g2D.setStrokeThickness(RNA.CHEM_PROB_ARROW_THICKNESS * scaleFactor
+                               * cpa.getIntensity());
+               g2D.setPlainStroke();
+               Point2D.Double v = cpa.getDirVector();
+               Point2D.Double vn = cpa.getNormalVector();
+               Point2D.Double base = new Point2D.Double(
+                               (anchor.x + _RNA.CHEM_PROB_DIST * scaleFactor * v.x),
+                               (anchor.y + _RNA.CHEM_PROB_DIST * scaleFactor * v.y));
+               Point2D.Double edge = new Point2D.Double(
+                               (base.x + _RNA.CHEM_PROB_BASE_LENGTH * cpa.getIntensity()
+                                               * scaleFactor * v.x),
+                               (base.y + _RNA.CHEM_PROB_BASE_LENGTH * cpa.getIntensity()
+                                               * scaleFactor * v.y));
+               switch (cpa.getType()) {
+               case ARROW: {
+                       Point2D.Double arrowTip1 = new Point2D.Double(
+                                       (base.x + cpa.getIntensity()
+                                                       * scaleFactor
+                                                       * (_RNA.CHEM_PROB_ARROW_WIDTH * vn.x + _RNA.CHEM_PROB_ARROW_HEIGHT
+                                                                       * v.x)),
+                                       (base.y + cpa.getIntensity()
+                                                       * scaleFactor
+                                                       * (_RNA.CHEM_PROB_ARROW_WIDTH * vn.y + _RNA.CHEM_PROB_ARROW_HEIGHT
+                                                                       * v.y)));
+                       Point2D.Double arrowTip2 = new Point2D.Double(
+                                       (base.x + cpa.getIntensity()
+                                                       * scaleFactor
+                                                       * (-_RNA.CHEM_PROB_ARROW_WIDTH * vn.x + _RNA.CHEM_PROB_ARROW_HEIGHT
+                                                                       * v.x)),
+                                       (base.y + cpa.getIntensity()
+                                                       * scaleFactor
+                                                       * (-_RNA.CHEM_PROB_ARROW_WIDTH * vn.y + _RNA.CHEM_PROB_ARROW_HEIGHT
+                                                                       * v.y)));
+                       g2D.drawLine(base.x, base.y, edge.x, edge.y);
+                       g2D.drawLine(base.x, base.y, arrowTip1.x, arrowTip1.y);
+                       g2D.drawLine(base.x, base.y, arrowTip2.x, arrowTip2.y);
+               }
+                       break;
+               case PIN: {
+                       Point2D.Double side1 = new Point2D.Double(
+                                       (edge.x - cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_PIN_SEMIDIAG * v.x)),
+                                       (edge.y - cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_PIN_SEMIDIAG * v.y)));
+                       Point2D.Double side2 = new Point2D.Double(
+                                       (edge.x - cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_PIN_SEMIDIAG * vn.x)),
+                                       (edge.y - cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_PIN_SEMIDIAG * vn.y)));
+                       Point2D.Double side3 = new Point2D.Double(
+                                       (edge.x + cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_PIN_SEMIDIAG * v.x)),
+                                       (edge.y + cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_PIN_SEMIDIAG * v.y)));
+                       Point2D.Double side4 = new Point2D.Double(
+                                       (edge.x + cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_PIN_SEMIDIAG * vn.x)),
+                                       (edge.y + cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_PIN_SEMIDIAG * vn.y)));
+                       GeneralPath p2 = new GeneralPath();
+                       p2.moveTo((float) side1.x, (float) side1.y);
+                       p2.lineTo((float) side2.x, (float) side2.y);
+                       p2.lineTo((float) side3.x, (float) side3.y);
+                       p2.lineTo((float) side4.x, (float) side4.y);
+                       p2.closePath();
+                       g2D.fill(p2);
+                       g2D.drawLine(base.x, base.y, edge.x, edge.y);
+               }
+                       break;
+               case TRIANGLE: {
+                       Point2D.Double arrowTip1 = new Point2D.Double(
+                                       (edge.x + cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_TRIANGLE_WIDTH * vn.x)),
+                                       (edge.y + cpa.getIntensity() * scaleFactor
+                                                       * (_RNA.CHEM_PROB_TRIANGLE_WIDTH * vn.y)));
+                       Point2D.Double arrowTip2 = new Point2D.Double(
+                                       (edge.x + cpa.getIntensity() * scaleFactor
+                                                       * (-_RNA.CHEM_PROB_TRIANGLE_WIDTH * vn.x)),
+                                       (edge.y + cpa.getIntensity() * scaleFactor
+                                                       * (-_RNA.CHEM_PROB_TRIANGLE_WIDTH * vn.y)));
+                       GeneralPath p2 = new GeneralPath();
+                       p2.moveTo((float) base.x, (float) base.y);
+                       p2.lineTo((float) arrowTip1.x, (float) arrowTip1.y);
+                       p2.lineTo((float) arrowTip2.x, (float) arrowTip2.y);
+                       p2.closePath();
+                       g2D.fill(p2);
+               }
+                       break;
+               case DOT: {
+                       Double radius = scaleFactor * _RNA.CHEM_PROB_DOT_RADIUS
+                                       * cpa.getIntensity();
+                       Point2D.Double center = new Point2D.Double((base.x + radius * v.x),
+                                       (base.y + radius * v.y));
+                       g2D.fillCircle((center.x - radius), (center.y - radius),
+                                       (2 * radius));
+               }
+                       break;
+               }
+       }
+
+       Point2D.Double buildCaptionPosition(ModeleBase mb, double scaleFactor,
+                       double heightEstimate) {
+               double radius = 2.0;
+               if (_RNA.isNumberDrawn(mb, getNumPeriod())) {
+                       radius += _conf._distNumbers;
+               }
+               Point2D.Double center = mb.getCenter();
+               Point2D.Double p = mb.getCoords();
+               double realDistance = _RNA.BASE_RADIUS * radius + heightEstimate;
+               return new Point2D.Double(center.getX() + (p.getX() - center.getX())
+                               * ((p.distance(center) + realDistance) / p.distance(center)),
+                               center.getY()
+                                               + (p.getY() - center.getY())
+                                               * ((p.distance(center) + realDistance) / p
+                                                               .distance(center)));
+       }
+
+       private void renderAnnotations(VueVARNAGraphics g2D, double offX,
+                       double offY, double rnaBBoxX, double rnaBBoxY, double scaleFactor) {
+               for (TextAnnotation textAnnotation : _RNA.getAnnotations()) {
+                       g2D.setColor(textAnnotation.getColor());
+                       g2D.setFont(textAnnotation
+                                       .getFont()
+                                       .deriveFont(
+                                                       (float) (2.0 * textAnnotation.getFont().getSize() * scaleFactor)));
+                       Point2D.Double position = textAnnotation.getCenterPosition();
+                       if (textAnnotation.getType() == TextAnnotation.AnchorType.BASE) {
+                               ModeleBase mb = (ModeleBase) textAnnotation.getAncrage();
+                               double fontHeight = Math.ceil(textAnnotation.getFont()
+                                               .getSize());
+                               position = buildCaptionPosition(mb, scaleFactor, fontHeight);
+                       }
+                       position = transformCoord(position, offX, offY, rnaBBoxX, rnaBBoxY,
+                                       scaleFactor);
+                       g2D.drawStringCentered(textAnnotation.getTexte(), position.x,
+                                       position.y);
+                       if ((_selectedAnnotation == textAnnotation)
+                                       && (_highlightAnnotation)) {
+                               drawStringOutline(g2D, textAnnotation.getTexte(), position.x,
+                                               position.y, 5);
+                       }
+               }
+               for (ChemProbAnnotation cpa : _RNA.getChemProbAnnotations()) {
+                       Point2D.Double anchor = transformCoord(cpa.getAnchorPosition(),
+                                       offX, offY, rnaBBoxX, rnaBBoxY, scaleFactor);
+                       drawChemProbAnnotation(g2D, cpa, anchor, scaleFactor);
+               }
+
+       }
+
+       public Rectangle2D.Double getExtendedRNABBox() {
+               // We get the logical bounding box
+               Rectangle2D.Double rnabbox = _RNA.getBBox();
+               rnabbox.y -= _conf._distNumbers * _RNA.BASE_RADIUS;
+               rnabbox.height += 2.0 * _conf._distNumbers * _RNA.BASE_RADIUS;
+               rnabbox.x -= _conf._distNumbers * _RNA.BASE_RADIUS;
+               rnabbox.width += 2.0 * _conf._distNumbers * _RNA.BASE_RADIUS;
+               if (_RNA.hasVirtualLoops()) {
+                       rnabbox.y -= RNA.VIRTUAL_LOOP_RADIUS;
+                       rnabbox.height += 2.0 * RNA.VIRTUAL_LOOP_RADIUS;
+                       rnabbox.x -= RNA.VIRTUAL_LOOP_RADIUS;
+                       rnabbox.width += 2.0 * RNA.VIRTUAL_LOOP_RADIUS;
+               }
+               return rnabbox;
+       }
+
+       public void drawBackbone(VueVARNAGraphics g2D, Point2D.Double[] newCoords,
+                       double newRadius, double _scaleFactor) {
+               // Drawing backbone
+               if (getDrawBackbone()) {
+                       g2D.setStrokeThickness(1.5 * _scaleFactor);
+                       g2D.setColor(_conf._backboneColor);
+                       
+                       ModeleBackbone bck = _RNA.getBackbone();
+
+
+                       for (int i = 1; i < _RNA.get_listeBases().size(); i++) {
+                               Point2D.Double p1 = newCoords[i - 1];
+                               Point2D.Double p2 = newCoords[i];
+                               double dist = p1.distance(p2);
+                               int a = _RNA.getBaseAt(i - 1).getElementStructure();
+                               int b = _RNA.getBaseAt(i).getElementStructure();
+                               boolean consecutivePair = (a == i) && (b == i - 1);
+
+                               if ((dist > 0)) {
+                                       Point2D.Double vbp = new Point2D.Double();
+                                       vbp.x = (p2.x - p1.x) / dist;
+                                       vbp.y = (p2.y - p1.y) / dist;
+                                       
+                                       BackboneType bt = bck.getTypeBefore(i);
+                                       if (bt!=BackboneType.DISCONTINUOUS_TYPE)
+                                       {
+                                               if (bt==BackboneType.MISSING_PART_TYPE) {
+                                                       g2D.setSelectionStroke();
+                                               } else {
+                                                       g2D.setPlainStroke();
+                                               }
+                                               g2D.setColor(bck.getColorBefore(i, _conf._backboneColor));
+                                               
+                                               if (consecutivePair
+                                                               && (_RNA.getDrawMode() != RNA.DRAW_MODE_LINEAR)
+                                                               && (_RNA.getDrawMode() != RNA.DRAW_MODE_CIRCULAR)) {
+                                                       int dir = 0;
+                                                       if (i + 1 < newCoords.length) {
+                                                               dir = (_RNA.testDirectionality(i - 1, i, i + 1) ? -1
+                                                                               : 1);
+                                                       } else if (i - 2 >= 0) {
+                                                               dir = (_RNA.testDirectionality(i - 2, i - 1, i) ? -1
+                                                                               : 1);
+                                                       }
+                                                       Point2D.Double vn = new Point2D.Double(dir * vbp.y,
+                                                                       -dir * vbp.x);
+                                                       Point2D.Double centerSeg = new Point2D.Double(
+                                                                       (p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0);
+                                                       double distp1CenterSeq = p1.distance(centerSeg);
+                                                       double centerDist = Math
+                                                                       .sqrt((RNA.VIRTUAL_LOOP_RADIUS * _scaleFactor
+                                                                                       * RNA.VIRTUAL_LOOP_RADIUS * _scaleFactor)
+                                                                                       - distp1CenterSeq * distp1CenterSeq);
+                                                       Point2D.Double centerLoop = new Point2D.Double(
+                                                                       centerSeg.x + centerDist * vn.x, centerSeg.y
+                                                                                       + centerDist * vn.y);
+                                                       double radius = centerLoop.distance(p1);
+                                                       double a1 = 360.
+                                                                       * (Math.atan2(-(p1.y - centerLoop.y),
+                                                                                       (p1.x - centerLoop.x)))
+                                                                       / (2. * Math.PI);
+                                                       double a2 = 360.
+                                                                       * (Math.atan2(-(p2.y - centerLoop.y),
+                                                                                       (p2.x - centerLoop.x)))
+                                                                       / (2. * Math.PI);
+                                                       double angle = (a2 - a1);
+                                                       if (-dir * angle < 0) {
+                                                               angle += -dir * 360.;
+                                                       }
+                                                       // if (angle<0.) angle += 360.;
+                                                       // angle = -dir*(360-dir*angle);
+                                                       g2D.drawArc(centerLoop.x + .8 * newRadius * vn.x,
+                                                                       centerLoop.y + .8 * newRadius * vn.y,
+                                                                       2 * radius, 2 * radius, a1, angle);
+                                               } else {
+                                                       g2D.drawLine((newCoords[i - 1].x + newRadius * vbp.x),
+                                                                       (newCoords[i - 1].y + newRadius * vbp.y),
+                                                                       (newCoords[i].x - newRadius * vbp.x),
+                                                                       (newCoords[i].y - newRadius * vbp.y));
+                                               }
+                                       }
+                               }
+                       }
+               }
+       }
+
+       public Point2D.Double logicToPanel(Point2D.Double logicPoint) {
+               return new Point2D.Double(_offX
+                               + (getScaleFactor() * (logicPoint.x - _offsetRNA.x)), _offY
+                               + (getScaleFactor() * (logicPoint.y - _offsetRNA.y)));
+
+       }
+
+       public Rectangle2D.Double renderRNA(VueVARNAGraphics g2D,
+                       Rectangle2D.Double bbox) {
+               return renderRNA(g2D, bbox, false, true);
+       }
+
+       private double computeScaleFactor(Rectangle2D.Double bbox,
+                       boolean localView, boolean autoCenter) {
+               Rectangle2D.Double rnabbox = getExtendedRNABBox();
+               double scaleFactor = Math.min((double) bbox.width
+                               / (double) rnabbox.width, (double) bbox.height
+                               / (double) rnabbox.height);
+
+               // Use it to get an estimate of the font size for numbers ...
+               float newFontSize = Math.max(1,
+                               (int) ((1.7 * _RNA.BASE_RADIUS) * scaleFactor));
+               // ... and increase bounding box accordingly
+               rnabbox.y -= newFontSize;
+               rnabbox.height += newFontSize;
+               if (_conf._drawColorMap) {
+                       rnabbox.height += getColorMapHeight();
+               }
+               rnabbox.x -= newFontSize;
+               rnabbox.width += newFontSize;
+
+               // Now, compute the final scaling factor and corresponding font size
+               scaleFactor = Math.min((double) bbox.width / (double) rnabbox.width,
+                               (double) bbox.height / (double) rnabbox.height);
+               if (localView) {
+                       if (_conf._autoFit)
+                               setScaleFactor(scaleFactor);
+                       scaleFactor = getScaleFactor();
+               }
+               return scaleFactor;
+       }
+
+       public synchronized Rectangle2D.Double renderRNA(VueVARNAGraphics g2D,
+                       Rectangle2D.Double bbox, boolean localView, boolean autoCenter) {
+               Rectangle2D.Double rnaMultiBox = new Rectangle2D.Double(0, 0, 1, 1);
+               double scaleFactor = computeScaleFactor(bbox, localView, autoCenter);
+               float newFontSize = Math.max(1,
+                               (int) ((1.7 * _RNA.BASE_RADIUS) * scaleFactor));
+               double newRadius = Math.max(1.0, (scaleFactor * _RNA.BASE_RADIUS));
+               setBaseFontSize(newFontSize);
+               setNumbersFontSize(newFontSize);
+               double offX = bbox.x;
+               double offY = bbox.y;
+               Rectangle2D.Double rnabbox = getExtendedRNABBox();
+
+               if (_RNA.getSize() != 0) {
+
+                       Point2D.Double offsetRNA = new Point2D.Double(rnabbox.x, rnabbox.y);
+
+                       if (autoCenter) {
+                               offX = (bbox.x + (bbox.width - Math.round(rnabbox.width
+                                               * scaleFactor)) / 2.0);
+                               offY = (bbox.y + (bbox.height - Math.round(rnabbox.height
+                                               * scaleFactor)) / 2.0);
+                               if (localView) {
+                                       _offX = offX;
+                                       _offY = offY;
+                                       _offsetPanel = new Point2D.Double(_offX, _offY);
+                                       _offsetRNA = new Point2D.Double(rnabbox.x, rnabbox.y);
+                               }
+                       }
+
+                       if (localView) {
+                               offX = _offX;
+                               offY = _offY;
+                               offsetRNA = _offsetRNA;
+                       }
+
+                       // Re-scaling once and for all
+                       Point2D.Double[] newCoords = new Point2D.Double[_RNA
+                                       .get_listeBases().size()];
+                       Point2D.Double[] newCenters = new Point2D.Double[_RNA
+                                       .get_listeBases().size()];
+                       for (int i = 0; i < _RNA.get_listeBases().size(); i++) {
+                               ModeleBase mb = _RNA.getBaseAt(i);
+                               newCoords[i] = new Point2D.Double(offX
+                                               + (scaleFactor * (mb.getCoords().x - offsetRNA.x)),
+                                               offY + (scaleFactor * (mb.getCoords().y - offsetRNA.y)));
+
+                               Point2D.Double centerBck = _RNA.getCenter(i);
+                               // si la base est dans un angle entre une boucle et une helice
+                               if (_RNA.get_drawMode() == RNA.DRAW_MODE_NAVIEW
+                                               || _RNA.get_drawMode() == RNA.DRAW_MODE_RADIATE) {
+                                       if ((mb.getElementStructure() != -1)
+                                                       && i < _RNA.get_listeBases().size() - 1 && i > 1) {
+                                               ModeleBase b1 = _RNA.get_listeBases().get(i - 1);
+                                               ModeleBase b2 = _RNA.get_listeBases().get(i + 1);
+                                               int j1 = b1.getElementStructure();
+                                               int j2 = b2.getElementStructure();
+                                               if ((j1 == -1) ^ (j2 == -1)) {
+                                                       // alors la position du nombre associé doit etre
+                                                       Point2D.Double a1 = b1.getCoords();
+                                                       Point2D.Double a2 = b2.getCoords();
+                                                       Point2D.Double c1 = b1.getCenter();
+                                                       Point2D.Double c2 = b2.getCenter();
+
+                                                       centerBck.x = mb.getCoords().x + (c1.x - a1.x)
+                                                                       / c1.distance(a1) + (c2.x - a2.x)
+                                                                       / c2.distance(a2);
+                                                       centerBck.y = mb.getCoords().y + (c1.y - a1.y)
+                                                                       / c1.distance(a1) + (c2.y - a2.y)
+                                                                       / c2.distance(a2);
+                                               }
+                                       }
+                               }
+                               newCenters[i] = new Point2D.Double(offX
+                                               + (scaleFactor * (centerBck.x - offsetRNA.x)), offY
+                                               + (scaleFactor * (centerBck.y - offsetRNA.y)));
+                       }
+                       // Keep track of coordinates for mouse interactions
+                       if (localView) {
+                               _realCoords = newCoords;
+                               _realCenters = newCenters;
+                       }
+
+                       g2D.setStrokeThickness(1.5 * scaleFactor);
+                       g2D.setPlainStroke();
+                       g2D.setFont(_conf._fontBasesGeneral);
+
+                       // Drawing region highlights Annotation
+                       drawRegionHighlightsAnnotation(g2D, _realCoords, _realCenters,
+                                       scaleFactor);
+                       drawBackbone(g2D, newCoords, newRadius, scaleFactor);
+
+                       // Drawing base-pairs
+                       // pour chaque base
+                       for (int i = 0; i < _RNA.get_listeBases().size(); i++) {
+                               int j = _RNA.get_listeBases().get(i).getElementStructure();
+                               // si c'est une parenthese ouvrante (premiere base du
+                               // couple)
+                               if (j > i) {
+                                       ModeleBP msbp = _RNA.get_listeBases().get(i).getStyleBP();
+                                       // System.err.println(msbp);
+                                       if (msbp.isCanonical() || _conf._drawnNonCanonicalBP) {
+                                               if (_RNA.get_drawMode() == RNA.DRAW_MODE_LINEAR) {
+                                                       g2D.setStrokeThickness(_RNA.getBasePairThickness(
+                                                                       msbp, _conf)
+                                                                       * 2.0
+                                                                       * scaleFactor
+                                                                       * _conf._bpThickness);
+                                               } else {
+                                                       g2D.setStrokeThickness(_RNA.getBasePairThickness(
+                                                                       msbp, _conf) * 1.5 * scaleFactor);
+                                               }
+                                               g2D.setColor(_RNA.getBasePairColor(msbp, _conf));
+
+                                               if (_RNA.get_drawMode() == RNA.DRAW_MODE_LINEAR) {
+                                                       drawBasePairArc(g2D, i, j, newCoords[i],
+                                                                       newCoords[j], scaleFactor, msbp, newRadius);
+                                               } else {
+                                                       drawBasePair(g2D, newCoords[i], newCoords[j], msbp,
+                                                                       newRadius, scaleFactor);
+                                               }
+                                       }
+                               }
+                       }
+
+                       // Liaisons additionelles (non planaires)
+                       if (_conf._drawnNonPlanarBP) {
+                               ArrayList<ModeleBP> bpaux = _RNA.getStructureAux();
+                               for (int k = 0; k < bpaux.size(); k++) {
+                                       ModeleBP msbp = bpaux.get(k);
+                                       if (msbp.isCanonical() || _conf._drawnNonCanonicalBP) {
+                                               int i = msbp.getPartner5().getIndex();
+                                               int j = msbp.getPartner3().getIndex();
+                                               if (_RNA.get_drawMode() == RNA.DRAW_MODE_LINEAR) {
+                                                       g2D.setStrokeThickness(_RNA.getBasePairThickness(
+                                                                       msbp, _conf)
+                                                                       * 2.5
+                                                                       * scaleFactor
+                                                                       * _conf._bpThickness);
+                                                       g2D.setPlainStroke();
+                                               } else {
+                                                       g2D.setStrokeThickness(_RNA.getBasePairThickness(
+                                                                       msbp, _conf) * 1.5 * scaleFactor);
+                                                       g2D.setPlainStroke();
+                                               }
+
+                                               g2D.setColor(_RNA.getBasePairColor(msbp, _conf));
+                                               if (j > i) {
+                                                       if (_RNA.get_drawMode() == RNA.DRAW_MODE_LINEAR) {
+                                                               drawBasePairArc(g2D, i, j, newCoords[i],
+                                                                               newCoords[j], scaleFactor, msbp, newRadius);
+                                                       } else {
+                                                               drawBasePair(g2D, newCoords[i], newCoords[j],
+                                                                               msbp, newRadius, scaleFactor);
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+
+                       // Drawing bases
+                       g2D.setPlainStroke();
+                       for (int i = 0; i < Math.min(_RNA.get_listeBases().size(),
+                                       newCoords.length); i++) {
+                               drawBase(g2D, i, newCoords, newCenters, newRadius, scaleFactor,
+                                               localView);
+                       }
+
+                       rnaMultiBox = new Rectangle2D.Double(offX, offY,
+                                       (scaleFactor * rnabbox.width) - 1,
+                                       (scaleFactor * rnabbox.height) - 1);
+
+                       if (localView) {
+                               // Drawing bbox
+                               if (_debug || _drawBBox) {
+                                       g2D.setColor(Color.RED);
+                                       g2D.setSelectionStroke();
+                                       g2D.drawRect(rnaMultiBox.x, rnaMultiBox.y,
+                                                       rnaMultiBox.width, rnaMultiBox.height);
+                               }
+
+                               // Draw color map
+                               if (_conf._drawColorMap) {
+                                       drawColorMap(g2D, scaleFactor, rnabbox);
+                               }
+
+                               if (_debug || _drawBBox) {
+                                       g2D.setColor(Color.GRAY);
+                                       g2D.setSelectionStroke();
+                                       g2D.drawRect(0, 0, getWidth() - 1, getHeight()
+                                                       - getTitleHeight() - 1);
+                               }
+                       }
+                       // Draw annotations
+                       renderAnnotations(g2D, offX, offY, offsetRNA.x, offsetRNA.y,
+                                       scaleFactor);
+                       // Draw additional debug shape
+                       if (_RNA._debugShape != null) {
+                               Color c = new Color(255, 0, 0, 50);
+                               g2D.setColor(c);
+                               AffineTransform at = new AffineTransform();
+                               at.translate(offX - scaleFactor * rnabbox.x, offY - scaleFactor
+                                               * rnabbox.y);
+                               at.scale(scaleFactor, scaleFactor);
+                               Shape s = at.createTransformedShape(_RNA._debugShape);
+                               if (s instanceof GeneralPath) {
+                                       g2D.fill((GeneralPath) s);
+                               }
+                       }
+               } else {
+                       g2D.setColor(VARNAConfig.DEFAULT_MESSAGE_COLOR);
+                       g2D.setFont(VARNAConfig.DEFAULT_MESSAGE_FONT);
+                       rnaMultiBox = new Rectangle2D.Double(0,0,10,10);
+                       g2D.drawStringCentered("No RNA here", bbox.getCenterX(),bbox.getCenterY());
+               }
+               return rnaMultiBox;
+       }
+
+       public void centerViewOn(double x, double y) {
+               Rectangle2D.Double r = _RNA.getBBox();
+               _target = new Point2D.Double(x, y);
+               Point2D.Double q = logicToPanel(_target);
+               Point p = new Point((int) (-q.x), (int) (-q.y));
+               setTranslation(p);
+               repaint();
+       }
+
+       Point2D.Double _target = new Point2D.Double(0, 0);
+       Point2D.Double _target2 = new Point2D.Double(0, 0);
+
+       public ModeleBase getBaseAt(Point2D.Double po) {
+               ModeleBase mb = null;
+               Point2D.Double p = panelToLogicPoint(po);
+               double dist = Double.MAX_VALUE;
+               for (ModeleBase tmp : _RNA.get_listeBases()) {
+                       double ndist = tmp.getCoords().distance(p);
+                       if (dist > ndist) {
+                               mb = tmp;
+                               dist = ndist;
+                       }
+               }
+               return mb;
+       }
+
+       public void setColorMapValues(Double[] values) {
+               _RNA.setColorMapValues(values, _conf._cm, true);
+               _conf._drawColorMap = true;
+               repaint();
+       }
+
+       public void setColorMapMaxValue(double d) {
+               _conf._cm.setMaxValue(d);
+       }
+
+       public void setColorMapMinValue(double d) {
+               _conf._cm.setMinValue(d);
+       }
+
+       public ModeleColorMap getColorMap() {
+               return _conf._cm;
+       }
+
+       public void setColorMap(ModeleColorMap cm) {
+               //_RNA.adaptColorMapToValues(cm);
+               _conf._cm = cm;
+               repaint();
+       }
+
+       public void setColorMapCaption(String caption) {
+               _conf._colorMapCaption = caption;
+               repaint();
+       }
+
+       public String getColorMapCaption() {
+               return _conf._colorMapCaption;
+       }
+
+       public void drawColorMap(boolean draw) {
+               _conf._drawColorMap = draw;
+       }
+
+       private double getColorMapHeight() {
+               double result = VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE
+                               + _conf._colorMapHeight;
+               if (!_conf._colorMapCaption.equals(""))
+                       result += VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE;
+               return result;
+       }
+
+       private void drawColorMap(VueVARNAGraphics g2D, double scaleFactor,
+                       Rectangle2D.Double rnabbox) {
+               double v1 = _conf._cm.getMinValue();
+               double v2 = _conf._cm.getMaxValue();
+               double x, y;
+               g2D.setPlainStroke();
+
+               double xSpaceAvail = 0;
+               double ySpaceAvail = Math
+                               .min((getHeight() - rnabbox.height * scaleFactor - getTitleHeight()) / 2.0,
+                                               scaleFactor
+                                                               * (_conf._colorMapHeight + VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE));
+               if ((int) ySpaceAvail == 0) {
+                       xSpaceAvail = Math.min(
+                                       (getWidth() - rnabbox.width * scaleFactor) / 2, scaleFactor
+                                                       * (_conf._colorMapWidth)
+                                                       + VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH);
+               }
+               double xBase = (xSpaceAvail + _offX + scaleFactor
+                               * (rnabbox.width - _conf._colorMapWidth - _conf._colorMapXOffset));
+               double hcaption = VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE;
+               double yBase = (ySpaceAvail + _offY + scaleFactor
+                               * (rnabbox.height - _conf._colorMapHeight
+                                               - _conf._colorMapYOffset - hcaption));
+
+               for (int i = 0; i < _conf._colorMapWidth; i++) {
+                       double ratio = (((double) i) / ((double) _conf._colorMapWidth));
+                       double val = v1 + (v2 - v1) * ratio;
+                       g2D.setColor(_conf._cm.getColorForValue(val));
+                       x = (xBase + scaleFactor * i);
+                       y = yBase;
+                       g2D.fillRect(x, y, scaleFactor
+                                       * VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH,
+                                       (scaleFactor * _conf._colorMapHeight));
+               }
+               g2D.setColor(VARNAConfig.DEFAULT_COLOR_MAP_OUTLINE);
+               g2D.drawRect(xBase, yBase,
+                               (VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH - 1 + scaleFactor
+                                               * _conf._colorMapWidth),
+                               ((scaleFactor * _conf._colorMapHeight)));
+               g2D.setFont(getFont()
+                               .deriveFont(
+                                               (float) (scaleFactor * VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE)));
+               g2D.setColor(VARNAConfig.DEFAULT_COLOR_MAP_FONT_COLOR);
+               NumberFormat nf = NumberFormat.getInstance();
+               nf.setMaximumFractionDigits(2);
+               nf.setMinimumFractionDigits(0);
+               g2D.drawStringCentered(nf.format(_conf._cm.getMinValue()), xBase, 
+                               yBase
+                               + scaleFactor * (_conf._colorMapHeight+(VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE / 1.7)));
+               g2D.drawStringCentered(nf.format(_conf._cm.getMaxValue()), xBase
+                               + VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH + scaleFactor
+                               * _conf._colorMapWidth, 
+                               yBase
+                               + scaleFactor * (_conf._colorMapHeight+(VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE / 1.7)));
+               if (!_conf._colorMapCaption.equals(""))
+                       g2D.drawStringCentered(
+                                       "" + _conf._colorMapCaption,
+                                       xBase + scaleFactor * _conf._colorMapWidth / 2.0,
+                                       yBase
+                                                       + scaleFactor
+                                                       * (VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE / 1.7 + _conf._colorMapHeight));
+
+       }
+
+       public Point2D.Double panelToLogicPoint(Point2D.Double p) {
+               return new Point2D.Double(
+                               ((p.x - getOffsetPanel().x) / getScaleFactor())
+                                               + getRNAOffset().x,
+                               ((p.y - getOffsetPanel().y) / getScaleFactor())
+                                               + getRNAOffset().y);
+       }
+
+       public Point2D.Double transformCoord(Point2D.Double coordDebut,
+                       double offX, double offY, double rnaBBoxX, double rnaBBoxY,
+                       double scaleFactor) {
+               return new Point2D.Double(offX
+                               + (scaleFactor * (coordDebut.x - rnaBBoxX)), offY
+                               + (scaleFactor * (coordDebut.y - rnaBBoxY)));
+       }
+
+       public void eraseSequence() {
+               _RNA.eraseSequence();
+       }
+
+       public Point2D.Double transformCoord(Point2D.Double coordDebut) {
+               Rectangle2D.Double rnabbox = getExtendedRNABBox();
+               return new Point2D.Double(_offX
+                               + (getScaleFactor() * (coordDebut.x - rnabbox.x)), _offY
+                               + (getScaleFactor() * (coordDebut.y - rnabbox.y)));
+       }
+
+       public void paintComponent(Graphics g) {
+               paintComponent(g, false);
+       }
+
+       public void paintComponent(Graphics g, boolean transparentBackground) {
+               if (_premierAffichage) {
+                       // _border = new Dimension(0, 0);
+                       _translation.x = 0;
+                       _translation.y = (int) (-getTitleHeight() / 2.0);
+                       _popup.buildPopupMenu();
+                       this.add(_popup);
+                       _premierAffichage = false;
+               }
+
+               Graphics2D g2 = (Graphics2D) g;
+               Stroke dflt = g2.getStroke();
+               VueVARNAGraphics g2D = new SwingGraphics(g2);
+               g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+                               RenderingHints.VALUE_ANTIALIAS_ON);
+               this.removeAll();
+               super.paintComponent(g2);
+               renderComponent(g2D, transparentBackground, getScaleFactor());
+               if (isFocusOwner()) {
+                       g2.setStroke(new BasicStroke(1.5f));
+                       g2.setColor(Color.decode("#C0C0C0"));
+                       g2.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
+
+               }
+               g2.setStroke(dflt);
+               /*
+                * PSExport e = new PSExport(); SecStrProducerGraphics export = new
+                * SecStrProducerGraphics(e); renderRNA(export, getExtendedRNABBox());
+                * try { export.saveToDisk("./out.ps"); } catch
+                * (ExceptionWritingForbidden e1) { e1.printStackTrace(); }
+                */
+       }
+
+       /**
+        * Draws current RNA structure in a given Graphics "device".
+        * 
+        * @param g2D
+        *            A graphical device
+        * @param transparentBackground
+        *            Whether the background should be transparent, or drawn.
+        */
+       public synchronized void renderComponent(VueVARNAGraphics g2D,
+                       boolean transparentBackground, double scaleFactor) {
+
+               updateTitleHeight();
+
+               if (_debug || _drawBorder) {
+                       g2D.setColor(Color.BLACK);
+                       g2D.setPlainStroke();
+                       g2D.drawRect(getLeftOffset(), getTopOffset(), getInnerWidth(),
+                                       getInnerHeight());
+
+               }
+
+               
+               if (!transparentBackground) {
+                       super.setBackground(_conf._backgroundColor);
+               } else {
+                       super.setBackground(new Color(0, 0, 0, 120));
+               }
+
+               // BH 2018 was lt, not lteq here
+               // SwingJS sets the minimum panel size -- probably incorrectly -- to the size for VARNAPanel
+               if (getMinimumSize().height <= getSize().height
+                               && getMinimumSize().width <= getSize().width) {
+                       // Draw Title
+                       if (!getTitle().equals("")) {
+                               g2D.setColor(_conf._titleColor);
+                               g2D.setFont(_conf._titleFont);
+                               g2D.drawStringCentered(getTitle(), this.getWidth() / 2,
+                                               this.getHeight() - getTitleHeight() / 2.0);
+                       }
+                       // Draw RNA
+                       renderRNA(g2D, getClip(), true, _conf._autoCenter);
+               }
+               if (_selectionRectangle != null) {
+                       g2D.setColor(Color.BLACK);
+                       g2D.setSelectionStroke();
+                       g2D.drawRect(_selectionRectangle.x, _selectionRectangle.y,
+                                       _selectionRectangle.width, _selectionRectangle.height);
+               }
+               if ((_linkOrigin != null) && (_linkDestination != null)) {
+                       g2D.setColor(_conf._bondColor);
+                       g2D.setPlainStroke();
+                       g2D.setStrokeThickness(3.0 * scaleFactor);
+                       Point2D.Double linkOrigin = (_linkOrigin);
+                       Point2D.Double linkDestination = (_linkDestination);
+                       g2D.drawLine(linkOrigin.x, linkOrigin.y, linkDestination.x,
+                                       linkDestination.y);
+                       for (int i : getSelection().getIndices())
+                               drawBase(g2D, i, _realCoords, _realCenters, scaleFactor
+                                               * _RNA.BASE_RADIUS, scaleFactor, true);
+               }
+
+               if (_debug) {
+                       g2D.setStrokeThickness(3.0 * scaleFactor);
+                       g2D.setColor(Color.black);
+                       Point2D.Double t = this.logicToPanel(_target);
+                       g2D.drawLine(t.x - 3, t.y - 3, t.x + 3, t.y + 3);
+                       g2D.drawLine(t.x - 3, t.y + 3, t.x + 3, t.y - 3);
+                       g2D.setColor(Color.red);
+                       t = this.logicToPanel(_target2);
+                       g2D.drawLine(t.x - 3, t.y - 3, t.x + 3, t.y + 3);
+                       g2D.drawLine(t.x - 3, t.y + 3, t.x + 3, t.y - 3);
+               }
+       }
+
+       public void drawRegionHighlightsAnnotation(VueVARNAGraphics g2D,
+                       Point2D.Double[] realCoords, Point2D.Double[] realCenters,
+                       double scaleFactor) {
+               g2D.setStrokeThickness(2.0 * scaleFactor);
+               g2D.setPlainStroke();
+               for (HighlightRegionAnnotation r : _RNA.getHighlightRegion()) {
+                       GeneralPath s = r.getShape(realCoords, realCenters, scaleFactor);
+                       g2D.setColor(r.getFillColor());
+                       g2D.fill(s);
+                       g2D.setColor(r.getOutlineColor());
+                       g2D.draw(s);
+               }
+       }
+
+       private Rectangle2D.Double getClip() {
+               return new Rectangle2D.Double(getLeftOffset(), getTopOffset(),
+                               this.getInnerWidth(), this.getInnerHeight());
+       }
+
+       public Rectangle2D.Double getViewClip() {
+               return new Rectangle2D.Double(this.getLeftOffset(),
+                               this.getTopOffset(), this.getInnerWidth(),
+                               this.getInnerHeight());
+       }
+
+       /**
+        * Returns the color used to draw backbone bounds.
+        * 
+        * @return The color used to draw backbone bounds
+        */
+       public Color getBackboneColor() {
+               return _conf._backboneColor;
+       }
+
+       /**
+        * Sets the color to be used for drawing backbone interactions.
+        * 
+        * @param backbone_color
+        *            The new color for the backbone bounds
+        */
+       public void setBackboneColor(Color backbone_color) {
+               _conf._backboneColor = backbone_color;
+       }
+
+       /**
+        * Returns the color used to display hydrogen bonds (base pairings)
+        * 
+        * @return The color of hydrogen bonds
+        */
+       public Color getBondColor() {
+               return _conf._bondColor;
+       }
+
+       /**
+        * Returns the title of this panel
+        * 
+        * @return The title
+        */
+       public String getTitle() {
+               return _RNA.getName();
+       }
+
+       /**
+        * Sets the new color to be used for hydrogen bonds (base pairings)
+        * 
+        * @param bond_color
+        *            The new color for hydrogen bonds
+        */
+       public void setDefaultBPColor(Color bond_color) {
+               _conf._bondColor = bond_color;
+       }
+
+       /**
+        * Sets the size of the border, i.e. the empty space between the end of the
+        * drawing area and the actual border.
+        * 
+        * @param b
+        *            The new border size
+        */
+       public void setBorderSize(Dimension b) {
+               _border = b;
+       }
+
+       /**
+        * Returns the size of the border, i.e. the empty space between the end of
+        * the drawing area
+        * 
+        * @return The border size
+        */
+       public Dimension getBorderSize() {
+               return _border;
+       }
+
+       /**
+        * Sets the RNA to be displayed within this Panel. This method does not use
+        * a drawing algorithm to reassigns base coordinates, rather assuming that
+        * the RNA was previously drawn.
+        * 
+        * @param r
+        *            An already drawn RNA to display in this panel
+        */
+       public synchronized void showRNA(RNA r) {
+               fireUINewStructure(r);
+               _RNA = r;
+       }
+
+       /**
+        * Sets the RNA secondary structure to be drawn in this panel, using the
+        * default layout algorithm. In addition to the raw nucleotides sequence,
+        * the secondary structure is given in the so-called "Dot-bracket notation"
+        * (DBN) format. This format is a well-parenthesized word over the alphabet
+        * '(',')','.'.<br/>
+        * Ex:<code>((((((((....))))..(((((...))).))))))</code><br />
+        * Returns <code>true</code> if the sequence/structure couple could be
+        * parsed into a valid secondary structure, and <code>false</code>
+        * otherwise.
+        * 
+        * @param seq
+        *            The raw nucleotides sequence
+        * @param str
+        *            The secondary structure
+        * @throws ExceptionNonEqualLength
+        */
+       public void drawRNA(String seq, String str) throws ExceptionNonEqualLength {
+               drawRNA(seq, str, _RNA.get_drawMode());
+       }
+
+       /**
+        * Sets the RNA secondary structure to be drawn in this panel, using a given
+        * layout algorithm.
+        * 
+        * @param r
+        *            The new secondary structure
+        * @param drawMode
+        *            The drawing algorithm
+        */
+       public void drawRNA(RNA r, int drawMode) {
+               r.setDrawMode(drawMode);
+               drawRNA(r);
+       }
+
+       /**
+        * Redraws the current RNA. This reassigns base coordinates to their default
+        * value using the current drawing algorithm.
+        */
+
+       public void drawRNA() {
+               try {
+                       _RNA.drawRNA(_RNA.get_drawMode(), _conf);
+               } catch (ExceptionNAViewAlgorithm e) {
+                       errorDialog(e);
+                       e.printStackTrace();
+               }
+               repaint();
+       }
+
+       /**
+        * Sets the RNA secondary structure to be drawn in this panel, using the
+        * current drawing algorithm.
+        * 
+        * @param r
+        *            The new secondary structure
+        */
+       public void drawRNA(RNA r) {
+               if (r != null) {
+                       _RNA = r;
+                       drawRNA();
+               }
+       }
+
+       /**
+        * Sets the RNA secondary structure to be drawn in this panel, using a given
+        * layout algorithm. In addition to the raw nucleotides sequence, the
+        * secondary structure is given in the so-called "Dot-bracket notation"
+        * (DBN) format. This format is a well-parenthesized word over the alphabet
+        * '(',')','.'.<br/>
+        * Ex: <code>((((((((....))))..(((((...))).))))))</code><br />
+        * Returns <code>true</code> if the sequence/structure couple could be
+        * parsed into a valid secondary structure, and <code>false</code>
+        * otherwise.
+        * 
+        * @param seq
+        *            The raw nucleotides sequence
+        * @param str
+        *            The secondary structure
+        * @param drawMode
+        *            The drawing algorithm
+        * @throws ExceptionNonEqualLength
+        */
+       public void drawRNA(String seq, String str, int drawMode)
+                       throws ExceptionNonEqualLength {
+               _RNA.setDrawMode(drawMode);
+               try {
+                       _RNA.setRNA(seq, str);
+                       drawRNA();
+               } catch (ExceptionUnmatchedClosingParentheses e) {
+                       errorDialog(e);
+               } catch (ExceptionFileFormatOrSyntax e1) {
+                       errorDialog(e1);
+               }
+       }
+
+       public void drawRNA(Reader r, int drawMode) throws ExceptionNonEqualLength,
+                       ExceptionFileFormatOrSyntax {
+               _RNA.setDrawMode(drawMode);
+               Collection<RNA> rnas = RNAFactory.loadSecStr(r);
+               if (rnas.isEmpty()) {
+                       throw new ExceptionFileFormatOrSyntax(
+                                       "No RNA could be parsed from that source.");
+               }
+               _RNA = rnas.iterator().next();
+               drawRNA();
+       }
+
+       /**
+        * Draws a secondary structure of RNA using the default drawing algorithm
+        * and displays it, using an interpolated transition between the previous
+        * one and the new one. Extra bases, resulting from a size difference
+        * between the two successive RNAs, are assumed to initiate from the middle
+        * of the sequence. In other words, both prefixes and suffixes of the RNAs
+        * are assumed to match, and what remains is an insertion.
+        * 
+        * @param seq
+        *            Sequence
+        * @param str
+        *            Structure in dot bracket notation
+        * @throws ExceptionNonEqualLength
+        *             If len(seq)!=len(str)
+        */
+       public void drawRNAInterpolated(String seq, String str)
+                       throws ExceptionNonEqualLength {
+               drawRNAInterpolated(seq, str, _RNA.get_drawMode());
+       }
+
+       /**
+        * Draws a secondary structure of RNA using a given algorithm and displays
+        * it, using an interpolated transition between the previous one and the new
+        * one. Extra bases, resulting from a size difference between the two
+        * successive RNAs, are assumed to initiate from the middle of the sequence.
+        * In other words, both prefixes and suffixes of the RNAs are assumed to
+        * match, and what remains is an insertion.
+        * 
+        * @param seq
+        *            Sequence
+        * @param str
+        *            Structure in dot bracket notation
+        * @param drawMode
+        *            The drawing algorithm to be used for the initial placement
+        * @throws ExceptionNonEqualLength
+        *             If len(seq)!=len(str)
+        */
+       public void drawRNAInterpolated(String seq, String str, int drawMode) {
+               drawRNAInterpolated(seq, str, drawMode,
+                               Mapping.DefaultOutermostMapping(_RNA.get_listeBases().size(),
+                                               str.length()));
+       }
+
+       /**
+        * Draws a secondary structure of RNA using the default drawing algorithm
+        * and displays it, using an interpolated transition between the previous
+        * one and the new one. Here, a mapping between those bases of the new
+        * structure and the previous one is explicitly provided.
+        * 
+        * @param seq
+        *            Sequence
+        * @param str
+        *            Structure in dot bracket notation
+        * @param m
+        *            A mapping between the currently rendered structure and its
+        *            successor (seq,str)
+        * @throws ExceptionNonEqualLength
+        *             If len(seq)!=len(str)
+        */
+       public void drawRNAInterpolated(String seq, String str, Mapping m) {
+               drawRNAInterpolated(seq, str, _RNA.get_drawMode(), m);
+       }
+
+       /**
+        * Draws a secondary structure of RNA using a given drawing algorithm and
+        * displays it, using an interpolated transition between the previous one
+        * and the new one. Here, a mapping between those bases of the new structure
+        * and the previous one is provided.
+        * 
+        * @param seq
+        *            Sequence
+        * @param str
+        *            Structure in dot bracket notation
+        * @param drawMode
+        *            The drawing algorithm to be used for the initial placement
+        * @param m
+        *            A mapping between the currently rendered structure and its
+        *            successor (seq,str)
+        */
+       public void drawRNAInterpolated(String seq, String str, int drawMode,
+                       Mapping m) {
+               RNA target = new RNA();
+               try {
+                       target.setRNA(seq, str);
+                       drawRNAInterpolated(target, drawMode, m);
+               } catch (ExceptionUnmatchedClosingParentheses e) {
+                       errorDialog(e);
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       errorDialog(e);
+               }
+       }
+
+       /**
+        * Draws a secondary structure of RNA using the default drawing algorithm
+        * and displays it, using an interpolated transition between the previous
+        * one and the new one. Here, a mapping between those bases of the new
+        * structure and the previous one is explicitly provided.
+        * 
+        * @param target
+        *            Secondary structure
+        */
+       public void drawRNAInterpolated(RNA target) {
+               drawRNAInterpolated(target, target.get_drawMode(),
+                               Mapping.DefaultOutermostMapping(_RNA.get_listeBases().size(),
+                                               target.getSize()));
+       }
+
+       /**
+        * Draws a secondary structure of RNA using the default drawing algorithm
+        * and displays it, using an interpolated transition between the previous
+        * one and the new one. Here, a mapping between those bases of the new
+        * structure and the previous one is explicitly provided.
+        * 
+        * @param target
+        *            Secondary structure
+        * @param m
+        *            A mapping between the currently rendered structure and its
+        *            successor (seq,str)
+        */
+       public void drawRNAInterpolated(RNA target, Mapping m) {
+               drawRNAInterpolated(target, target.get_drawMode(), m);
+       }
+
+       /**
+        * Draws a secondary structure of RNA using a given drawing algorithm and
+        * displays it, using an interpolated transition between the previous one
+        * and the new one. Here, a mapping between those bases of the new structure
+        * and the previous one is provided.
+        * 
+        * @param target
+        *            Secondary structure of RNA
+        * @param drawMode
+        *            The drawing algorithm to be used for the initial placement
+        * @param m
+        *            A mapping between the currently rendered structure and its
+        *            successor (seq,str)
+        */
+       public void drawRNAInterpolated(RNA target, int drawMode, Mapping m) {
+               try {
+                       target.drawRNA(drawMode, _conf);
+                       _conf._drawColorMap = false;
+                       _interpolator.addTarget(target, m);
+               } catch (ExceptionNAViewAlgorithm e) {
+                       errorDialog(e);
+                       e.printStackTrace();
+               }
+       }
+
+       /**
+        * Returns the current algorithm used for drawing the structure
+        * 
+        * @return The current drawing algorithm
+        */
+       public int getDrawMode() {
+               return this._RNA.getDrawMode();
+       }
+
+       public void showRNA(RNA t, VARNAConfig cfg) {
+               showRNA(t);
+               if (cfg != null) {
+                       this.setConfig(cfg);
+               }
+               repaint();
+       }
+
+       /**
+        * Checks whether an interpolated transition bewteen two RNAs is occurring.
+        * 
+        * @return True if an interpolated transition is occurring, false otherwise
+        */
+
+       public boolean isInterpolationInProgress() {
+               if (_interpolator == null) {
+                       return false;
+               } else
+                       return _interpolator.isInterpolationInProgress();
+       }
+
+       /**
+        * Simply displays (does not redraw) a secondary structure , using an
+        * interpolated transition between the previous one and the new one. A
+        * default mapping between those bases of the new structure and the previous
+        * one is used.
+        * 
+        * @param target
+        *            Secondary structure of RNA
+        */
+       public void showRNAInterpolated(RNA target) {
+               showRNAInterpolated(target, Mapping.DefaultOutermostMapping(_RNA
+                               .get_listeBases().size(), target.getSize()));
+       }
+
+       /**
+        * Simply displays (does not redraw) a secondary structure , using an
+        * interpolated transition between the previous one and the new one. Here, a
+        * mapping between bases of the new structure and the previous one is given.
+        * 
+        * @param target
+        *            Secondary structure of RNA
+        * @param m
+        *            A mapping between the currently rendered structure and its
+        *            successor (seq,str)
+        * @throws ExceptionNonEqualLength
+        *             If len(seq)!=len(str)
+        */
+       public void showRNAInterpolated(RNA target, Mapping m) {
+               showRNAInterpolated(target, null, m);
+       }
+
+       public void showRNAInterpolated(RNA target, VARNAConfig cfg, Mapping m) {
+               _interpolator.addTarget(target, cfg, m);
+       }
+
+       /**
+        * When comparison mode is ON, sets the two RNA secondary structure to be
+        * drawn in this panel, using a given layout algorithm. In addition to the
+        * raw nucleotides sequence, the secondary structure is given in the
+        * so-called "Dot-bracket notation" (DBN) format. This format is a
+        * well-parenthesized word over the alphabet '(',')','.'.<br/>
+        * Ex: <code>((((((((....))))..(((((...))).))))))</code><br />
+        * 
+        * @param firstSeq
+        *            The first RNA raw nucleotides sequence
+        * @param firstStruct
+        *            The first RNA secondary structure
+        * @param secondSeq
+        *            The second RNA raw nucleotides sequence
+        * @param secondStruct
+        *            The second RNA secondary structure
+        * @param drawMode
+        *            The drawing algorithm
+        */
+       public void drawRNA(String firstSeq, String firstStruct, String secondSeq,
+                       String secondStruct, int drawMode) {
+               _RNA.setDrawMode(drawMode);
+               /**
+                * Checking the sequences and structures validities...
+                */
+
+               // This is a comparison, so the two RNA alignment past in parameters
+               // must
+               // have the same sequence and structure length.
+               if (firstSeq.length() == secondSeq.length()
+                               && firstStruct.length() == secondStruct.length()) {
+                       // First RNA
+                       if (firstSeq.length() != firstStruct.length()) {
+                               if (_conf._showWarnings) {
+                                       emitWarning("First sequence length " + firstSeq.length()
+                                                       + " differs from that of it's secondary structure "
+                                                       + firstStruct.length()
+                                                       + ". \nAdapting first sequence length ...");
+                               }
+                               if (firstSeq.length() < firstStruct.length()) {
+                                       while (firstSeq.length() < firstStruct.length()) {
+                                               firstSeq += " ";
+                                       }
+                               } else {
+                                       firstSeq = firstSeq.substring(0, firstStruct.length());
+                               }
+                       }
+
+                       // Second RNA
+                       if (secondSeq.length() != secondStruct.length()) {
+                               if (_conf._showWarnings) {
+                                       emitWarning("Second sequence length " + secondSeq.length()
+                                                       + " differs from that of it's secondary structure "
+                                                       + secondStruct.length()
+                                                       + ". \nAdapting second sequence length ...");
+                               }
+                               if (secondSeq.length() < secondStruct.length()) {
+                                       while (secondSeq.length() < secondStruct.length()) {
+                                               secondSeq += " ";
+                                       }
+                               } else {
+                                       secondSeq = secondSeq.substring(0, secondStruct.length());
+                               }
+                       }
+
+                       int RNALength = firstSeq.length();
+                       String string_superStruct = new String("");
+                       String string_superSeq = new String("");
+                       /**
+                        * In this array, we'll have for each indexes of each characters of
+                        * the final super-structure, the RNA number which is own it.
+                        */
+                       ArrayList<Integer> array_rnaOwn = new ArrayList<Integer>();
+
+                       /**
+                        * Generating super-structure sequences and structures...
+                        */
+
+                       firstStruct = firstStruct.replace('-', '.');
+                       secondStruct = secondStruct.replace('-', '.');
+                       // First of all, we make the structure
+                       for (int i = 0; i < RNALength; i++) {
+                               // If both characters are the same, so it'll be in the super
+                               // structure
+                               if (firstStruct.charAt(i) == secondStruct.charAt(i)) {
+                                       string_superStruct = string_superStruct
+                                                       + firstStruct.charAt(i);
+                                       array_rnaOwn.add(0);
+                               }
+                               // Else if one of the characters is an opening parenthese, so
+                               // it'll be an opening parenthese in the super structure
+                               else if (firstStruct.charAt(i) == '('
+                                               || secondStruct.charAt(i) == '(') {
+                                       string_superStruct = string_superStruct + '(';
+                                       array_rnaOwn.add((firstStruct.charAt(i) == '(') ? 1 : 2);
+                               }
+                               // Else if one of the characters is a closing parenthese, so
+                               // it'll be a closing parenthese in the super structure
+                               else if (firstStruct.charAt(i) == ')'
+                                               || secondStruct.charAt(i) == ')') {
+                                       string_superStruct = string_superStruct + ')';
+                                       array_rnaOwn.add((firstStruct.charAt(i) == ')') ? 1 : 2);
+                               } else {
+                                       string_superStruct = string_superStruct + '.';
+                                       array_rnaOwn.add(-1);
+                               }
+                       }
+
+                       // Next, we make the sequence taking the characters at the same
+                       // index in the first and second sequence
+                       for (int i = 0; i < RNALength; i++) {
+                               string_superSeq = string_superSeq + firstSeq.charAt(i)
+                                               + secondSeq.charAt(i);
+                       }
+
+                       // Now, we need to create the super-structure RNA with the owning
+                       // bases array
+                       // in order to color bases outer depending on the owning statement
+                       // of each bases.
+                       if (!string_superSeq.equals("") && !string_superStruct.equals("")) {
+                               try {
+                                       _RNA.setRNA(string_superSeq, string_superStruct,
+                                                       array_rnaOwn);
+                               } catch (ExceptionUnmatchedClosingParentheses e) {
+                                       errorDialog(e);
+                               } catch (ExceptionFileFormatOrSyntax e) {
+                                       errorDialog(e);
+                               }
+                       } else {
+                               emitWarning("ERROR : The super-structure is NULL.");
+                       }
+
+                       switch (_RNA.get_drawMode()) {
+                       case RNA.DRAW_MODE_RADIATE:
+                               _RNA.drawRNARadiate(_conf);
+                               break;
+                       case RNA.DRAW_MODE_CIRCULAR:
+                               _RNA.drawRNACircle(_conf);
+                               break;
+                       case RNA.DRAW_MODE_LINEAR:
+                               _RNA.drawRNALine(_conf);
+                               break;
+                       case RNA.DRAW_MODE_NAVIEW:
+                               try {
+                                       _RNA.drawRNANAView(_conf);
+                               } catch (ExceptionNAViewAlgorithm e) {
+                                       errorDialog(e);
+                               }
+                               break;
+                       default:
+                               break;
+                       }
+
+               }
+       }
+
+       /**
+        * Returns the currently selected base index, obtained through a mouse-left
+        * click
+        * 
+        * @return Selected base
+        * 
+        *         public int getSelectedBaseIndex() { return _selectedBase; }
+        * 
+        *         /** Returns the currently selected base, obtained through a
+        *         mouse-left click
+        * 
+        * @return Selected base
+        * 
+        *         public ModeleBase getSelectedBase() { return
+        *         _RNA.get_listeBases().get(_selectedBase); }
+        * 
+        *         /** Sets the selected base index
+        * 
+        * @param base
+        *            New selected base index
+        * 
+        *            public void setSelectedBase(int base) { _selectedBase = base;
+        *            }
+        */
+
+       /**
+        * Returns the coordinates of the currently displayed RNA
+        * 
+        * @return Coordinates array
+        */
+       public Point2D.Double[] getRealCoords() {
+               return _realCoords;
+       }
+
+       /**
+        * Sets the coordinates of the currently displayed RNA
+        * 
+        * @param coords
+        *            New coordinates
+        */
+       public void setRealCoords(Point2D.Double[] coords) {
+               _realCoords = coords;
+       }
+
+       /**
+        * Returns the popup menu used for user mouse iteractions
+        * 
+        * @return Popup menu
+        */
+       public VueMenu getPopup() {
+               return _popup;
+       }
+
+       /**
+        * Sets the color used to display hydrogen bonds (base pairings)
+        * 
+        * @param bond_color
+        *            The color of hydrogen bonds
+        */
+       public void setBondColor(Color bond_color) {
+               _conf._bondColor = bond_color;
+       }
+
+       /**
+        * Returns the color used to draw the title
+        * 
+        * @return The color used to draw the title
+        */
+       public Color getTitleColor() {
+               return _conf._titleColor;
+       }
+
+       /**
+        * Sets the color used to draw the title
+        * 
+        * @param title_color
+        *            The new color used to draw the title
+        */
+       public void setTitleColor(Color title_color) {
+               _conf._titleColor = title_color;
+       }
+
+       /**
+        * Returns the height taken by the title
+        * 
+        * @return The height taken by the title
+        */
+       private int getTitleHeight() {
+               return _titleHeight;
+       }
+
+       /**
+        * Sets the height taken by the title
+        * 
+        * @param title_height
+        *            The height taken by the title
+        */
+       @SuppressWarnings("unused")
+       private void setTitleHeight(int title_height) {
+               _titleHeight = title_height;
+       }
+
+       /**
+        * Returns the current state of auto centering mode.
+        * 
+        * @return True if autocentered, false otherwise
+        */
+       public boolean isAutoCentered() {
+               return _conf._autoCenter;
+       }
+
+       /**
+        * Sets the current state of auto centering mode.
+        * 
+        * @param center
+        *            New auto-centered state
+        */
+       public void setAutoCenter(boolean center) {
+               _conf._autoCenter = center;
+       }
+
+       /**
+        * Returns the font currently used for rendering the title.
+        * 
+        * @return Current title font
+        */
+       public Font getTitleFont() {
+               return _conf._titleFont;
+       }
+
+       /**
+        * Sets the font used for rendering the title.
+        * 
+        * @param font
+        *            New title font
+        */
+       public void setTitleFont(Font font) {
+               _conf._titleFont = font;
+               updateTitleHeight();
+       }
+
+       /**
+        * For the LINE_MODE drawing algorithm, sets the base pair height increment,
+        * i.e. the vertical distance between two nested arcs.
+        * 
+        * @return The current base pair increment
+        */
+       public double getBPHeightIncrement() {
+               return _RNA._bpHeightIncrement;
+       }
+
+       /**
+        * Sets the base pair height increment, i.e. the vertical distance between
+        * two arcs to be used in LINE_MODE.
+        * 
+        * @param inc
+        *            New height increment
+        */
+       public void setBPHeightIncrement(double inc) {
+               _RNA._bpHeightIncrement = inc;
+       }
+
+       /**
+        * Returns the shifting of the origin of the Panel in zoom mode
+        * 
+        * @return The logical coordinate of the top-left panel point
+        */
+       public Point2D.Double getOffsetPanel() {
+               return _offsetPanel;
+       }
+
+       /**
+        * Returns the vector bringing the logical coordinate of left-top-most point
+        * in the panel to the left-top-most point of the RNA.
+        * 
+        * @return The logical coordinate of the top-left panel point
+        */
+       private Point2D.Double getRNAOffset() {
+               return _offsetRNA;
+       }
+
+       /**
+        * Returns this panel's UI menu
+        * 
+        * @return Applet's UI popupmenu
+        */
+       public VueMenu getPopupMenu() {
+               return _popup;
+       }
+
+       /**
+        * Returns the atomic zoom factor step, or increment.
+        * 
+        * @return Atomic zoom factor increment
+        */
+       public double getZoomIncrement() {
+               return _conf._zoomAmount;
+       }
+
+       /**
+        * Sets the atomic zoom factor step, or increment.
+        * 
+        * @param amount
+        *            Atomic zoom factor increment
+        */
+       public void setZoomIncrement(Object amount) {
+               setZoomIncrement(Float.valueOf(amount.toString()));
+       }
+
+       /**
+        * Sets the atomic zoom factor step, or increment.
+        * 
+        * @param amount
+        *            Atomic zoom factor increment
+        */
+       public void setZoomIncrement(double amount) {
+               _conf._zoomAmount = amount;
+       }
+
+       /**
+        * Returns the current zoom factor
+        * 
+        * @return Current zoom factor
+        */
+       public double getZoom() {
+               return _conf._zoom;
+       }
+
+       /**
+        * Sets the current zoom factor
+        * 
+        * @param _zoom
+        *            New zoom factor
+        */
+       public void setZoom(Object _zoom) {
+               double d = Float.valueOf(_zoom.toString());
+               if (_conf._zoom != d) {
+                       _conf._zoom = d;
+                       fireZoomLevelChanged(d);
+               }
+       }
+
+       /**
+        * Returns the translation used for zooming in and out
+        * 
+        * @return A vector describing the translation
+        */
+       public Point getTranslation() {
+               return _translation;
+       }
+
+       /**
+        * Sets the translation used for zooming in and out
+        * 
+        * @param trans
+        *            A vector describing the new translation
+        */
+       public void setTranslation(Point trans) {
+               _translation = trans;
+               checkTranslation();
+               fireTranslationChanged();
+       }
+
+       /**
+        * Returns the current RNA model
+        * 
+        * @return Current RNA model
+        */
+       public RNA getRNA() {
+               return _RNA;
+       }
+
+       /**
+        * Checks whether the drawn RNA is too large to be displayed, allowing for
+        * shifting mouse interactions.
+        * 
+        * @return true if the RNA is too large to be displayed, false otherwise
+        */
+       public boolean isOutOfFrame() {
+               return _horsCadre;
+       }
+
+       /**
+        * Pops up an error Dialog displaying an exception in an human-readable way.
+        * 
+        * @param error
+        *            The exception to display within the Dialog
+        */
+       public void errorDialog(Exception error) {
+               errorDialog(error, this);
+       }
+
+       /**
+        * Pops up an error Dialog displaying an exception in an human-readable way
+        * if errors are set to be displayed.
+        * 
+        * @see #setErrorsOn(boolean)
+        * @param error
+        *            The exception to display within the Dialog
+        * @param c
+        *            Parent component for the dialog box
+        */
+       public void errorDialog(Exception error, Component c) {
+               if (isErrorsOn()) {
+                       JOptionPane.showMessageDialog(c, error.getMessage(), "VARNA Error",
+                                       JOptionPane.ERROR_MESSAGE);
+               }
+       }
+
+       /**
+        * Pops up an error Dialog displaying an exception in an human-readable way.
+        * 
+        * @param error
+        *            The exception to display within the Dialog
+        * @param c
+        *            Parent component for the dialog box
+        */
+       public static void errorDialogStatic(Exception error, Component c) {
+               if (c != null) {
+                       JOptionPane.showMessageDialog(c, error.getMessage(),
+                                       "VARNA Critical Error", JOptionPane.ERROR_MESSAGE);
+               } else {
+                       System.err.println("Error: " + error.getMessage());
+               }
+       }
+
+       /**
+        * Displays a warning message through a modal dialog if warnings are set to
+        * be displayed.
+        * 
+        * @see #setShowWarnings(boolean)
+        * @param warning
+        *            A message expliciting the warning
+        */
+       public void emitWarning(String warning) {
+               if (_conf._showWarnings)
+                       JOptionPane.showMessageDialog(this, warning, "VARNA Warning",
+                                       JOptionPane.WARNING_MESSAGE);
+       }
+
+       public static void emitWarningStatic(Exception e, Component c) {
+               emitWarningStatic(e.getMessage(), c);
+       }
+
+       public static void emitWarningStatic(String warning, Component c) {
+               if (c != null) {
+                       JOptionPane.showMessageDialog(c, warning, "VARNA Warning",
+                                       JOptionPane.WARNING_MESSAGE);
+               } else {
+                       System.err.println("Error: " + warning);
+               }
+       }
+
+       /**
+        * Toggles modifications on and off
+        * 
+        * @param modifiable
+        *            Modification status
+        */
+       public void setModifiable(boolean modifiable) {
+               _conf._modifiable = modifiable;
+       }
+
+       /**
+        * Returns current modification status
+        * 
+        * @return current modification status
+        */
+       public boolean isModifiable() {
+               return _conf._modifiable;
+       }
+
+       /**
+        * Resets the visual aspects (Zoom factor, shift) for the Panel.
+        */
+       public void reset() {
+               this.setBorderSize(new Dimension(0, 0));
+               this.setTranslation(new Point(0, (int) (-getTitleHeight() / 2.0)));
+               this.setZoom(VARNAConfig.DEFAULT_ZOOM);
+               this.setZoomIncrement(VARNAConfig.DEFAULT_AMOUNT);
+       }
+
+       /**
+        * Returns the color used to draw non-standard bases
+        * 
+        * @return The color used to draw non-standard bases
+        */
+       public Color getNonStandardBasesColor() {
+               return _conf._specialBasesColor;
+       }
+
+       /**
+        * Sets the color used to draw non-standard bases
+        * 
+        * @param basesColor
+        *            The color used to draw non-standard bases
+        */
+       public void setNonStandardBasesColor(Color basesColor) {
+               _conf._specialBasesColor = basesColor;
+       }
+
+       /**
+        * Checks if the current translation doesn't "kick" the whole RNA out of the
+        * panel, and corrects the situation if necessary.
+        */
+       public void checkTranslation() {
+               // verification pour un zoom < 1
+               if (this.getZoom() <= 1) {
+                       // verification sortie gauche
+                       if (this.getTranslation().x < -(int) ((this.getWidth() - this
+                                       .getInnerWidth()) / 2.0)) {
+                               this.setTranslation(new Point(-(int) ((this.getWidth() - this
+                                               .getInnerWidth()) / 2.0), this.getTranslation().y));
+                       }
+                       // verification sortie droite
+                       if (this.getTranslation().x > (int) ((this.getWidth() - this
+                                       .getInnerWidth()) / 2.0)) {
+                               this.setTranslation(new Point((int) ((this.getWidth() - this
+                                               .getInnerWidth()) / 2.0), this.getTranslation().y));
+                       }
+                       // verification sortie bas
+                       if (this.getTranslation().y > (int) ((this.getHeight()
+                                       - getTitleHeight() * 2 - this.getInnerHeight()) / 2.0)) {
+                               this.setTranslation(new Point(this.getTranslation().x,
+                                               (int) ((this.getHeight() - getTitleHeight() * 2 - this
+                                                               .getInnerHeight()) / 2.0)));
+                       }
+                       // verification sortie haut
+                       if (this.getTranslation().y < -(int) ((this.getHeight() - this
+                                       .getInnerHeight()) / 2.0)) {
+                               this.setTranslation(new Point(
+                                               this.getTranslation().x,
+                                               -(int) ((this.getHeight() - this.getInnerHeight()) / 2.0)));
+                       }
+               } else {
+                       // zoom > 1
+                       Rectangle r2 = getZoomedInTranslationBox();
+                       int LBoundX = r2.x;
+                       int UBoundX = r2.x + r2.width;
+                       int LBoundY = r2.y;
+                       int UBoundY = r2.y + r2.height;
+                       if (this.getTranslation().x < LBoundX) {
+                               this.setTranslation(new Point(LBoundX, getTranslation().y));
+                       } else if (this.getTranslation().x > UBoundX) {
+                               this.setTranslation(new Point(UBoundX, getTranslation().y));
+                       }
+                       if (this.getTranslation().y < LBoundY) {
+                               this.setTranslation(new Point(getTranslation().x, LBoundY));
+                       } else if (this.getTranslation().y > UBoundY) {
+                               this.setTranslation(new Point(getTranslation().x, UBoundY));
+                       }
+               }
+       }
+
+       public Rectangle getZoomedInTranslationBox() {
+               int LBoundX = -(int) ((this.getInnerWidth()) / 2.0);
+               int UBoundX = (int) ((this.getInnerWidth()) / 2.0);
+               int LBoundY = -(int) ((this.getInnerHeight()) / 2.0);
+               int UBoundY = (int) ((this.getInnerHeight()) / 2.0);
+               return new Rectangle(LBoundX, LBoundY, UBoundX - LBoundX, UBoundY
+                               - LBoundY);
+
+       }
+
+       /**
+        * Returns the "real pixels" x-coordinate of the RNA.
+        * 
+        * @return X-coordinate of the translation
+        */
+       public int getLeftOffset() {
+               return _border.width
+                               + ((this.getWidth() - 2 * _border.width) - this.getInnerWidth())
+                               / 2 + _translation.x;
+       }
+
+       /**
+        * Returns the "real pixels" width of the drawing surface for our RNA.
+        * 
+        * @return Width of the drawing surface for our RNA
+        */
+       public int getInnerWidth() {
+               // Largeur du dessin
+               return (int) Math.round((this.getWidth() - 2 * _border.width)
+                               * _conf._zoom);
+       }
+
+       /**
+        * Returns the "real pixels" y-coordinate of the RNA.
+        * 
+        * @return Y-coordinate of the translation
+        */
+       public int getTopOffset() {
+               return _border.height
+                               + ((this.getHeight() - 2 * _border.height) - this
+                                               .getInnerHeight()) / 2 + _translation.y;
+       }
+
+       /**
+        * Returns the "real pixels" height of the drawing surface for our RNA.
+        * 
+        * @return Height of the drawing surface for our RNA
+        */
+       public int getInnerHeight() {
+               // Hauteur du dessin
+               return (int) Math.round((this.getHeight()) * _conf._zoom - 2
+                               * _border.height - getTitleHeight());
+       }
+
+       /**
+        * Checks if the current mode is the "comparison" mode
+        * 
+        * @return True if comparison, false otherwise
+        */
+       public boolean isComparisonMode() {
+               return _conf._comparisonMode;
+       }
+
+       /**
+        * Rotates the RNA coordinates by a certain angle
+        * 
+        * @param angleDegres
+        *            Rotation angle, in degrees
+        */
+       public void globalRotation(Double angleDegres) {
+               _RNA.globalRotation(angleDegres);
+               fireLayoutChanged();
+               repaint();
+       }
+
+       /**
+        * Returns the index of the currently selected base, defaulting to the
+        * closest base to the last mouse-click.
+        * 
+        * @return Index of the currently selected base
+        */
+       public Integer getNearestBase() {
+               return _nearestBase;
+       }
+
+       /**
+        * Sets the index of the currently selected base.
+        * 
+        * @param base
+        *            Index of the new selected base
+        */
+       public void setNearestBase(Integer base) {
+               _nearestBase = base;
+       }
+
+       /**
+        * Returns the color used to draw 'Gaps' bases in comparison mode
+        * 
+        * @return Color used for 'Gaps'
+        */
+       public Color getGapsBasesColor() {
+               return _conf._dashBasesColor;
+       }
+
+       /**
+        * Sets the color to use for 'Gaps' bases in comparison mode
+        * 
+        * @param c
+        *            Color used for 'Gaps'
+        */
+       public void setGapsBasesColor(Color c) {
+               _conf._dashBasesColor = c;
+       }
+
+       @SuppressWarnings("unused")
+       private void imprimer() {
+               // PrintPanel canvas;
+               // canvas = new PrintPanel();
+               PrintRequestAttributeSet attributes;
+               attributes = new HashPrintRequestAttributeSet();
+               try {
+                       PrinterJob job = PrinterJob.getPrinterJob();
+                       // job.setPrintable(this);
+                       if (job.printDialog(attributes)) {
+                               job.print(attributes);
+                       }
+               } catch (PrinterException exception) {
+                       errorDialog(exception);
+               }
+       }
+
+       /**
+        * Checks whether errors are to be displayed
+        * 
+        * @return Error display status
+        */
+       public boolean isErrorsOn() {
+               return _conf._errorsOn;
+       }
+
+       /**
+        * Sets whether errors are to be displayed
+        * 
+        * @param on
+        *            New error display status
+        */
+       public void setErrorsOn(boolean on) {
+               _conf._errorsOn = on;
+       }
+
+       /**
+        * Returns the view associated with user interactions
+        * 
+        * @return A view associated with user interactions
+        */
+       public VueUI getVARNAUI() {
+               return _UI;
+       }
+
+       /**
+        * Toggles on/off using base inner color for drawing base-pairs
+        * 
+        * @param on
+        *            True for using base inner color for drawing base-pairs, false
+        *            for classic mode
+        */
+       public void setUseBaseColorsForBPs(boolean on) {
+               _conf._useBaseColorsForBPs = on;
+       }
+
+       /**
+        * Returns true if current base color is used as inner color for drawing
+        * base-pairs
+        * 
+        * @return True for using base inner color for drawing base-pairs, false for
+        *         classic mode
+        */
+       public boolean getUseBaseColorsForBPs() {
+               return _conf._useBaseColorsForBPs;
+       }
+
+       /**
+        * Toggles on/off using a special color used for drawing "non-standard"
+        * bases
+        * 
+        * @param on
+        *            True for using a special color used for drawing "non-standard"
+        *            bases, false for classic mode
+        */
+       public void setColorNonStandardBases(boolean on) {
+               _conf._colorSpecialBases = on;
+       }
+
+       /**
+        * Returns true if a special color is used as inner color for non-standard
+        * base
+        * 
+        * @return True for using a special color used for drawing "non-standard"
+        *         bases, false for classic mode
+        */
+       public boolean getColorSpecialBases() {
+               return _conf._colorSpecialBases;
+       }
+
+       /**
+        * Toggles on/off using a special color used for drawing "Gaps" bases in
+        * comparison mode
+        * 
+        * @param on
+        *            True for using a special color used for drawing "Gaps" bases
+        *            in comparison mode, false for classic mode
+        */
+       public void setColorGapsBases(boolean on) {
+               _conf._colorDashBases = on;
+       }
+
+       /**
+        * Returns true if a special color is used for drawing "Gaps" bases in
+        * comparison mode
+        * 
+        * @return True for using a special color used for drawing "Gaps" bases in
+        *         comparison mode, false for classic mode
+        */
+       public boolean getColorGapsBases() {
+               return _conf._colorDashBases;
+       }
+
+       /**
+        * Toggles on/off displaying warnings
+        * 
+        * @param on
+        *            True to display warnings, false otherwise
+        */
+       public void setShowWarnings(boolean on) {
+               _conf._showWarnings = on;
+       }
+
+       /**
+        * Get current warning display status
+        * 
+        * @return True to display warnings, false otherwise
+        */
+       public boolean getShowWarnings() {
+               return _conf._showWarnings;
+       }
+
+       /**
+        * Toggles on/off displaying non-canonical base-pairs
+        * 
+        * @param on
+        *            True to display NC base-pairs, false otherwise
+        */
+       public void setShowNonCanonicalBP(boolean on) {
+               _conf._drawnNonCanonicalBP = on;
+       }
+
+       /**
+        * Return the current display status for non-canonical base-pairs
+        * 
+        * @return True if NC base-pairs are displayed, false otherwise
+        */
+       public boolean getShowNonCanonicalBP() {
+               return _conf._drawnNonCanonicalBP;
+       }
+
+       /**
+        * Toggles on/off displaying "non-planar" base-pairs
+        * 
+        * @param on
+        *            True to display "non-planar" base-pairs, false otherwise
+        */
+       public void setShowNonPlanarBP(boolean on) {
+               _conf._drawnNonPlanarBP = on;
+       }
+
+       /**
+        * Return the current display status for non-planar base-pairs
+        * 
+        * @return True if non-planars base-pairs are displayed, false otherwise
+        */
+       public boolean getShowNonPlanarBP() {
+               return _conf._drawnNonPlanarBP;
+       }
+
+       /**
+        * Sets the base-pair representation style
+        * 
+        * @param st
+        *            The new base-pair style
+        */
+       public void setBPStyle(VARNAConfig.BP_STYLE st) {
+               _conf._mainBPStyle = st;
+       }
+
+       /**
+        * Returns the base-pair representation style
+        * 
+        * @return The current base-pair style
+        */
+       public VARNAConfig.BP_STYLE getBPStyle() {
+               return _conf._mainBPStyle;
+       }
+
+       /**
+        * Returns the current VARNA Panel configuration. The returned instance
+        * should not be modified directly, but rather through the getters/setters
+        * from the VARNAPanel class.
+        * 
+        * @return Current configuration
+        */
+       public VARNAConfig getConfig() {
+               return _conf;
+       }
+
+       /**
+        * Sets the background color
+        * 
+        * @param c
+        *            New background color
+        */
+       public void setBackground(Color c) {
+               if (_conf != null) {
+                       if (c != null) {
+                               _conf._backgroundColor = c;
+                               _conf._drawBackground = (!c
+                                               .equals(VARNAConfig.DEFAULT_BACKGROUND_COLOR));
+                       } else {
+                               _conf._backgroundColor = VARNAConfig.DEFAULT_BACKGROUND_COLOR;
+                               _conf._drawBackground = false;
+                       }
+               }
+
+       }
+
+       /**
+        * Starts highlighting the selected base.
+        */
+       public void highlightSelectedBase(ModeleBase m) {
+               ArrayList<Integer> v = new ArrayList<Integer>();
+               int sel = m.getIndex();
+               if (sel != -1) {
+                       v.add(sel);
+               }
+               setSelection(v);
+       }
+
+       /**
+        * Starts highlighting the selected base.
+        */
+       public void highlightSelectedStem(ModeleBase m) {
+               ArrayList<Integer> v = new ArrayList<Integer>();
+               int sel = m.getIndex();
+               if (sel != -1) {
+                       ArrayList<Integer> r = _RNA.findStem(sel);
+                       v.addAll(r);
+               }
+               setSelection(v);
+       }
+
+       public BaseList getSelection() {
+               return _selectedBases;
+       }
+
+       public ArrayList<Integer> getSelectionIndices() {
+               return _selectedBases.getIndices();
+       }
+
+       public void setSelection(ArrayList<Integer> indices) {
+               setSelection(_RNA.getBasesAt(indices));
+       }
+
+       public void setSelection(Collection<? extends ModeleBase> mbs) {
+               BaseList bck = new BaseList(_selectedBases);
+               _selectedBases.clear();
+               _selectedBases.addBases(mbs);
+               _blink.setActive(true);
+               fireSelectionChanged(bck, _selectedBases);
+       }
+
+       public ArrayList<Integer> getBasesInRectangleDiff(Rectangle recIn,
+                       Rectangle recOut) {
+               ArrayList<Integer> result = new ArrayList<Integer>();
+               for (int i = 0; i < _realCoords.length; i++) {
+                       if (recIn.contains(_realCoords[i])
+                                       ^ recOut.contains(_realCoords[i]))
+                               result.add(i);
+               }
+               return result;
+       }
+
+       public ArrayList<Integer> getBasesInRectangle(Rectangle rec) {
+               ArrayList<Integer> result = new ArrayList<Integer>();
+               for (int i = 0; i < _realCoords.length; i++) {
+                       if (rec.contains(_realCoords[i]))
+                               result.add(i);
+               }
+               return result;
+       }
+
+       public void setSelectionRectangle(Rectangle rec) {
+               ArrayList<Integer> result = new ArrayList<Integer>();
+               if (_selectionRectangle != null) {
+                       result = getBasesInRectangleDiff(_selectionRectangle, rec);
+               } else {
+                       result = getBasesInRectangle(rec);
+               }
+               _selectionRectangle = new Rectangle(rec);
+               toggleSelection(result);
+               repaint();
+       }
+
+       public void removeSelectionRectangle() {
+               _selectionRectangle = null;
+       }
+
+       public void addToSelection(Collection<? extends Integer> indices) {
+               for (int i : indices) {
+                       addToSelection(i);
+               }
+       }
+
+       public void addToSelection(int i) {
+               BaseList bck = new BaseList(_selectedBases);
+               ModeleBase mb = _RNA.getBaseAt(i);
+               _selectedBases.addBase(mb);
+               _blink.setActive(true);
+               fireSelectionChanged(bck, _selectedBases);
+       }
+
+       public void removeFromSelection(int i) {
+               BaseList bck = new BaseList(_selectedBases);
+               ModeleBase mb = _RNA.getBaseAt(i);
+               _selectedBases.removeBase(mb);
+               if (_selectedBases.size() == 0) {
+                       _blink.setActive(false);
+               } else {
+                       _blink.setActive(true);
+               }
+               fireSelectionChanged(bck, _selectedBases);
+       }
+
+       public boolean isInSelection(int i) {
+               return _selectedBases.contains(_RNA.getBaseAt(i));
+       }
+
+       public void toggleSelection(int i) {
+               if (isInSelection(i))
+                       removeFromSelection(i);
+               else
+                       addToSelection(i);
+       }
+
+       public void toggleSelection(Collection<? extends Integer> indices) {
+               for (int i : indices) {
+                       toggleSelection(i);
+               }
+       }
+
+       /**
+        * Stops highlighting bases
+        */
+       public void clearSelection() {
+               BaseList bck = new BaseList(_selectedBases);
+               _selectedBases.clear();
+               _blink.setActive(false);
+               repaint();
+               fireSelectionChanged(bck, _selectedBases);
+       }
+
+       public void saveSelection() {
+               _backupSelection.clear();
+               _backupSelection.addAll(_selectedBases.getBases());
+       }
+
+       public void restoreSelection() {
+               setSelection(_backupSelection);
+       }
+
+       /**
+        * Stops highlighting bases
+        */
+       public void resetAnnotationHighlight() {
+               _highlightAnnotation = false;
+               repaint();
+       }
+
+       /**
+        * Toggles on/off a rectangular outline of the bounding box.
+        * 
+        * @param on
+        *            True to draw the bounding box, false otherwise
+        */
+       public void drawBBox(boolean on) {
+               _drawBBox = on;
+       }
+
+       /**
+        * Toggles on/off a rectangular outline of the border.
+        * 
+        * @param on
+        *            True to draw the bounding box, false otherwise
+        */
+       public void drawBorder(boolean on) {
+               _drawBorder = on;
+       }
+
+       public void setBaseInnerColor(Color c) {
+               _RNA.setBaseInnerColor(c);
+       }
+
+       public void setBaseNumbersColor(Color c) {
+               _RNA.setBaseNumbersColor(c);
+       }
+
+       public void setBaseNameColor(Color c) {
+               _RNA.setBaseNameColor(c);
+       }
+
+       public void setBaseOutlineColor(Color c) {
+               _RNA.setBaseOutlineColor(c);
+       }
+
+       public ArrayList<TextAnnotation> getListeAnnotations() {
+               return _RNA.getAnnotations();
+       }
+
+       public void resetListeAnnotations() {
+               _RNA.clearAnnotations();
+               repaint();
+       }
+
+       public void addAnnotation(TextAnnotation textAnnotation) {
+               _RNA.addAnnotation(textAnnotation);
+               repaint();
+       }
+
+       public boolean removeAnnotation(TextAnnotation textAnnotation) {
+               boolean done = _RNA.removeAnnotation(textAnnotation);
+               repaint();
+               return done;
+       }
+
+       public TextAnnotation get_selectedAnnotation() {
+               return _selectedAnnotation;
+       }
+
+       public void set_selectedAnnotation(TextAnnotation annotation) {
+               _selectedAnnotation = annotation;
+       }
+
+       public void removeSelectedAnnotation() {
+               _highlightAnnotation = false;
+               _selectedAnnotation = null;
+       }
+
+       public void highlightSelectedAnnotation() {
+               _highlightAnnotation = true;
+       }
+
+       public boolean getFlatExteriorLoop() {
+               return _conf._flatExteriorLoop;
+       }
+
+       public void setFlatExteriorLoop(boolean on) {
+               _conf._flatExteriorLoop = on;
+       }
+
+       public void setLastSelectedPosition(Point2D.Double p) {
+               _lastSelectedCoord.x = p.x;
+               _lastSelectedCoord.y = p.y;
+       }
+
+       public Point2D.Double getLastSelectedPosition() {
+               return _lastSelectedCoord;
+       }
+
+       public void setSequence(String s) {
+               _RNA.setSequence(s);
+               repaint();
+       }
+
+       public void setColorMapVisible(boolean b) {
+               _conf._drawColorMap = b;
+               repaint();
+       }
+
+       public boolean getColorMapVisible() {
+               return _conf._drawColorMap;
+       }
+
+       public void removeColorMap() {
+               _conf._drawColorMap = false;
+               repaint();
+       }
+
+       public void saveSession(String path) {
+               /*
+                * FileOutputStream fos = null; ObjectOutputStream out = null; try { fos
+                * = new FileOutputStream(path); out = new ObjectOutputStream(fos);
+                * out.writeObject(new FullBackup(_conf, _RNA, _conf._title));
+                * out.close(); } catch (Exception ex) { ex.printStackTrace(); }
+                */
+               toXML(path);
+       }
+
+        public FullBackup loadSession(String path) throws ExceptionLoadingFailed { 
+          return loadSession(new File(path));
+        }
+       public FullBackup loadSession(File path) throws ExceptionLoadingFailed {
+
+               FullBackup bck = importSession(path);
+               Mapping map = Mapping.DefaultOutermostMapping(getRNA().getSize(),
+                               bck.rna.getSize());
+               showRNAInterpolated(bck.rna, map);
+               _conf = bck.config;
+               repaint();
+               return bck;
+       }
+
+       public static String VARNA_SESSION_EXTENSION = "varna";
+
+       public static FullBackup importSession(Object path) // BH was String
+                       throws ExceptionLoadingFailed {
+               try {
+                       FileInputStream fis = (path instanceof File ? new FileInputStream((File) path) : new FileInputStream(path.toString()));
+                       // ZipInputStream zis = new
+                       // ZipInputStream(new BufferedInputStream(fis));
+                       // zis.getNextEntry();
+                       FullBackup h = importSession(fis, path.toString());
+                       // zis.close();
+                       return h;
+               } catch (FileNotFoundException e) {
+                       throw (new ExceptionLoadingFailed("File not found.", path.toString()));
+               } catch (IOException e) {
+                       // TODO Auto-generated catch block
+                       throw (new ExceptionLoadingFailed(
+                                       "I/O error while loading session.", path.toString()));
+               }
+       }
+
+       public static FullBackup importSession(InputStream fis, String path)
+                       throws ExceptionLoadingFailed {
+               System.setProperty("javax.xml.parsers.SAXParserFactory",
+                               "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
+               SAXParserFactory saxFact = javax.xml.parsers.SAXParserFactory
+                               .newInstance();
+               saxFact.setValidating(false);
+               saxFact.setXIncludeAware(false);
+               saxFact.setNamespaceAware(false);
+               try {
+                       SAXParser sp = saxFact.newSAXParser();
+                       VARNASessionParser sessionData = new VARNASessionParser();
+                       sp.parse(fis, sessionData);
+                       FullBackup res = new FullBackup(sessionData.getVARNAConfig(),
+                                       sessionData.getRNA(), "test"); 
+                       return res;
+               } catch (ParserConfigurationException e) {
+                       throw new ExceptionLoadingFailed("Bad XML parser configuration",
+                                       path);
+               } catch (SAXException e) {
+                       throw new ExceptionLoadingFailed("XML parser Exception", path);
+               } catch (IOException e) {
+                       throw new ExceptionLoadingFailed("I/O error", path);
+               }
+       }
+
+       public void loadFile(File path) {
+               loadFile(path, false);
+       }
+
+       public boolean getDrawBackbone() {
+               return _conf._drawBackbone;
+       }
+
+       public void setDrawBackbone(boolean b) {
+               _conf._drawBackbone = b;
+       }
+
+       public void addHighlightRegion(HighlightRegionAnnotation n) {
+               _RNA.addHighlightRegion(n);
+       }
+
+       public void removeHighlightRegion(HighlightRegionAnnotation n) {
+               _RNA.removeHighlightRegion(n);
+       }
+
+       public void addHighlightRegion(int i, int j) {
+               _RNA.addHighlightRegion(i, j);
+       }
+
+       public void addHighlightRegion(int i, int j, Color fill, Color outline,
+                       double radius) {
+               _RNA.addHighlightRegion(i, j, fill, outline, radius);
+       }
+       
+       public void loadRNA(String path) {
+               loadRNA(path, false);
+       }
+       
+       public void loadRNA(Object path, boolean interpolate) { // BH was String
+               try {
+                       Collection<RNA> rnas = (path instanceof File ? RNAFactory.loadSecStr(new FileReader((File) path)) : RNAFactory.loadSecStr(path.toString()));
+                       if (rnas.isEmpty()) {
+                               throw new ExceptionFileFormatOrSyntax(
+                                               "No RNA could be parsed from that source.");
+                       }
+                       RNA rna = rnas.iterator().next();
+                       try {
+                               rna.drawRNA(_conf);
+                       } catch (ExceptionNAViewAlgorithm e) {
+                               e.printStackTrace();
+                       }
+                       if (!interpolate) {
+                               showRNA(rna);
+                       } else {
+                               this.showRNAInterpolated(rna);
+                       }
+
+               } catch (FileNotFoundException e) {
+                       e.printStackTrace();
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       e.printStackTrace();
+               } catch (Exception e) {
+                       e.printStackTrace();
+               }
+       }
+
+       public void loadFile(File path, boolean interpolate) { // was String BH StringJS
+               try {
+                       loadSession(path);
+               } catch (Exception e1) {
+                       loadRNA(path, interpolate);
+               }
+       }
+
+       public void setConfig(VARNAConfig cfg) {
+               _conf = cfg;
+       }
+
+       public void toggleDrawOutlineBases() {
+               _conf._drawOutlineBases = !_conf._drawOutlineBases;
+       }
+
+       public void toggleFillBases() {
+               _conf._fillBases = !_conf._fillBases;
+       }
+
+       public void setDrawOutlineBases(boolean drawn) {
+               _conf._drawOutlineBases = drawn;
+       }
+
+       public void setFillBases(boolean drawn) {
+               _conf._fillBases = drawn;
+       }
+
+       public void readValues(Reader r) {
+               this._RNA.readValues(r, _conf._cm);
+       }
+
+       public void addVARNAListener(InterfaceVARNAListener v) {
+               _VARNAListeners.add(v);
+       }
+
+       public void fireLayoutChanged() {
+               for (InterfaceVARNAListener v : _VARNAListeners) {
+                       v.onStructureRedrawn();
+               }
+       }
+
+       public void fireUINewStructure(RNA r) {
+               for (InterfaceVARNAListener v : _VARNAListeners) {
+                       v.onUINewStructure(_conf, r);
+               }
+       }
+
+       public void fireZoomLevelChanged(double d) {
+               for (InterfaceVARNAListener v : _VARNAListeners) {
+                       v.onZoomLevelChanged();
+               }
+       }
+
+       public void fireTranslationChanged() {
+               for (InterfaceVARNAListener v2 : _VARNAListeners) {
+                       v2.onTranslationChanged();
+               }
+       }
+
+       public void addSelectionListener(InterfaceVARNASelectionListener v) {
+               _selectionListeners.add(v);
+       }
+
+       public void fireSelectionChanged(BaseList mold, BaseList mnew) {
+               BaseList addedBases = mnew.removeAll(mold);
+               BaseList removedBases = mold.removeAll(mnew);
+               for (InterfaceVARNASelectionListener v2 : _selectionListeners) {
+                       v2.onSelectionChanged(mnew, addedBases, removedBases);
+               }
+       }
+
+       public void fireHoverChanged(ModeleBase mold, ModeleBase mnew) {
+               for (InterfaceVARNASelectionListener v2 : _selectionListeners) {
+                       v2.onHoverChanged(mold, mnew);
+               }
+       }
+
+       public void addRNAListener(InterfaceVARNARNAListener v) {
+               _RNAListeners.add(v);
+       }
+
+       public void addVARNABasesListener(InterfaceVARNABasesListener l) {
+               _basesListeners.add(l);
+       }
+
+       public void fireSequenceChanged(int index, String oldseq, String newseq) {
+               for (InterfaceVARNARNAListener v2 : _RNAListeners) {
+                       v2.onSequenceModified(index, oldseq, newseq);
+               }
+       }
+
+       public void fireStructureChanged(Set<ModeleBP> current,
+                       Set<ModeleBP> addedBasePairs, Set<ModeleBP> removedBasePairs) {
+               for (InterfaceVARNARNAListener v2 : _RNAListeners) {
+                       v2.onStructureModified(current, addedBasePairs, removedBasePairs);
+               }
+       }
+
+       public void fireLayoutChanged(
+                       Hashtable<Integer, Point2D.Double> movedPositions) {
+               for (InterfaceVARNARNAListener v2 : _RNAListeners) {
+                       v2.onRNALayoutChanged(movedPositions);
+               }
+       }
+
+       public void fireBaseClicked(ModeleBase mb, MouseEvent me) {
+               if (mb != null) {
+                       for (InterfaceVARNABasesListener v2 : _basesListeners) {
+                               v2.onBaseClicked(mb, me);
+                       }
+               }
+       }
+
+       public double getOrientation() {
+               return _RNA.getOrientation();
+       }
+
+       public ModeleBase _hoveredBase = null;
+
+       public void setHoverBase(ModeleBase m) {
+               if (m != _hoveredBase) {
+                       ModeleBase bck = _hoveredBase;
+                       _hoveredBase = m;
+                       repaint();
+                       fireHoverChanged(bck, m);
+               }
+       }
+
+       public void toXML(String path) {
+               FileOutputStream fis;
+               try {
+                       fis = new FileOutputStream(path);
+                       // ZipOutputStream zis = new ZipOutputStream(new
+                       // BufferedOutputStream(fis));
+                       // ZipEntry entry = new ZipEntry("VARNASession");
+                       // zis.putNextEntry(entry);
+                       PrintWriter pw = new PrintWriter(fis);
+                       toXML(pw);
+                       pw.flush();
+                       // zis.closeEntry();
+                       // zis.close();
+                       fis.close();
+               } catch (FileNotFoundException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (IOException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+       }
+
+       public void toXML(PrintWriter out) {
+               try {
+
+                       // out = new PrintWriter(System.out);
+                       StreamResult streamResult = new StreamResult(out);
+                       SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
+                                       .newInstance();
+                       // SAX2.0 ContentHandler.
+                       TransformerHandler hd = tf.newTransformerHandler();
+                       Transformer serializer = hd.getTransformer();
+                       serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
+                       serializer
+                                       .setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "users.dtd");
+                       serializer.setOutputProperty(OutputKeys.INDENT, "yes");
+                       hd.setResult(streamResult);
+                       hd.startDocument();
+                       toXML(hd);
+                       hd.endDocument();
+               } catch (TransformerConfigurationException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (SAXException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+
+       }
+
+       public static String XML_ELEMENT_NAME = "VARNASession";
+
+       public void toXML(TransformerHandler hd) throws SAXException {
+               AttributesImpl atts = new AttributesImpl();
+               hd.startElement("", "", XML_ELEMENT_NAME, atts);
+               _RNA.toXML(hd);
+               _conf.toXML(hd);
+               hd.endElement("", "", XML_ELEMENT_NAME);
+       }
+
+       public TextAnnotation getNearestAnnotation(int x, int y) {
+               TextAnnotation t = null;
+               if (getListeAnnotations().size() != 0) {
+                       double dist = Double.MAX_VALUE;
+                       double d2;
+                       Point2D.Double position;
+                       for (TextAnnotation textAnnot : getListeAnnotations()) {
+                               // calcul de la distance
+                               position = textAnnot.getCenterPosition();
+                               position = transformCoord(position);
+                               d2 = Math.sqrt(Math.pow((position.x - x), 2)
+                                               + Math.pow((position.y - y), 2));
+                               // si la valeur est inferieur au minimum actuel
+                               if ((dist > d2)
+                                               && (d2 < getScaleFactor()
+                                                               * ControleurClicMovement.MIN_SELECTION_DISTANCE)) {
+                                       t = textAnnot;
+                                       dist = d2;
+                               }
+                       }
+               }
+               return t;
+       }
+
+       public ModeleBase getNearestBase(int x, int y, boolean always,
+                       boolean onlyPaired) {
+               int i = getNearestBaseIndex(x, y, always, onlyPaired);
+               if (i == -1)
+                       return null;
+               return getRNA().get_listeBases().get(i);
+       }
+
+       public ModeleBase getNearestBase(int x, int y) {
+               return getNearestBase(x, y, false, false);
+       }
+
+       public int getNearestBaseIndex(int x, int y, boolean always,
+                       boolean onlyPaired) {
+               double d2, dist = Double.MAX_VALUE;
+               int mb = -1;
+               for (int i = 0; i < getRealCoords().length; i++) {
+                       if (!onlyPaired
+                                       || (getRNA().get_listeBases().get(i).getElementStructure() != -1)) {
+                               d2 = Math.sqrt(Math.pow((getRealCoords()[i].x - x), 2)
+                                               + Math.pow((getRealCoords()[i].y - y), 2));
+                               if ((dist > d2)
+                                               && ((d2 < getScaleFactor()
+                                                               * ControleurClicMovement.MIN_SELECTION_DISTANCE) || always)) {
+                                       dist = d2;
+                                       mb = i;
+                               }
+                       }
+               }
+               return mb;
+       }
+
+       public void globalRescale(double factor) {
+               _RNA.rescale(factor);
+               fireLayoutChanged();
+               repaint();
+       }
+
+       public void setSpaceBetweenBases(double sp) {
+               _conf._spaceBetweenBases = sp;
+       }
+
+       public double getSpaceBetweenBases() {
+               return _conf._spaceBetweenBases;
+       }
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/AlignmentDemo.java b/src2/fr/orsay/lri/varna/applications/AlignmentDemo.java
new file mode 100644 (file)
index 0000000..18c328c
--- /dev/null
@@ -0,0 +1,286 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+public class AlignmentDemo extends JFrame{
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+       private static final String DEFAULT_SEQUENCE1 =  "CGCGCACGCGA----UAUU----UCGCGUCGCGCAUUUGCGCGUAGCGCG";
+       private static final String DEFAULT_STRUCTURE1 = "(((((.(((((----....----))))).(((((....)))))..)))))";
+
+       private static final String DEFAULT_SEQUENCE2 =  "CGCGCACGCGSGCGCGUUUGCGCUCGCGU---------------AGCGCG";
+       private static final String DEFAULT_STRUCTURE2 = "(((((.(((((((((....))))))))).--------------..)))))";
+       // private static final String DEFAULT_STRUCTURE1 = "((((....))))";
+       // private static final String DEFAULT_STRUCTURE2 =
+       // "((((..(((....)))..))))";
+
+       private VARNAPanel _vpMaster;
+
+       private JPanel _tools = new JPanel();
+       private JPanel _input = new JPanel();
+
+       private JPanel _seq1Panel = new JPanel();
+       private JPanel _seq2Panel = new JPanel();
+       private JPanel _struct1Panel = new JPanel();
+       private JPanel _struct2Panel = new JPanel();
+       private JLabel _info = new JLabel();
+       private JTextField _struct1 = new JTextField(DEFAULT_STRUCTURE1);
+       private JTextField _struct2 = new JTextField(DEFAULT_STRUCTURE2);
+       private JTextField _seq1 = new JTextField(DEFAULT_SEQUENCE1);
+       private JTextField _seq2 = new JTextField(DEFAULT_SEQUENCE2);
+       private JLabel _struct1Label = new JLabel(" Str1:");
+       private JLabel _struct2Label = new JLabel(" Str2:");
+       private JLabel _seq1Label = new JLabel(" Seq1:");
+       private JLabel _seq2Label = new JLabel(" Seq2:");
+       private JButton _goButton = new JButton("Go");
+
+       private String _str1Backup = "";
+       private String _str2Backup = "";
+       private String _seq1Backup = "";
+       private String _seq2Backup = "";
+       private RNA _RNA = new RNA();
+
+       private static String errorOpt = "error";
+       @SuppressWarnings("unused")
+       private boolean _error;
+
+       private Color _backgroundColor = Color.white;
+
+       @SuppressWarnings("unused")
+       private int _algoCode;
+
+
+       public AlignmentDemo() {
+               super();
+                       _vpMaster = new VARNAPanel(getSeq1(), getStruct1(), getSeq2(), getStruct2(), RNA.DRAW_MODE_RADIATE,"");
+               _vpMaster.setPreferredSize(new Dimension(600, 400));
+               RNAPanelDemoInit();
+       }
+
+       private void RNAPanelDemoInit() {
+               int marginTools = 40;
+
+               setBackground(_backgroundColor);
+               _vpMaster.setBackground(_backgroundColor);
+
+               Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
+
+
+               _goButton.addActionListener(new ActionListener() {
+
+                       public void actionPerformed(ActionEvent e) {
+                                       _vpMaster.drawRNA(getSeq1(), getStruct1(), getSeq2(), getStruct2(), _vpMaster.getDrawMode());
+                               _vpMaster.repaint();
+                       }
+               });
+
+               
+               _seq1Label.setHorizontalTextPosition(JLabel.LEFT);
+               _seq1Label.setPreferredSize(new Dimension(marginTools, 15));
+               _seq1.setFont(textFieldsFont);
+
+               _seq1Panel.setLayout(new BorderLayout());
+               _seq1Panel.add(_seq1Label, BorderLayout.WEST);
+               _seq1Panel.add(_seq1, BorderLayout.CENTER);
+
+               _seq2Label.setHorizontalTextPosition(JLabel.LEFT);
+               _seq2Label.setPreferredSize(new Dimension(marginTools, 15));
+               _seq2.setFont(textFieldsFont);
+               
+               _seq2Panel.setLayout(new BorderLayout());
+               _seq2Panel.add(_seq2Label, BorderLayout.WEST);
+               _seq2Panel.add(_seq2, BorderLayout.CENTER);
+
+               _struct1Label.setPreferredSize(new Dimension(marginTools, 15));
+               _struct1Label.setHorizontalTextPosition(JLabel.LEFT);
+               _struct1.setFont(textFieldsFont);
+               _struct1Panel.setLayout(new BorderLayout());
+               _struct1Panel.add(_struct1Label, BorderLayout.WEST);
+               _struct1Panel.add(_struct1, BorderLayout.CENTER);
+
+               _struct2Label.setPreferredSize(new Dimension(marginTools, 15));
+               _struct2Label.setHorizontalTextPosition(JLabel.LEFT);
+               _struct2.setFont(textFieldsFont);
+               _struct2Panel.setLayout(new BorderLayout());
+               _struct2Panel.add(_struct2Label, BorderLayout.WEST);
+               _struct2Panel.add(_struct2, BorderLayout.CENTER);
+
+               _input.setLayout(new GridLayout(4, 0));
+               _input.add(_seq1Panel);
+               _input.add(_struct1Panel);
+               _input.add(_seq2Panel);
+               _input.add(_struct2Panel);
+
+               JPanel goPanel = new JPanel();
+               goPanel.setLayout(new BorderLayout());
+
+               _tools.setLayout(new BorderLayout());
+               _tools.add(_input, BorderLayout.CENTER);
+               _tools.add(_info, BorderLayout.SOUTH);
+               _tools.add(goPanel, BorderLayout.EAST);
+
+               goPanel.add(_goButton, BorderLayout.CENTER);
+               
+               getContentPane().setLayout(new BorderLayout());
+               JPanel VARNAs = new JPanel();
+               VARNAs.setLayout(new GridLayout(1,1));
+               VARNAs.add(_vpMaster);
+               getContentPane().add(VARNAs, BorderLayout.CENTER);
+               getContentPane().add(_tools, BorderLayout.SOUTH);
+
+               setVisible(true);
+               _vpMaster.getVARNAUI().UIRadiate();
+       }
+
+       public RNA getRNA() {
+
+               if (!( _str1Backup.equals(getStruct1())
+                       && _str2Backup.equals(getStruct2())
+                       && _seq1Backup.equals(getSeq1())
+                       && _seq2Backup.equals(getSeq2())
+               )) {
+                       _vpMaster.drawRNA(getSeq1(), getStruct1(), getSeq2(), getStruct2(), _vpMaster.getDrawMode());
+                       _RNA = _vpMaster.getRNA();
+                       _str1Backup = getStruct1();
+                       _str2Backup = getStruct2();
+                       _seq1Backup = getSeq1();
+                       _seq2Backup = getSeq2();
+               }
+               return _RNA;
+       }
+
+
+       public String getStruct1() {
+               return cleanStruct(_struct1.getText());
+       }
+
+       public String getStruct2() {
+               return cleanStruct(_struct2.getText());
+       }
+
+       public String getSeq1() {
+               return cleanStruct(_seq1.getText());
+       }
+
+       public String getSeq2() {
+               return cleanStruct(_seq2.getText());
+       }
+       
+       
+       private String cleanStruct(String struct) {
+               struct = struct.replaceAll("[:-]", "-");
+               return struct;
+       }
+
+       public String[][] getParameterInfo() {
+               String[][] info = {
+                               // Parameter Name Kind of Value Description,
+                               { "sequenceDBN", "String", "A raw RNA sequence" },
+                               { "structureDBN", "String",
+                                               "An RNA structure in dot bracket notation (DBN)" },
+                               { errorOpt, "boolean", "To show errors" }, };
+               return info;
+       }
+
+       public void init() {
+               _vpMaster.setBackground(_backgroundColor);
+               _error = true;
+       }
+
+       @SuppressWarnings("unused")
+       private Color getSafeColor(String col, Color def) {
+               Color result;
+               try {
+                       result = Color.decode(col);
+               } catch (Exception e) {
+                       try {
+                               result = Color.getColor(col, def);
+                       } catch (Exception e2) {
+                               return def;
+                       }
+               }
+               return result;
+       }
+
+       public VARNAPanel get_varnaPanel() {
+               return _vpMaster;
+       }
+
+       public void set_varnaPanel(VARNAPanel surface) {
+               _vpMaster = surface;
+       }
+
+       public JTextField get_struct() {
+               return _struct1;
+       }
+
+       public void set_struct(JTextField _struct) {
+               this._struct1 = _struct;
+       }
+
+       public JTextField get_seq() {
+               return _seq1;
+       }
+
+       public void set_seq(JTextField _seq) {
+               this._seq1 = _seq;
+       }
+
+       public JLabel get_info() {
+               return _info;
+       }
+
+       public void set_info(JLabel _info) {
+               this._info = _info;
+       }
+
+       public static void main(String[] args) {
+               AlignmentDemo d = new AlignmentDemo();
+               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               d.pack();
+               d.setVisible(true);
+       }
+
+       public void onWarningEmitted(String s) {
+               // TODO Auto-generated method stub
+               
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/BasicINI.java b/src2/fr/orsay/lri/varna/applications/BasicINI.java
new file mode 100644 (file)
index 0000000..89a590e
--- /dev/null
@@ -0,0 +1,178 @@
+package fr.orsay.lri.varna.applications;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.Reader;
+import java.io.StreamTokenizer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Set;
+
+public class BasicINI {
+
+       private Hashtable<String,Hashtable<String,String>> _data = new Hashtable<String,Hashtable<String,String>>();
+
+
+       public void addItem(String category, String key, String val)
+       {
+               if (!_data.containsKey(category))
+               {
+                       _data.put(category, new Hashtable<String,String>());
+               }
+               System.out.println("[E]"+key+"->"+val);
+               _data.get(category).put(key,val);
+       }
+
+
+       public String getItem(String category, String key)
+       {
+               String result = "";
+               if (_data.containsKey(category))
+               {
+                       if (_data.get(category).containsKey(key))
+                       {
+                               result = _data.get(category).get(key);
+                       }
+               }
+               return result;
+       }
+
+       public ArrayList<String> getItemList(String category)
+       {
+               ArrayList<String> result = new ArrayList<String>();
+               if (_data.containsKey(category))
+               {
+                       for (String key: _data.get(category).keySet())
+                       {
+                               result.add(_data.get(category).get(key));
+                       }
+               }
+               return result;
+       }
+
+       public BasicINI(){
+
+       }
+
+       public static void saveINI(BasicINI data, String filename)  
+       {
+               try
+               {
+                       FileWriter out = new FileWriter(filename);
+                       Set<String> cats = data._data.keySet();
+                       String[] sortedCats = new String[cats.size()];
+                       sortedCats = cats.toArray(sortedCats); 
+                       Arrays.sort(sortedCats);
+                       for (int i=0;i<sortedCats.length;i++)
+                       {
+                               String cat = sortedCats[i];             
+                               out.write("["+cat+"]\n"); 
+                               Hashtable<String,String> vals = data._data.get(cat);
+                               Set<String> keys = vals.keySet();
+                               String[] sortedKeys = new String[keys.size()];
+                               sortedKeys = keys.toArray(sortedKeys); 
+                               for(int j=0;j<sortedKeys.length;j++)
+                               {
+                                       String key = sortedKeys[j];
+                                       String val = vals.get(key);
+                                       out.write(key+"="+val+"\n");                            
+                               }
+                       }
+                       out.close();
+               }
+               catch(Exception e3)
+               {e3.printStackTrace();}
+       }
+
+       public static BasicINI loadINI(String filename)  
+       {
+               BasicINI result = new BasicINI();    
+
+               // Etats du parsing simplifie ...
+               final int CATEGORY = 0;
+               final int KEY = 1;
+               final int VAL = 2;
+               int state = KEY;
+               String category = "";
+               String key = "";
+               String val = "";
+
+               try
+               {
+                       System.out.println("Loading "+new File(filename).getAbsolutePath());
+
+                       Reader r = new FileReader(filename);
+                       StreamTokenizer s = new StreamTokenizer(r);
+                       s.resetSyntax();
+                       s.eolIsSignificant(true);
+                       s.wordChars('\u0000','\u00FF');
+                       s.whitespaceChars('\u0000','\u000F');
+                       s.ordinaryChar('[');
+                       s.ordinaryChar(']');
+                       s.ordinaryChar('=');
+                       int token = s.nextToken();
+                       while(token != StreamTokenizer.TT_EOF)
+                       {
+                               switch(token)
+                               {
+                               case('[') :
+                               {
+                                       state = CATEGORY;
+                               }
+                               break;
+                               case(']') :
+                               {
+                                       state = KEY;
+                               }
+                               break;
+                               case('=') :
+                               {
+                                       state = VAL;
+                               }
+                               break;
+                               case(StreamTokenizer.TT_EOL) :
+                               {
+                                       if (state==VAL)
+                                       {
+                                         state = KEY;
+                                         result.addItem(category, key, val);
+                                         key="";
+                                         val="";
+                                       }
+                               }
+                               case(StreamTokenizer.TT_WORD) :
+                               {
+                                       String word = s.sval;
+                                       switch(state)
+                                       {
+                                       case(CATEGORY) :
+                                       {
+                                               category = word;
+                                       }
+                                       break;
+                                       case(KEY) :
+                                       {
+                                               key = word;
+                                       }
+                                       break;
+                                       case(VAL) :
+                                       {
+                                               val = word;
+                                       }
+                                       break;
+                                       }
+                               }
+                               break;
+                               }
+                               token = s.nextToken();
+                       }
+               }
+               catch(Exception exc1)
+               {exc1.printStackTrace();}
+               return result;
+       }
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/FileNameExtensionFilter.java b/src2/fr/orsay/lri/varna/applications/FileNameExtensionFilter.java
new file mode 100644 (file)
index 0000000..377a4f1
--- /dev/null
@@ -0,0 +1,71 @@
+package fr.orsay.lri.varna.applications;
+
+import java.io.File;
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+import javax.swing.filechooser.FileFilter;
+
+public class FileNameExtensionFilter extends FileFilter {
+
+    Hashtable<String,Integer> _exts = new Hashtable<String,Integer>();
+    String _desc = "";
+       
+       public FileNameExtensionFilter(String desc,String ext1)
+       {
+               _desc = desc;
+               _exts.put(ext1,0);
+       }
+
+       public FileNameExtensionFilter(String desc,String ext1,String ext2)
+       {
+               this(desc,ext1);
+               _exts.put(ext2,1);
+       }
+       
+       public FileNameExtensionFilter(String desc,String ext1,String ext2,String ext3)
+       {
+               this(desc,ext1,ext2);
+               _exts.put(ext3,2);
+       }
+
+       public FileNameExtensionFilter(String desc,String ext1,String ext2,String ext3,String ext4)
+       {
+               this(desc,ext1,ext2,ext3);
+               _exts.put(ext4,3);
+       }
+       
+       
+       public boolean accept(File path) {
+               String name = path.getName();
+               if (path.isDirectory())
+                       return true;
+               int index = name.lastIndexOf(".");
+               if (index != -1)
+               {
+                 String suffix = name.substring(index+1);
+                 if (_exts.containsKey(suffix))
+                 {return true;}
+               }
+               return false;
+       }
+
+       @Override
+       public String getDescription() {
+               return _desc;
+       }
+       
+       public String[] getExtensions()
+       {
+               String[] exts = new String[_exts.size()];
+               Enumeration<String> k = _exts.keys();
+               int n = 0;
+               while(k.hasMoreElements())
+               {
+                       exts[n] = k.nextElement();
+                       n++;
+               }
+               return exts;
+       }       
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/NussinovDemo.java b/src2/fr/orsay/lri/varna/applications/NussinovDemo.java
new file mode 100644 (file)
index 0000000..94ac79d
--- /dev/null
@@ -0,0 +1,819 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseEvent;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collections;
+
+import javax.swing.BorderFactory;
+import javax.swing.DefaultComboBoxModel;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+import javax.swing.JTextPane;
+import javax.swing.border.BevelBorder;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurInterpolator;
+import fr.orsay.lri.varna.exceptions.ExceptionDrawingAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.exceptions.MappingException;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.VARNAConfig.BP_STYLE;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModelBaseStyle;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNABasesListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;;
+
+public class NussinovDemo extends JFrame implements InterfaceVARNAListener,InterfaceVARNABasesListener {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+       private static final String SEQUENCE_DUMMY =        "AAAAAAAAAA";
+       private static final String SEQUENCE_A =        "AGGCACGUCU";
+       private static final String SEQUENCE_B =  "GAGUAGCCUC";
+       private static final String SEQUENCE_C = "GCAUAGCUGC";
+       private static final String SEQUENCE_INRIA = "GAGAAGUACUUGAAAUUGGCCUCCUC";
+       
+
+       private static final String SEQUENCE_BIG = "AAAACAAAAACACCAUGGUGUUUUCACCCAAUUGGGUGAAAACAGAGAUCUCGAGAUCUCUGUUUUUGUUUU"; 
+
+       private static final String DEFAULT_STRUCTURE = "..........";
+       // private static final String DEFAULT_STRUCTURE1 = "((((....))))";
+       // private static final String DEFAULT_STRUCTURE2 =
+       // "((((..(((....)))..))))";
+
+       private VARNAPanel _vpMaster;
+
+       private InfoPanel _infos = new InfoPanel();
+       private JPanel _tools = new JPanel();
+       private JPanel _input = new JPanel();
+
+       private JPanel _seqPanel = new JPanel();
+       private JPanel _structPanel = new JPanel();
+       private JLabel _actions = new JLabel();
+       private JLabel _struct = new JLabel(DEFAULT_STRUCTURE);
+       private JComboBox _seq1 = new JComboBox();
+       private JLabel _structLabel = new JLabel("Structure Secondaire");
+       private JLabel _seqLabel = new JLabel("Sequence d'ARN");
+       private JButton _goButton = new JButton("Repliement");
+       private JButton _switchButton = new JButton("Effacer");
+
+
+       private Color _backgroundColor = Color.white;
+       
+       public static Font textFieldsFont = Font.decode("MonoSpaced-BOLD-16");
+       public static Font labelsFont = Font.decode("SansSerif-BOLD-20");
+       public static final int marginTools = 250;
+       public static String APP_TITLE = "Fête de la science 2015 - Inria AMIB - Repliement d'ARN";
+       
+
+       public static ModelBaseStyle createStyle(String txt) 
+       {
+               ModelBaseStyle result = new ModelBaseStyle();
+               try {
+                       result.assignParameters(txt);
+               } catch (ExceptionModeleStyleBaseSyntaxError e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionParameterError e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+               return result;
+       }
+       
+       public void applyTo(VARNAPanel vp, ModelBaseStyle mb, int[] indices)
+       {
+               for(int i=0;i<indices.length;i++)
+               { 
+                       ModeleBase m = vp.getRNA().getBaseAt(indices[i]);
+                       m.setStyleBase(mb);
+                       if (m.getElementStructure()!=-1)
+                       {
+                               vp.getRNA().getBaseAt(m.getElementStructure()).setStyleBase(mb);
+                       }
+               }
+               vp.repaint();
+       }
+       
+       
+       public NussinovDemo() {
+               super();
+               try {
+                       _vpMaster = new VARNAPanel(getSeq(), "");
+               } catch (ExceptionNonEqualLength e) {
+                       _vpMaster.errorDialog(e);
+               }
+               _vpMaster.setPreferredSize(new Dimension(600, 600));
+               RNAPanelDemoInit();
+       }
+
+       public static void formatLabel(JLabel j)
+       {
+               j.setHorizontalTextPosition(JLabel.LEFT);
+               j.setPreferredSize(new Dimension(marginTools, 15));
+               j.setFont(labelsFont);
+       }
+       
+       private void RNAPanelDemoInit() {
+               
+               
+
+               _seq1.setFont(textFieldsFont);
+               String[] seqs = {SEQUENCE_DUMMY,SEQUENCE_INRIA,SEQUENCE_A,SEQUENCE_B,SEQUENCE_C,SEQUENCE_BIG};
+               _seq1.setModel(new DefaultComboBoxModel(seqs));
+               _seq1.setEditable(true);
+               
+
+               setBackground(_backgroundColor);
+               _vpMaster.setBackground(_backgroundColor);
+               _vpMaster.addVARNAListener(this);
+               _vpMaster.setFlatExteriorLoop(true);
+               
+
+
+               formatLabel(_seqLabel);
+               formatLabel(_structLabel);
+
+               _goButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               showSolution();
+                               onStructureRedrawn();
+                       }
+               });
+
+               _switchButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               try {
+                                                       RNA r = new RNA();
+                                                       r.setRNA("", "");
+                                                       _struct.setText("");
+                                                       _vpMaster.setTitle("");
+                                                       _vpMaster.showRNA(r);
+                                                       onStructureRedrawn();
+                                       } 
+                               catch (ExceptionFileFormatOrSyntax e2) {
+                                       e2.printStackTrace();
+                               } catch (ExceptionUnmatchedClosingParentheses e2) {
+                                       // TODO Auto-generated catch block
+                                       e2.printStackTrace();
+                               }
+                               _vpMaster.repaint();
+                       }
+               });
+
+               _seqPanel.setLayout(new BorderLayout());
+               _seqPanel.add(_seqLabel, BorderLayout.WEST);
+               _seqPanel.add(_seq1, BorderLayout.CENTER);
+
+               _structLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _structLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _struct.setFont(textFieldsFont);
+               _structPanel.setLayout(new BorderLayout());
+               _structPanel.add(_structLabel, BorderLayout.WEST);
+               _structPanel.add(_struct, BorderLayout.CENTER);
+
+               _input.setLayout(new GridLayout(0, 1));
+               _input.add(_seqPanel);
+               _input.add(_structPanel);
+
+               JPanel goPanel = new JPanel();
+               goPanel.setLayout(new BorderLayout());
+
+               _infos.setFont(labelsFont);
+
+               
+               _tools.setLayout(new BorderLayout());
+               _tools.add(_infos, BorderLayout.SOUTH);
+               _tools.add(_input, BorderLayout.CENTER);
+               _tools.add(_actions, BorderLayout.NORTH);
+               _tools.add(goPanel, BorderLayout.EAST);
+               _tools.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
+
+               goPanel.add(_goButton, BorderLayout.CENTER);
+               goPanel.add(_switchButton, BorderLayout.SOUTH);
+
+               getContentPane().setLayout(new BorderLayout());
+               JPanel VARNAs = new JPanel();
+               VARNAs.setLayout(new GridLayout(1,2));
+               VARNAs.add(_vpMaster);
+               VARNAs.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
+               getContentPane().add(VARNAs, BorderLayout.CENTER);
+               getContentPane().add(_tools, BorderLayout.SOUTH);
+
+               setVisible(true);
+
+               _vpMaster.getVARNAUI().UIRadiate();
+               _vpMaster.setTitleFontSize(26f);
+               _vpMaster.setTitleFontStyle(Font.PLAIN);
+               _vpMaster.addVARNABasesListener(this);
+               _vpMaster.setBackground(Color.decode("#308099"));
+               _vpMaster.setModifiable(false);
+               _vpMaster.setTitle("Repliement cible");
+               _vpMaster.setBPStyle(BP_STYLE.SIMPLE);
+               _vpMaster.setBackboneColor(Color.white);
+               _vpMaster.setDefaultBPColor(Color.white);
+               _vpMaster.setBaseNumbersColor(Color.white);
+               _vpMaster.setBaseOutlineColor(Color.white);
+               _vpMaster.setTitleColor(Color.white);           
+               _vpMaster.setTitleFontSize(26f);
+
+               
+               
+               this.setTitle(APP_TITLE);
+               
+               showSolution();
+               onStructureRedrawn();
+       }
+
+       private synchronized void showSolution()
+       {
+               ArrayList<String> sols = getStructs();
+               _infos.setInfo(sols, count(getSeq()));
+       }
+       
+
+
+
+       public String getSeq()
+       {
+               return (""+_seq1.getSelectedItem()).toUpperCase();
+       }
+
+       
+       private boolean canBasePairAll(char a, char b)
+       {
+               return true;
+       }
+
+       private boolean canBasePairBasic(char a, char b)
+       {
+               if ((a=='G')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='G'))
+                       return true;
+               if ((a=='U')&&(b=='A'))
+                       return true;
+               if ((a=='A')&&(b=='U'))
+                       return true;
+               if ((a=='G')&&(b=='U'))
+                       return true;
+               if ((a=='U')&&(b=='G'))
+                       return true;
+               return false;
+       }
+
+       private double basePairScoreBasic(char a, char b)
+       {
+               if ((a=='G')&&(b=='C'))
+                       return 1.0;
+               if ((a=='C')&&(b=='G'))
+                       return 1.0;
+               if ((a=='U')&&(b=='A'))
+                       return 1.0;
+               if ((a=='A')&&(b=='U'))
+                       return 1.0;
+               if ((a=='G')&&(b=='U'))
+                       return 1.0;
+               if ((a=='U')&&(b=='G'))
+                       return 1.0;
+               return Double.NEGATIVE_INFINITY;
+       }
+
+       
+       private boolean canBasePairNussinov(char a, char b)
+       {
+               if ((a=='G')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='G'))
+                       return true;
+               if ((a=='U')&&(b=='A'))
+                       return true;
+               if ((a=='A')&&(b=='U'))
+                       return true;
+               if ((a=='U')&&(b=='G'))
+                       return true;
+               if ((a=='G')&&(b=='U'))
+                       return true;
+               return false;
+       }
+
+       private double basePairScoreNussinov(char a, char b)
+       {
+               if ((a=='G')&&(b=='C'))
+                       return 3.0;
+               if ((a=='C')&&(b=='G'))
+                       return 3.0;
+               if ((a=='U')&&(b=='A'))
+                       return 2.0;
+               if ((a=='A')&&(b=='U'))
+                       return 2.0;
+               if ((a=='U')&&(b=='G'))
+                       return 1.0;
+               if ((a=='G')&&(b=='U'))
+                       return 1.0;
+               return Double.NEGATIVE_INFINITY;
+       }
+
+       private boolean canBasePairINRIA(char a, char b)
+       {
+               if ((a=='U')&&(b=='A'))
+                       return true;
+               if ((a=='A')&&(b=='U'))
+                       return true;
+               if ((a=='G')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='G'))
+                       return true;
+
+               if ((a=='A')&&(b=='G'))
+                       return true;
+               if ((a=='G')&&(b=='A'))
+                       return true;
+               if ((a=='U')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='U'))
+                       return true;
+               if ((a=='A')&&(b=='A'))
+                       return true;
+               if ((a=='U')&&(b=='U'))
+                       return true;
+
+               if ((a=='U')&&(b=='G'))
+                       return true;
+               if ((a=='G')&&(b=='U'))
+                       return true;
+               if ((a=='A')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='A'))
+                       return true;
+               return false;
+       }
+
+       private double basePairScoreINRIA(char a, char b)
+       {
+               if ((a=='U')&&(b=='A'))
+                       return 3;
+               if ((a=='A')&&(b=='U'))
+                       return 3;
+               if ((a=='G')&&(b=='C'))
+                       return 3;
+               if ((a=='C')&&(b=='G'))
+                       return 3;
+
+               if ((a=='A')&&(b=='G'))
+                       return 2;
+               if ((a=='G')&&(b=='A'))
+                       return 2;
+               if ((a=='U')&&(b=='C'))
+                       return 2;
+               if ((a=='C')&&(b=='U'))
+                       return 2;
+               if ((a=='A')&&(b=='A'))
+                       return 2;
+               if ((a=='U')&&(b=='U'))
+                       return 2;
+
+               if ((a=='U')&&(b=='G'))
+                       return 1;
+               if ((a=='G')&&(b=='U'))
+                       return 1;
+               if ((a=='A')&&(b=='C'))
+                       return 1;
+               if ((a=='C')&&(b=='A'))
+                       return 1;
+               return Double.NEGATIVE_INFINITY;
+       }
+       
+       private boolean canBasePair(char a, char b)
+       {
+               return canBasePairBasic(a,b);
+               //return canBasePairNussinov(a,b);
+               //return canBasePairINRIA(a,b);
+       }
+       
+       private double basePairScore(char a, char b)
+       {
+               return basePairScoreBasic(a,b);
+               //return basePairScoreNussinov(a,b);
+               //return basePairScoreINRIA(a,b);
+       }
+       
+       public double[][] fillMatrix(String seq)
+       {
+               int n = seq.length();
+               double[][] tab = new double[n][n];
+               for(int m=1;m<=n;m++)
+               {
+                       for(int i=0;i<n-m+1;i++)
+                       {
+                               int j = i+m-1;
+                               tab[i][j] = 0;
+                               if (i<j)
+                               { 
+                                       tab[i][j] = Math.max(tab[i][j], tab[i+1][j]); 
+                                       for (int k=i+1;k<=j;k++)
+                                       {
+                                               if (canBasePair(seq.charAt(i),seq.charAt(k)))
+                                               {
+                                                       double fact1 = 0;
+                                                       if (k>i+1)
+                                                       {
+                                                               fact1 = tab[i+1][k-1];
+                                                       }
+                                                       double fact2 = 0;
+                                                       if (k<j)
+                                                       {
+                                                               fact2 = tab[k+1][j];
+                                                       }
+                                                       tab[i][j] = Math.max(tab[i][j],basePairScore(seq.charAt(i),seq.charAt(k))+fact1+fact2);
+                                               } 
+                                       }
+                               }
+                       }                       
+               }
+               return tab;
+       }
+
+       public static ArrayList<Double> combine(double bonus, ArrayList<Double> part1, ArrayList<Double> part2)
+       {
+               ArrayList<Double> base = new ArrayList<Double>();
+               for(double d1: part1)
+               {
+                       for(double d2: part2)
+                       {
+                               base.add(bonus+d1+d2);
+                       }
+               }
+               return base;
+       }
+
+       public static ArrayList<Double> selectBests(ArrayList<Double> base)
+       {
+               ArrayList<Double> result = new ArrayList<Double>();
+               double best = Double.NEGATIVE_INFINITY;
+               for(double val: base)
+               {
+                       best = Math.max(val, best);
+               }
+               for(double val: base)
+               {
+                       if (val == best)
+                               result.add(val);
+               }
+               return result;
+       }
+
+       
+       private ArrayList<String> backtrack(double[][] tab, String seq)
+       {
+               return backtrack(tab,seq, 0, seq.length()-1);
+       }
+
+       private ArrayList<String> backtrack(double[][] tab, String seq, int i, int j)
+       {
+               ArrayList<String> result = new ArrayList<String>();
+               if (i<j)
+               { 
+                       ArrayList<Integer> indices = new ArrayList<Integer>();
+                       indices.add(-1);
+                       for (int k=i+1;k<=j;k++)
+                       {
+                               indices.add(k);
+                       }
+                       for (int k : indices)
+                       {
+                               if (k==-1)
+                               {
+                                       if (tab[i][j] == tab[i+1][j])
+                                       {
+                                               for (String s:backtrack(tab, seq, i+1,j))
+                                               {
+                                                       result.add("."+s);
+                                               }
+                                       }
+                               }
+                               else
+                               {
+                                       if (canBasePair(seq.charAt(i),seq.charAt(k)))
+                                       {
+                                               double fact1 = 0;
+                                               if (k>i+1)
+                                               {
+                                                       fact1 = tab[i+1][k-1];
+                                               }
+                                               double fact2 = 0;
+                                               if (k<j)
+                                               {
+                                                       fact2 = tab[k+1][j];
+                                               }
+                                               if (tab[i][j]==basePairScore(seq.charAt(i),seq.charAt(k))+fact1+fact2)
+                                               { 
+                                                       for (String s1:backtrack(tab, seq, i+1,k-1))
+                                                       {
+                                                               for (String s2:backtrack(tab, seq, k+1,j))
+                                                               {
+                                                                       result.add("("+s1+")"+s2);
+                                                               }
+                                                       }
+                                               }
+                                       }                                       
+                               }                               
+                       }
+               }
+               else if  (i==j)
+               {
+                       result.add(".");
+               }
+               else 
+               {
+                       result.add("");
+               }
+               return result;
+       }
+       
+       public BigInteger count(String seq)
+       {
+               int n = seq.length();
+               
+               BigInteger[][] tab = new BigInteger[n][n];
+               for(int m=1;m<=n;m++)
+               {
+                       for(int i=0;i<n-m+1;i++)
+                       {
+                               int j = i+m-1;
+                               tab[i][j] = BigInteger.ZERO;
+                               if (i<j)
+                               { 
+                                       tab[i][j] = tab[i][j].add(tab[i+1][j]); 
+                                       for (int k=i+1;k<=j;k++)
+                                       {
+                                               if (canBasePair(seq.charAt(i),seq.charAt(k)))
+                                               {
+                                                       BigInteger fact1 = BigInteger.ONE;
+                                                       if (k>i+1)
+                                                       {
+                                                               fact1 = tab[i+1][k-1];
+                                                       }
+                                                       BigInteger fact2 = BigInteger.ONE;
+                                                       if (k<j)
+                                                       {
+                                                               fact2 = tab[k+1][j];
+                                                       }
+                                                       tab[i][j] = tab[i][j].add(fact1.multiply(fact2));
+                                               } 
+                                       }
+                               }
+                               else
+                               {
+                                       tab[i][j] = BigInteger.ONE;
+                               }
+                       }                       
+               }
+               return tab[0][n-1];
+       }
+       
+       private String _cache = "";
+       ArrayList<String> _cacheStructs = new ArrayList<String>(); 
+       
+       public ArrayList<String> getStructs() {
+               String seq = getSeq();
+               seq = seq.toUpperCase();
+               if (!_cache.equals(seq))
+               {
+                       double[][] mfe = fillMatrix(seq);
+                       _cacheStructs = backtrack(mfe,seq);
+                       _cache = seq;
+               }
+               return _cacheStructs;
+       }
+
+       public VARNAPanel get_varnaPanel() {
+               return _vpMaster;
+       }
+
+       public void set_varnaPanel(VARNAPanel surface) {
+               _vpMaster = surface;
+       }
+
+
+       public JLabel get_info() {
+               return _actions;
+       }
+
+       public void set_info(JLabel _info) {
+               this._actions = _info;
+       }
+
+       public static void main(String[] args) {
+               NussinovDemo d = new NussinovDemo();
+               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               d.pack();
+               d.setVisible(true);
+       }
+
+       public void onStructureRedrawn() {
+               _vpMaster.repaint();
+       }
+
+       public void onWarningEmitted(String s) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onLoad(String path) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onLoaded() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onUINewStructure(VARNAConfig v, RNA r) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       static final String[] _bases =     {"A","C","G","U"};
+       static final String[] _basesComp = {"U","G","C","A"};
+       
+       public void onBaseClicked(ModeleBase mb, MouseEvent e) {
+       }
+       
+       public void onZoomLevelChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onTranslationChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+       private class InfoPanel extends JPanel
+       {
+               ArrayList<String> _sols = new ArrayList<String>();
+               BigInteger _nbFolds = BigInteger.ZERO;
+               JTextArea _text = new JTextArea("");
+               JTextArea _subopts = new JTextArea("");
+               JPanel _suboptBrowser = new JPanel();
+               JPanel _suboptCount = new JPanel();
+               int _selectedIndex = 0;
+               JButton next = new JButton(">");
+               JButton previous = new JButton("<");
+               
+               InfoPanel()
+               {
+                       setLayout(new BorderLayout());
+                       add(_suboptBrowser,BorderLayout.SOUTH);
+                       add(_suboptCount,BorderLayout.NORTH);
+                       
+                       next.addActionListener(new ActionListener(){
+                               public void actionPerformed(ActionEvent arg0) {
+                                       if (_sols.size()>0)
+                                       {
+                                               setSelectedIndex((_selectedIndex+1)%_sols.size());
+                                       }
+                               }                               
+                       });
+
+                       previous.addActionListener(new ActionListener(){
+                               public void actionPerformed(ActionEvent arg0) {
+                                       if (_sols.size()>0)
+                                       {
+                                               setSelectedIndex((_selectedIndex+_sols.size()-1)%_sols.size());
+                                       }
+                               }                               
+                       });
+                       next.setEnabled(false);
+                       previous.setEnabled(false);
+                       
+
+                       JLabel nbLab = new JLabel("#Repliements");
+                       NussinovDemo.formatLabel(nbLab);
+
+                       _suboptCount.setLayout(new BorderLayout());
+                       _suboptCount.add(nbLab,BorderLayout.WEST);
+                       _suboptCount.add(_text,BorderLayout.CENTER);
+
+                       JLabel cooptlab = new JLabel("#Co-optimaux");
+                       NussinovDemo.formatLabel(cooptlab);
+                       
+                       JPanel commands = new JPanel();
+                       commands.add(previous);
+                       commands.add(next);
+                       
+                       JPanel jp = new JPanel();
+                       jp.setLayout(new BorderLayout());
+                       jp.add(_subopts,BorderLayout.WEST);
+                       jp.add(commands,BorderLayout.CENTER);
+
+                       _suboptBrowser.setLayout(new BorderLayout());
+                       _suboptBrowser.add(cooptlab,BorderLayout.WEST);
+                       _suboptBrowser.add(jp,BorderLayout.CENTER);
+                       
+                       
+               }
+                       
+                               
+               public void setSelectedIndex(int i)
+               {
+                       _selectedIndex = i;
+                       RNA rfolded = new RNA();
+                       try {
+                               rfolded.setRNA(getSeq(), _sols.get(i));
+                               rfolded.drawRNARadiate(_vpMaster.getConfig());
+                               rfolded.setBaseNameColor(Color.white);
+                               rfolded.setBaseOutlineColor(Color.white);
+                               rfolded.setBaseNumbersColor(Color.white);
+                               _vpMaster.setBaseNumbersColor(Color.white);
+                               _vpMaster.setBaseOutlineColor(Color.white);
+                               _vpMaster.setFillBases(false);
+                               _vpMaster.setBaseNameColor(Color.white);
+                               _vpMaster.showRNAInterpolated(rfolded);                 
+                               
+                       } catch (ExceptionUnmatchedClosingParentheses e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       } catch (ExceptionFileFormatOrSyntax e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+                       _struct.setText(_sols.get(i));
+                       formatDescription();
+               }
+               
+               public void setFont(Font f)
+               {
+                       super.setFont(f);
+                       if(_text!=null)
+                       {
+                               _text.setFont(f);
+                               _text.setOpaque(false);
+                       }
+                       if(_subopts!=null)
+                       {
+                       _subopts.setFont(f);
+                       _subopts.setOpaque(false);
+                       }
+               }
+               public void setInfo(ArrayList<String> sols, BigInteger nbFolds)
+               {
+                       _sols = sols;
+                       _nbFolds = nbFolds;
+                       formatDescription();
+                       setSelectedIndex(0);
+               }
+               
+               private void formatDescription()
+               {
+                       _text.setText(""+_nbFolds);
+                       _subopts.setText(""+_sols.size());
+                       next.setEnabled(_sols.size()>1);
+                       previous.setEnabled(_sols.size()>1);
+                       
+               }
+               
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/applications/NussinovDesignDemo.java b/src2/fr/orsay/lri/varna/applications/NussinovDesignDemo.java
new file mode 100644 (file)
index 0000000..9c82a07
--- /dev/null
@@ -0,0 +1,997 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.MouseEvent;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collections;
+
+import javax.swing.BorderFactory;
+import javax.swing.DefaultComboBoxModel;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JSplitPane;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+import javax.swing.JTextPane;
+import javax.swing.border.BevelBorder;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurInterpolator;
+import fr.orsay.lri.varna.exceptions.ExceptionDrawingAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.exceptions.MappingException;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.VARNAConfig.BP_STYLE;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModelBaseStyle;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNABasesListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;;
+
+public class NussinovDesignDemo extends JFrame implements InterfaceVARNAListener,InterfaceVARNABasesListener, ItemListener {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+       private static final String SEQUENCE_A =        "AGGCACGUCU";
+       private static final String SEQUENCE_B =  "GAGUAGCCUC";
+       private static final String SEQUENCE_C = "GCAUAGCUGC";
+       private static final String SEQUENCE_INRIA = "CGAUUGCAUCGCAAGU";
+       
+       private static final String TARGET_STRUCTURE_1 = "(((((((..)))))))";
+       private static final String TARGET_STRUCTURE_2 = "(((())))(((())))";
+       private static final String TARGET_STRUCTURE_3 = "(.((.((..).)).))";
+       private static final String TARGET_STRUCTURE_4 = "((((((())))(((())(()))))))";
+       private static final String TARGET_STRUCTURE_5 = "(((())))(((())))(((())))(((())))(((())))(((())))";
+
+       private static final String SEQUENCE_BIG = "AAAACAAAAACACCAUGGUGUUUUCACCCAAUUGGGUGAAAACAGAGAUCUCGAGAUCUCUGUUUUUGUUUU"; 
+
+       private static final String DEFAULT_STRUCTURE = "..........";
+       // private static final String DEFAULT_STRUCTURE1 = "((((....))))";
+       // private static final String DEFAULT_STRUCTURE2 =
+       // "((((..(((....)))..))))";
+
+       private VARNAPanel _vpMaster;
+       private VARNAPanel _vpTarget;
+
+       private InfoPanel _infos = new InfoPanel();
+       private JPanel _tools = new JPanel();
+       private JPanel _input = new JPanel();
+
+       private JPanel _seqPanel = new JPanel();
+       private JPanel _structPanel = new JPanel();
+       private JLabel _actions = new JLabel();
+       private JComboBox _struct = new JComboBox();
+       private JLabel _seq1 = new JLabel();
+       private JLabel _structLabel = new JLabel("Structure Cible");
+       private JLabel _seqLabel = new JLabel("Sequence d'ARN");
+       private JButton _switchButton = new JButton("Reset");
+
+
+       private Color _backgroundColor = Color.white;
+
+       private Color _okColor = Color.decode("#E33729");
+       private Color _koColor = new Color(250,200,200);
+
+
+       public static ModelBaseStyle createStyle(String txt) 
+       {
+               ModelBaseStyle result = new ModelBaseStyle();
+               try {
+                       result.assignParameters(txt);
+               } catch (ExceptionModeleStyleBaseSyntaxError e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionParameterError e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+               return result;
+       }
+       
+       public void applyTo(VARNAPanel vp, ModelBaseStyle mb, int[] indices)
+       {
+               for(int i=0;i<indices.length;i++)
+               { 
+                       ModeleBase m = vp.getRNA().getBaseAt(indices[i]);
+                       m.setStyleBase(mb);
+                       if (m.getElementStructure()!=-1)
+                       {
+                               vp.getRNA().getBaseAt(m.getElementStructure()).setStyleBase(mb);
+                       }
+               }
+               vp.repaint();
+       }
+       
+       
+       public NussinovDesignDemo() {
+               super();
+               try {
+                       _vpMaster = new VARNAPanel(getSeq(), "");
+                       _vpTarget = new VARNAPanel();
+               } catch (ExceptionNonEqualLength e) {
+                       _vpMaster.errorDialog(e);
+               }
+               _vpMaster.setPreferredSize(new Dimension(600, 600));
+               _vpTarget.setPreferredSize(new Dimension(600, 600));
+               RNAPanelDemoInit();
+       }
+       
+       static Font labelsFont = Font.decode("Dialog-BOLD-25");
+
+       private void RNAPanelDemoInit() {
+               int marginTools = 250;
+               Font textFieldsFont = Font.decode("MonoSpaced-BOLD-16");
+               
+               
+
+               _seq1.setFont(textFieldsFont.deriveFont(25f));
+               
+
+               setBackground(_backgroundColor);
+
+               
+               _structLabel.setFont(labelsFont.deriveFont(Font.PLAIN));
+
+               
+               String[] secstr = {TARGET_STRUCTURE_1,TARGET_STRUCTURE_2,TARGET_STRUCTURE_3,TARGET_STRUCTURE_4,TARGET_STRUCTURE_5};
+               DefaultComboBoxModel cm = new DefaultComboBoxModel(secstr); 
+               _struct.setModel(cm);
+               _struct.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               System.out.println(e.getActionCommand());
+                               setTarget(((JComboBox)e.getSource()).getSelectedItem().toString());
+                       }
+               });
+               _struct.setFont(textFieldsFont);
+               _struct.setEnabled(true);
+               _struct.setEditable(true);
+
+
+               _switchButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               setTarget(_struct.getSelectedItem().toString());                
+                       }
+               });
+
+               _seqPanel.setLayout(new BorderLayout());
+               _seqPanel.add(_seqLabel, BorderLayout.WEST);
+               _seqPanel.add(_seq1, BorderLayout.CENTER);
+
+               _seqPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
+
+               _structLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _structLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _structPanel.setLayout(new BorderLayout());
+               _structPanel.add(_structLabel, BorderLayout.WEST);
+               _structPanel.add(_struct, BorderLayout.CENTER);
+
+               _input.setLayout(new GridLayout(0, 1));
+               _input.add(_structPanel);
+               
+               JPanel goPanel = new JPanel();
+               goPanel.setLayout(new BorderLayout());
+
+               _infos.setFont(labelsFont);
+
+
+               formatLabel(_seqLabel);
+               formatLabel(_seq1);
+
+               
+               _tools.setLayout(new BorderLayout());
+               //_tools.add(_infos, BorderLayout.NORTH);
+               _tools.add(_input, BorderLayout.CENTER);
+               _tools.add(_actions, BorderLayout.SOUTH);
+               _tools.add(goPanel, BorderLayout.EAST);
+               
+               _tools.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
+
+               //goPanel.add(_goButton, BorderLayout.CENTER);
+               goPanel.add(_switchButton, BorderLayout.CENTER);
+
+               getContentPane().setLayout(new BorderLayout());
+               JSplitPane VARNAs = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
+               VARNAs.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
+               //VARNAs.setLayout(new GridLayout(1,2));
+               JPanel mast2 = new JPanel();
+               mast2.setLayout(new BorderLayout());
+               mast2.add(_seqPanel, BorderLayout.NORTH);
+               mast2.add(_infos, BorderLayout.SOUTH);
+
+               JPanel mast = new JPanel();
+               mast.setLayout(new BorderLayout());
+               mast.add(_vpMaster, BorderLayout.CENTER);
+               mast.add(mast2,BorderLayout.SOUTH);
+               
+               VARNAs.add(mast);
+               VARNAs.add(_vpTarget);
+               VARNAs.doLayout();
+               VARNAs.setDividerSize(5);
+               
+               getContentPane().add(VARNAs, BorderLayout.CENTER);
+               getContentPane().add(_tools, BorderLayout.NORTH);
+
+               setVisible(true);
+
+
+               _vpMaster.setBackground(_backgroundColor);
+               _vpMaster.addVARNAListener(this);
+               _vpMaster.setTitle("Meilleur repliement - Séquence courante");
+               _vpMaster.setBPStyle(BP_STYLE.SIMPLE);
+               _vpMaster.getVARNAUI().UIRadiate();
+               _vpMaster.setTitleFontSize(26f);
+               _vpMaster.setTitleFontStyle(Font.PLAIN);
+               
+               _vpTarget.setBackground(Color.decode("#308099"));
+               _vpTarget.setModifiable(false);
+               _vpTarget.setTitle("Repliement cible");
+               _vpTarget.setBPStyle(BP_STYLE.SIMPLE);
+               _vpTarget.setBackboneColor(Color.white);
+               _vpTarget.setDefaultBPColor(Color.white);
+               _vpTarget.setBaseNumbersColor(Color.white);
+               _vpTarget.setBaseOutlineColor(Color.white);
+               _vpTarget.setTitleColor(Color.white);           
+               _vpTarget.setTitleFontSize(26f);
+
+               
+               _okColor = Color.decode("#F39126");
+               _koColor = new Color(250,200,200);
+               
+               _seqPanel.setBackground(Color.decode("#E33729"));
+               _infos.setBackground(Color.decode("#E33729"));
+
+
+               
+               _vpMaster.addVARNABasesListener(this);
+               setTitle("Fête de la science 2015 - Inria AMIB - Design d'ARN");
+               
+               setTarget(secstr[0]);
+               
+       }
+
+       private synchronized void showSolution()
+       {
+               ArrayList<String> sols = getStructs();
+               _infos.setInfo(sols, count(getSeq()));
+               if ((sols.size()==1)&&(sols.get(0).equals(_struct.getSelectedItem().toString())))
+               {
+                       /*JOptionPane.showMessageDialog(null, 
+                                       "Vous avez trouvé une séquence pour cette structure !!!\n Saurez vous faire le design de molécules plus complexes ?",
+                                       "Félicitations !", 
+                                       JOptionPane.INFORMATION_MESSAGE);*/
+                       
+               }
+               else
+               {
+                       this._vpMaster.setTitle("Meilleur repliement - Séquence courante");
+               }
+       }
+       
+
+       public void setTarget(String target)
+       {
+               try {
+                       _vpTarget.drawRNA(String.format("%"+target.length()+"s", ""),target);
+                       _vpTarget.setBaseNumbersColor(Color.white);
+                       _vpTarget.setBaseOutlineColor(Color.white);
+                       //_vpTarget.toggleDrawOutlineBases();
+                       createDummySeq();
+                       showSolution();
+                       onStructureRedrawn();
+               } catch (ExceptionNonEqualLength e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+       }
+       
+       private void createDummySeq()
+       {
+               RNA r = _vpTarget.getRNA();
+               String seq = new String();
+               for (int i=0;i<r.getSize();i++)
+               {
+                       seq += 'A';
+               }
+               try {
+               RNA rn = new RNA();
+                       rn.setRNA(seq,r.getStructDBN());
+               for(ModeleBP mbp: r.getAllBPs())
+               {
+                       rn.getBaseAt(mbp.getIndex5()).setContent("A"); 
+                       rn.getBaseAt(mbp.getIndex3()).setContent("U"); 
+               }
+               _vpMaster.drawRNA(rn);
+               _vpMaster.repaint();
+               _seq1.setText(_vpMaster.getRNA().getSeq());
+               } catch (ExceptionUnmatchedClosingParentheses e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+       }
+
+
+       public String getSeq()
+       {
+               return (""+_seq1.getText()).toUpperCase();
+       }
+
+       
+       private boolean canBasePairAll(char a, char b)
+       {
+               return true;
+       }
+
+       private boolean canBasePairBasic(char a, char b)
+       {
+               if ((a=='G')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='G'))
+                       return true;
+               if ((a=='U')&&(b=='A'))
+                       return true;
+               if ((a=='A')&&(b=='U'))
+                       return true;
+               return false;
+       }
+
+       private double basePairScoreBasic(char a, char b)
+       {
+               if ((a=='G')&&(b=='C'))
+                       return 1.0;
+               if ((a=='C')&&(b=='G'))
+                       return 1.0;
+               if ((a=='U')&&(b=='A'))
+                       return 1.0;
+               if ((a=='A')&&(b=='U'))
+                       return 1.0;
+               return Double.NEGATIVE_INFINITY;
+       }
+
+       
+       private boolean canBasePairNussinov(char a, char b)
+       {
+               if ((a=='G')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='G'))
+                       return true;
+               if ((a=='U')&&(b=='A'))
+                       return true;
+               if ((a=='A')&&(b=='U'))
+                       return true;
+               if ((a=='U')&&(b=='G'))
+                       return true;
+               if ((a=='G')&&(b=='U'))
+                       return true;
+               return false;
+       }
+
+       private double basePairScoreNussinov(char a, char b)
+       {
+               if ((a=='G')&&(b=='C'))
+                       return 3.0;
+               if ((a=='C')&&(b=='G'))
+                       return 3.0;
+               if ((a=='U')&&(b=='A'))
+                       return 2.0;
+               if ((a=='A')&&(b=='U'))
+                       return 2.0;
+               if ((a=='U')&&(b=='G'))
+                       return 1.0;
+               if ((a=='G')&&(b=='U'))
+                       return 1.0;
+               return Double.NEGATIVE_INFINITY;
+       }
+
+       private boolean canBasePairINRIA(char a, char b)
+       {
+               if ((a=='U')&&(b=='A'))
+                       return true;
+               if ((a=='A')&&(b=='U'))
+                       return true;
+               if ((a=='G')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='G'))
+                       return true;
+
+               if ((a=='A')&&(b=='G'))
+                       return true;
+               if ((a=='G')&&(b=='A'))
+                       return true;
+               if ((a=='U')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='U'))
+                       return true;
+               if ((a=='A')&&(b=='A'))
+                       return true;
+               if ((a=='U')&&(b=='U'))
+                       return true;
+
+               if ((a=='U')&&(b=='G'))
+                       return true;
+               if ((a=='G')&&(b=='U'))
+                       return true;
+               if ((a=='A')&&(b=='C'))
+                       return true;
+               if ((a=='C')&&(b=='A'))
+                       return true;
+               return false;
+       }
+
+       private double basePairScoreINRIA(char a, char b)
+       {
+               if ((a=='U')&&(b=='A'))
+                       return 3;
+               if ((a=='A')&&(b=='U'))
+                       return 3;
+               if ((a=='G')&&(b=='C'))
+                       return 3;
+               if ((a=='C')&&(b=='G'))
+                       return 3;
+
+               if ((a=='A')&&(b=='G'))
+                       return 2;
+               if ((a=='G')&&(b=='A'))
+                       return 2;
+               if ((a=='U')&&(b=='C'))
+                       return 2;
+               if ((a=='C')&&(b=='U'))
+                       return 2;
+               if ((a=='A')&&(b=='A'))
+                       return 2;
+               if ((a=='U')&&(b=='U'))
+                       return 2;
+
+               if ((a=='U')&&(b=='G'))
+                       return 1;
+               if ((a=='G')&&(b=='U'))
+                       return 1;
+               if ((a=='A')&&(b=='C'))
+                       return 1;
+               if ((a=='C')&&(b=='A'))
+                       return 1;
+               return Double.NEGATIVE_INFINITY;
+       }
+       
+       private boolean canBasePair(char a, char b)
+       {
+               return canBasePairBasic(a,b);
+               //return canBasePairNussinov(a,b);
+               //return canBasePairINRIA(a,b);
+       }
+       
+       private double basePairScore(char a, char b)
+       {
+               return basePairScoreBasic(a,b);
+               //return basePairScoreNussinov(a,b);
+               //return basePairScoreINRIA(a,b);
+       }
+       
+       public double[][] fillMatrix(String seq)
+       {
+               int n = seq.length();
+               double[][] tab = new double[n][n];
+               for(int m=1;m<=n;m++)
+               {
+                       for(int i=0;i<n-m+1;i++)
+                       {
+                               int j = i+m-1;
+                               tab[i][j] = 0;
+                               if (i<j)
+                               { 
+                                       tab[i][j] = Math.max(tab[i][j], tab[i+1][j]); 
+                                       for (int k=i+1;k<=j;k++)
+                                       {
+                                               if (canBasePair(seq.charAt(i),seq.charAt(k)))
+                                               {
+                                                       double fact1 = 0;
+                                                       if (k>i+1)
+                                                       {
+                                                               fact1 = tab[i+1][k-1];
+                                                       }
+                                                       double fact2 = 0;
+                                                       if (k<j)
+                                                       {
+                                                               fact2 = tab[k+1][j];
+                                                       }
+                                                       tab[i][j] = Math.max(tab[i][j],basePairScore(seq.charAt(i),seq.charAt(k))+fact1+fact2);
+                                               } 
+                                       }
+                               }
+                       }                       
+               }
+               return tab;
+       }
+
+       public static ArrayList<Double> combine(double bonus, ArrayList<Double> part1, ArrayList<Double> part2)
+       {
+               ArrayList<Double> base = new ArrayList<Double>();
+               for(double d1: part1)
+               {
+                       for(double d2: part2)
+                       {
+                               base.add(bonus+d1+d2);
+                       }
+               }
+               return base;
+       }
+
+       public static ArrayList<Double> selectBests(ArrayList<Double> base)
+       {
+               ArrayList<Double> result = new ArrayList<Double>();
+               double best = Double.NEGATIVE_INFINITY;
+               for(double val: base)
+               {
+                       best = Math.max(val, best);
+               }
+               for(double val: base)
+               {
+                       if (val == best)
+                               result.add(val);
+               }
+               return result;
+       }
+
+       
+       private ArrayList<String> backtrack(double[][] tab, String seq)
+       {
+               return backtrack(tab,seq, 0, seq.length()-1);
+       }
+
+       private ArrayList<String> backtrack(double[][] tab, String seq, int i, int j)
+       {
+               ArrayList<String> result = new ArrayList<String>();
+               if (i<j)
+               { 
+                       ArrayList<Integer> indices = new ArrayList<Integer>();
+                       indices.add(-1);
+                       for (int k=i+1;k<=j;k++)
+                       {
+                               indices.add(k);
+                       }
+                       for (int k : indices)
+                       {
+                               if (k==-1)
+                               {
+                                       if (tab[i][j] == tab[i+1][j])
+                                       {
+                                               for (String s:backtrack(tab, seq, i+1,j))
+                                               {
+                                                       result.add("."+s);
+                                               }
+                                       }
+                               }
+                               else
+                               {
+                                       if (canBasePair(seq.charAt(i),seq.charAt(k)))
+                                       {
+                                               double fact1 = 0;
+                                               if (k>i+1)
+                                               {
+                                                       fact1 = tab[i+1][k-1];
+                                               }
+                                               double fact2 = 0;
+                                               if (k<j)
+                                               {
+                                                       fact2 = tab[k+1][j];
+                                               }
+                                               if (tab[i][j]==basePairScore(seq.charAt(i),seq.charAt(k))+fact1+fact2)
+                                               { 
+                                                       for (String s1:backtrack(tab, seq, i+1,k-1))
+                                                       {
+                                                               for (String s2:backtrack(tab, seq, k+1,j))
+                                                               {
+                                                                       result.add("("+s1+")"+s2);
+                                                               }
+                                                       }
+                                               }
+                                       }                                       
+                               }                               
+                       }
+               }
+               else if  (i==j)
+               {
+                       result.add(".");
+               }
+               else 
+               {
+                       result.add("");
+               }
+               return result;
+       }
+       
+       public BigInteger count(String seq)
+       {
+               int n = seq.length();
+               
+               BigInteger[][] tab = new BigInteger[n][n];
+               for(int m=1;m<=n;m++)
+               {
+                       for(int i=0;i<n-m+1;i++)
+                       {
+                               int j = i+m-1;
+                               tab[i][j] = BigInteger.ZERO;
+                               if (i<j)
+                               { 
+                                       tab[i][j] = tab[i][j].add(tab[i+1][j]); 
+                                       for (int k=i+1;k<=j;k++)
+                                       {
+                                               if (canBasePair(seq.charAt(i),seq.charAt(k)))
+                                               {
+                                                       BigInteger fact1 = BigInteger.ONE;
+                                                       if (k>i+1)
+                                                       {
+                                                               fact1 = tab[i+1][k-1];
+                                                       }
+                                                       BigInteger fact2 = BigInteger.ONE;
+                                                       if (k<j)
+                                                       {
+                                                               fact2 = tab[k+1][j];
+                                                       }
+                                                       tab[i][j] = tab[i][j].add(fact1.multiply(fact2));
+                                               } 
+                                       }
+                               }
+                               else
+                               {
+                                       tab[i][j] = BigInteger.ONE;
+                               }
+                       }                       
+               }
+               return tab[0][n-1];
+       }
+       
+       private String _cache = "";
+       ArrayList<String> _cacheStructs = new ArrayList<String>(); 
+       
+       public ArrayList<String> getStructs() {
+               String seq = getSeq();
+               seq = seq.toUpperCase();
+               if (!_cache.equals(seq))
+               {
+                       double[][] mfe = fillMatrix(seq);
+                       _cacheStructs = backtrack(mfe,seq);
+                       _cache = seq;
+               }
+               return _cacheStructs;
+       }
+
+       public VARNAPanel get_varnaPanel() {
+               return _vpMaster;
+       }
+
+       public void set_varnaPanel(VARNAPanel surface) {
+               _vpMaster = surface;
+       }
+
+
+       public JLabel get_info() {
+               return _actions;
+       }
+
+       public void set_info(JLabel _info) {
+               this._actions = _info;
+       }
+
+       public static void main(String[] args) {
+               NussinovDesignDemo d = new NussinovDesignDemo();
+               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               d.pack();
+               d.setVisible(true);
+       }
+
+       public void onStructureRedrawn() {
+               _vpMaster.repaint();
+       }
+
+       public void onWarningEmitted(String s) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onLoad(String path) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onLoaded() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onUINewStructure(VARNAConfig v, RNA r) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       static final String[] _bases =     {"A","C","G","U"};
+       static final String[] _basesComp = {"U","G","C","A"};
+       
+       public void onBaseClicked(ModeleBase mb, MouseEvent e) {
+               int index = -1;
+               for(int i =0;i<_bases.length;i++)
+               {
+                       if (mb.getContent().equalsIgnoreCase(_bases[i]))
+                       {
+                               index = i;
+                       }
+               }
+               index = (index+1)%_bases.length;
+               mb.setContent(_bases[index].toUpperCase());
+               ArrayList<ModeleBase> partners =_vpTarget.getRNA().getAllPartners(mb.getIndex());
+               if (partners.size()!=0)
+               {
+                       ModeleBase mbPartner = _vpMaster.getRNA().getBaseAt(partners.get(0).getIndex());
+                       mbPartner.setContent(_basesComp[index].toUpperCase());
+               }
+               _vpMaster.repaint();
+               _seq1.setText(_vpMaster.getRNA().getSeq());
+               new Temporizer(_vpMaster.getRNA().getSeq()).start();
+       }
+       
+       private class Temporizer extends Thread{
+               String _seq;
+               public Temporizer(String seq)
+               {
+                       _seq = seq;
+               }
+               public void run() {
+            try {
+                               this.sleep(1000);
+                               if (_vpMaster.getRNA().getSeq().equalsIgnoreCase(_seq))
+                               {
+                                       showSolution();
+                               }
+                       } catch (InterruptedException e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+        }
+       }
+       public void onZoomLevelChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onTranslationChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void itemStateChanged(ItemEvent arg0) {
+               // TODO Auto-generated method stub
+               System.out.println();
+       }
+
+       
+       public static void formatLabel(JLabel j)
+       {
+               j.setHorizontalTextPosition(JLabel.LEFT);
+               j.setPreferredSize(new Dimension(NussinovDemo.marginTools, 25));
+               j.setFont(labelsFont);
+               j.setForeground(Color.white);
+       }
+       
+       public static void formatLabel(JTextArea j)
+       {
+               j.setPreferredSize(new Dimension(NussinovDemo.marginTools, 25));
+               j.setFont(labelsFont);
+               j.setForeground(Color.white);
+       }
+
+       public class InfoPanel extends JPanel
+       {
+               ArrayList<String> _sols = new ArrayList<String>();
+               BigInteger _nbFolds = BigInteger.ZERO;
+               JLabel _text = new JLabel("");
+               JLabel _subopts = new JLabel("");
+               JPanel _suboptBrowser = new JPanel();
+               JPanel _suboptCount = new JPanel();
+               int _selectedIndex = 0;
+               JButton next = new JButton(">");
+               JButton previous = new JButton("<");
+               
+               InfoPanel()
+               {
+                       this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
+                       setLayout(new BorderLayout());
+                       add(_suboptBrowser,BorderLayout.SOUTH);
+                       add(_suboptCount,BorderLayout.NORTH);
+                       
+                       next.addActionListener(new ActionListener(){
+                               public void actionPerformed(ActionEvent arg0) {
+                                       if (_sols.size()>0)
+                                       {
+                                               setSelectedIndex((_selectedIndex+1)%_sols.size());
+                                       }
+                               }                               
+                       });
+
+                       previous.addActionListener(new ActionListener(){
+                               public void actionPerformed(ActionEvent arg0) {
+                                       if (_sols.size()>0)
+                                       {
+                                               setSelectedIndex((_selectedIndex+_sols.size()-1)%_sols.size());
+                                       }
+                               }                               
+                       });
+                       next.setEnabled(false);
+                       previous.setEnabled(false);
+
+                       JLabel nbLab = new JLabel("#Repliements");
+                       NussinovDesignDemo.formatLabel(nbLab);
+                       
+
+                       JLabel cooptlab = new JLabel("#Co-optimaux");
+                       NussinovDesignDemo.formatLabel(cooptlab);
+                       
+                       NussinovDesignDemo.formatLabel(_text);
+                       NussinovDesignDemo.formatLabel(_subopts);
+
+                       
+                       _suboptCount.setLayout(new BorderLayout());
+                       _suboptCount.add(nbLab,BorderLayout.WEST);
+                       _suboptCount.add(_text,BorderLayout.CENTER);
+                       _suboptCount.setBackground(Color.decode("#E33729"));
+
+                       
+                       JPanel commands = new JPanel();
+                       commands.add(previous);
+                       commands.add(next);
+                       commands.setBackground(Color.decode("#E33729"));
+                       
+                       JPanel jp = new JPanel();
+                       jp.setLayout(new BorderLayout());
+                       jp.add(_subopts,BorderLayout.WEST);
+                       jp.add(commands,BorderLayout.CENTER);
+                       jp.setBackground(Color.decode("#E33729"));
+
+                       _suboptBrowser.setLayout(new BorderLayout());
+                       _suboptBrowser.add(cooptlab,BorderLayout.WEST);
+                       _suboptBrowser.add(jp,BorderLayout.CENTER);
+                       _suboptBrowser.setBackground(Color.decode("#E33729"));
+                       
+               }
+                       
+                               
+               /*public void setSelectedIndex(int i)
+               {
+                       _selectedIndex = i;
+                       RNA rfolded = new RNA();
+                       try {
+                               rfolded.setRNA(getSeq(), _sols.get(i));
+                               rfolded.drawRNARadiate(_vpMaster.getConfig());
+                       _vpMaster.showRNAInterpolated(rfolded);
+                       } catch (ExceptionUnmatchedClosingParentheses e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       } catch (ExceptionFileFormatOrSyntax e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+                       //_struct.setText(_sols.get(i));
+                       formatDescription();
+               }*/
+               
+               public void setSelectedIndex(int i)
+               {
+                       _selectedIndex = i;
+                       RNA rfolded = new RNA();
+                       try {
+                               rfolded.setRNA(getSeq(), _sols.get(i));
+                               RNA target = _vpTarget.getRNA();
+                               for(ModeleBase mb: rfolded.get_listeBases())
+                               {
+                                       ModeleBase mbref = target.getBaseAt(mb.getIndex());
+                                       if (mb.getElementStructure()==mbref.getElementStructure())
+                                       {
+                                               mb.getStyleBase().setBaseInnerColor(_okColor);
+                                               mb.getStyleBase().setBaseNameColor(Color.white);
+                                       }
+                               }                               
+                               for(ModeleBase mb: target.get_listeBases())
+                               {
+                                       ModeleBase mbref = rfolded.getBaseAt(mb.getIndex());
+                                       if (mb.getElementStructure()==mbref.getElementStructure())
+                                       {
+                                               mb.getStyleBase().setBaseInnerColor(_okColor);
+                                       }
+                                       else
+                                       {
+                                               mb.getStyleBase().setBaseInnerColor(Color.white);
+                                       }
+                               }                               
+                               rfolded.drawRNARadiate(_vpMaster.getConfig());
+                               if ((_sols.size()==1)&& (target.getStructDBN().equals(_sols.get(0))))                                   
+                                       rfolded.setName("Félicitations !");
+                               else
+                                       rfolded.setName("Repliement stable - "+(i+1)+"/"+_sols.size());
+                       _vpMaster.showRNAInterpolated(rfolded);
+                       _vpTarget.repaint();
+                       } catch (ExceptionUnmatchedClosingParentheses e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       } catch (ExceptionFileFormatOrSyntax e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+                       //_struct.setSelectedItem(_sols.get(i));
+                       formatDescription();
+               }
+               
+//             public void setFont(Font f)
+//             {
+//                     super.setFont(f);
+//                     if(_text!=null)
+//                     {
+//                             _text.setFont(f);
+//                             _text.setOpaque(false);
+//                     }
+//                     if(_subopts!=null)
+//                     {
+//                     _subopts.setFont(f);
+//                     _subopts.setOpaque(false);
+//                     }
+//             }
+               public void setInfo(ArrayList<String> sols, BigInteger nbFolds)
+               {
+                       _sols = sols;
+                       _nbFolds = nbFolds;
+                       formatDescription();
+                       setSelectedIndex(0);
+               }
+               
+               private void formatDescription()
+               {
+                       _text.setText(""+_nbFolds);
+                       _subopts.setText(""+_sols.size());
+                       next.setEnabled(_sols.size()>1);
+                       previous.setEnabled(_sols.size()>1);
+                       
+               }
+               
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/SecStrConsensus.java b/src2/fr/orsay/lri/varna/applications/SecStrConsensus.java
new file mode 100644 (file)
index 0000000..5fce12b
--- /dev/null
@@ -0,0 +1,189 @@
+package fr.orsay.lri.varna.applications;
+
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+public class SecStrConsensus {
+       
+       
+       /**
+        * Internal class to represent a simple base-pair.
+        * @author Yawn
+        *
+        */
+       static class SimpleBP{
+               int bp5;
+               int bp3;
+               
+               public SimpleBP(int i5, int i3)
+               {
+                       bp5=i5;
+                       bp3=i3;
+               }
+       }
+       
+       public static int[] extractConsensus(ArrayList<ArrayList<SimpleBP>> bps)
+       {
+               // We do not currently know the length of the alignment
+               // => Estimate it as the biggest index of a base-pair plus one. 
+               int maxlength = 0;
+               for (ArrayList<SimpleBP> strs : bps)
+               {
+                       for (SimpleBP bp : strs)
+                       {
+                               maxlength = Math.max(1+Math.max(bp.bp5, bp.bp3), maxlength);
+                       }
+               }
+               // Now we have a good estimate for length, allocate and initialize data
+               // to be fed to the dynamic programming procedure.
+               ArrayList<Hashtable<Integer,Double>> seq = new ArrayList<Hashtable<Integer,Double>>();
+               for (int i=0;i<seq.size();i++)
+               { seq.add(new Hashtable<Integer,Double>()); }
+               for (ArrayList<SimpleBP> strs : bps)
+               {
+                       for (SimpleBP bp : strs)
+                       {
+                               int i = bp.bp5;
+                               int j = bp.bp3;
+                               Hashtable<Integer,Double> h = seq.get(i);
+                               if (!h.containsKey(j))
+                               {
+                                       h.put(j, 0.0);
+                               }
+                               h.put(j, h.get(i)+1.);
+                       }
+               }
+               // At this point, seq contains, at each position i, a hashtable which associates,
+               // to each possible end j, the number of time a base-pair (i,j) occurs in the alignment
+               
+               // We can now run the dynamic programming procedure on this data
+               double[][] mat = fillMatrix(seq); 
+               ArrayList<SimpleBP> res = backtrack(mat,seq);
+               
+               // Convert it to an array, ie finalres[i] = j >= 0 iff a base-pair (i,j) is present 
+               // in the consensus, or -1 otherwise
+               int[] finalres = new int[seq.size()];
+               for (int i=0;i<seq.size();i++)
+               { finalres[i] = -1; }
+               for (SimpleBP bp : res)
+               {
+                       finalres[bp.bp5] = bp.bp3;
+                       finalres[bp.bp3] = bp.bp5;
+               }
+               
+               return finalres;
+       }
+       
+       private static boolean canBasePair(ArrayList<Hashtable<Integer,Double>> seq, int i, int k)
+       {
+               return seq.get(i).containsKey(k);
+       }
+       
+       // Returns the score of a potential base-pair, ie the number of structures in which it is found.
+       private static double basePairScore(ArrayList<Hashtable<Integer,Double>> seq, int i, int k)
+       {
+               return seq.get(i).get(k);       
+       }
+       
+       
+       private static double[][] fillMatrix(ArrayList<Hashtable<Integer,Double>> seq)
+       {
+               int n = seq.size();
+               double[][] tab = new double[n][n];
+               for(int m=1;m<=n;m++)
+               {
+                       for(int i=0;i<n-m+1;i++)
+                       {
+                               int j = i+m-1;
+                               tab[i][j] = 0;
+                               if (i<j)
+                               { 
+                                       tab[i][j] = Math.max(tab[i][j], tab[i+1][j]); 
+                                       for (int k=i+1;k<=j;k++)
+                                       {
+                                               if (canBasePair(seq,i,k))
+                                               {
+                                                       double fact1 = 0;
+                                                       if (k>i+1)
+                                                       {
+                                                               fact1 = tab[i+1][k-1];
+                                                       }
+                                                       double fact2 = 0;
+                                                       if (k<j)
+                                                       {
+                                                               fact2 = tab[k+1][j];
+                                                       }
+                                                       tab[i][j] = Math.max(tab[i][j],basePairScore(seq,i,k)+fact1+fact2);
+                                               } 
+                                       }
+                               }
+                       }                       
+               }
+               return tab;
+       }       
+       
+       private static  ArrayList<SimpleBP> backtrack(double[][] tab,ArrayList<Hashtable<Integer,Double>> seq)
+       {
+               return backtrack(tab,seq,0,seq.size()-1);
+       }
+       
+       private static ArrayList<SimpleBP> backtrack(double[][] tab,ArrayList<Hashtable<Integer,Double>> seq, int i, int j)
+       {
+               ArrayList<SimpleBP> result = new ArrayList<SimpleBP>();
+               if (i<j)
+               { 
+                       ArrayList<Integer> indices = new ArrayList<Integer>();
+                       indices.add(-1);
+                       for (int k=i+1;k<=j;k++)
+                       {
+                               indices.add(k);
+                       }
+                       for (int k : indices)
+                       {
+                               if (k==-1)
+                               {
+                                       if (tab[i][j] == tab[i+1][j])
+                                       {
+                                               result = backtrack(tab, seq, i+1,j);
+                                       }
+                               }
+                               else
+                               {
+                                       if (canBasePair(seq,i,k))
+                                       {
+                                               double fact1 = 0;
+                                               if (k>i+1)
+                                               {
+                                                       fact1 = tab[i+1][k-1];
+                                               }
+                                               double fact2 = 0;
+                                               if (k<j)
+                                               {
+                                                       fact2 = tab[k+1][j];
+                                               }
+                                               if (tab[i][j]==basePairScore(seq,i,k)+fact1+fact2)
+                                               { 
+                                                       result = backtrack(tab, seq, i+1,k-1);
+                                                       result.addAll(backtrack(tab, seq, k+1,j));
+                                                       result.add(new SimpleBP(i,k));
+                                               }
+                                       }                                       
+                               }                               
+                       }
+               }
+               else if  (i==j)
+               {
+                       
+               }
+               else 
+               {
+                       
+               }
+               return result;
+       }
+       
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/SuperpositionDemo.java b/src2/fr/orsay/lri/varna/applications/SuperpositionDemo.java
new file mode 100644 (file)
index 0000000..edef438
--- /dev/null
@@ -0,0 +1,467 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurInterpolator;
+import fr.orsay.lri.varna.exceptions.ExceptionDrawingAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.exceptions.MappingException;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModelBaseStyle;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;;
+
+public class SuperpositionDemo extends JFrame implements InterfaceVARNAListener {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+       private static final String DEFAULT_SEQUENCE1 = "CGCGCACGCGAUAUUUCGCGUCGCGCAUUUGCGCGUAGCGCG";
+       private static final String DEFAULT_SEQUENCE2 = "CGCGCACGCGAUAUUUCGCGUCGCGCAUUUGCGCGUAGCGCG";
+
+       private static final String DEFAULT_STRUCTURE1 = "(((((.(((((----....----))))).(((((....)))))..)))))";
+       private static final String DEFAULT_STRUCTURE2 = "(((((.(((((((((....))))))))).--------------..)))))";
+       // private static final String DEFAULT_STRUCTURE1 = "((((....))))";
+       // private static final String DEFAULT_STRUCTURE2 =
+       // "((((..(((....)))..))))";
+
+       private VARNAPanel _vpMaster;
+       private VARNAPanel _vpSlave;
+
+       private JPanel _tools = new JPanel();
+       private JPanel _input = new JPanel();
+
+       private JPanel _seqPanel = new JPanel();
+       private JPanel _struct1Panel = new JPanel();
+       private JPanel _struct2Panel = new JPanel();
+       private JLabel _info = new JLabel();
+       private JTextField _struct1 = new JTextField(DEFAULT_STRUCTURE1);
+       private JTextField _struct2 = new JTextField(DEFAULT_STRUCTURE2);
+       private JTextField _seq1 = new JTextField(DEFAULT_SEQUENCE1);
+       private JTextField _seq2 = new JTextField(DEFAULT_SEQUENCE2);
+       private JLabel _struct1Label = new JLabel(" Str1:");
+       private JLabel _struct2Label = new JLabel(" Str2:");
+       private JLabel _seqLabel = new JLabel(" Seq:");
+       private JButton _goButton = new JButton("Go");
+       private JButton _switchButton = new JButton("Switch");
+
+       private String _str1Backup = "";
+       private String _str2Backup = "";
+       private RNA _RNA1 = new RNA();
+       private RNA _RNA2 = new RNA();
+
+       private static String errorOpt = "error";
+       @SuppressWarnings("unused")
+       private boolean _error;
+
+       private Color _backgroundColor = Color.white;
+
+       @SuppressWarnings("unused")
+       private int _algoCode;
+
+       private int _currentDisplay = 1;
+
+       public static ModelBaseStyle createStyle(String txt) 
+       {
+               ModelBaseStyle result = new ModelBaseStyle();
+               try {
+                       result.assignParameters(txt);
+               } catch (ExceptionModeleStyleBaseSyntaxError e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionParameterError e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+               return result;
+       }
+       
+       public void applyTo(VARNAPanel vp, ModelBaseStyle mb, int[] indices)
+       {
+               for(int i=0;i<indices.length;i++)
+               { 
+                       ModeleBase m = vp.getRNA().getBaseAt(indices[i]);
+                       m.setStyleBase(mb);
+                       if (m.getElementStructure()!=-1)
+                       {
+                               vp.getRNA().getBaseAt(m.getElementStructure()).setStyleBase(mb);
+                       }
+               }
+               vp.repaint();
+       }
+       
+       
+       public SuperpositionDemo() {
+               super();
+               try {
+                       _vpMaster = new VARNAPanel(getText1(), getStruct1());
+                       _vpSlave = new VARNAPanel(getText2(), getStruct2());
+               } catch (ExceptionNonEqualLength e) {
+                       _vpMaster.errorDialog(e);
+               }
+               _vpMaster.setPreferredSize(new Dimension(400, 400));
+               RNAPanelDemoInit();
+       }
+
+       private void RNAPanelDemoInit() {
+               int marginTools = 40;
+
+               setBackground(_backgroundColor);
+               _vpMaster.setBackground(_backgroundColor);
+               _vpMaster.addVARNAListener(this);
+               //_vpSlave.setModifiable(false);
+               _vpSlave.setBackground(Color.decode("#F0F0F0"));
+
+               _vpMaster.drawRNA(getRNA((_currentDisplay)%2));
+               _vpSlave.drawRNA(getRNA((_currentDisplay+1)%2));
+
+               /*ModeleStyleBase red = createStyle("label=#ff4d4d,fill=#ffdddd,outline=#ff4d4d");
+               int[] ired = {6,7,8,9,10};
+               applyTo(_vpMaster, red, ired);
+               applyTo(_vpSlave, red, ired);
+               ModeleStyleBase blue = createStyle("label=#0000ff,fill=#ddddff,outline=#0000ff");
+               int[] iblue = {0,1,2,3,4};
+               applyTo(_vpMaster, blue, iblue);
+               applyTo(_vpSlave, blue, iblue);
+               ModeleStyleBase purple = createStyle("label=#cc00cc,fill=#ffddff,outline=#cc00cc");
+               int[] ipurple = {21,22,23,24,25};
+               applyTo(_vpMaster, purple, ipurple);
+               ModeleStyleBase green = createStyle("label=#009900,fill=#aaeeaa,outline=#009900");
+               int[] igreen = {11,12,13,14};
+               applyTo(_vpSlave, green, igreen);*/
+               
+               Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
+
+               _seqLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _seqLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _seq1.setFont(textFieldsFont);
+               _seq1.setText(getRNA1().getSeq());
+               _seq2.setFont(textFieldsFont);
+               _seq2.setText(getRNA2().getSeq());
+
+               _goButton.addActionListener(new ActionListener() {
+
+                       public void actionPerformed(ActionEvent e) {
+                               _currentDisplay = (_currentDisplay + 1) % 2;
+                               _vpMaster.drawRNA(getRNA(_currentDisplay));
+                               _vpSlave.drawRNA(getRNA((_currentDisplay + 1) % 2));
+                               onStructureRedrawn();
+                       }
+               });
+
+               _switchButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               try {
+                                       _currentDisplay = (_currentDisplay + 1) % 2;
+
+                                                       Mapping m = Mapping.readMappingFromAlignment(
+                                                                       getStruct(_currentDisplay), getStruct((_currentDisplay+1)%2));
+                                                       Mapping m2 = Mapping.readMappingFromAlignment(
+                                                                       getStruct((_currentDisplay+1)%2), getStruct(_currentDisplay));
+                                                       _vpMaster.showRNAInterpolated(getRNA(_currentDisplay), m);
+                                                       _vpSlave.showRNAInterpolated(getRNA((_currentDisplay+1)%2), m2);
+                                                       onStructureRedrawn();
+                                       } 
+                               catch (MappingException e3) 
+                               {
+                                                       try {
+                                                               _vpMaster.drawRNAInterpolated(getText(_currentDisplay),getStruct(_currentDisplay));
+                                                       } catch (ExceptionNonEqualLength e1) {
+                                                               // TODO Auto-generated catch block
+                                                               e1.printStackTrace();
+                                                       }
+                                               }
+                               _vpMaster.repaint();
+                               _vpSlave.repaint();
+                       }
+               });
+
+               _seqPanel.setLayout(new BorderLayout());
+               _seqPanel.add(_seqLabel, BorderLayout.WEST);
+               _seqPanel.add(_seq1, BorderLayout.CENTER);
+
+               _struct1Label.setPreferredSize(new Dimension(marginTools, 15));
+               _struct1Label.setHorizontalTextPosition(JLabel.LEFT);
+               _struct1.setFont(textFieldsFont);
+               _struct1Panel.setLayout(new BorderLayout());
+               _struct1Panel.add(_struct1Label, BorderLayout.WEST);
+               _struct1Panel.add(_struct1, BorderLayout.CENTER);
+
+               _struct2Label.setPreferredSize(new Dimension(marginTools, 15));
+               _struct2Label.setHorizontalTextPosition(JLabel.LEFT);
+               _struct2.setFont(textFieldsFont);
+               _struct2Panel.setLayout(new BorderLayout());
+               _struct2Panel.add(_struct2Label, BorderLayout.WEST);
+               _struct2Panel.add(_struct2, BorderLayout.CENTER);
+
+               _input.setLayout(new GridLayout(3, 0));
+               _input.add(_seqPanel);
+               _input.add(_struct1Panel);
+               _input.add(_struct2Panel);
+
+               JPanel goPanel = new JPanel();
+               goPanel.setLayout(new BorderLayout());
+
+               _tools.setLayout(new BorderLayout());
+               _tools.add(_input, BorderLayout.CENTER);
+               _tools.add(_info, BorderLayout.SOUTH);
+               _tools.add(goPanel, BorderLayout.EAST);
+
+               goPanel.add(_goButton, BorderLayout.CENTER);
+               goPanel.add(_switchButton, BorderLayout.SOUTH);
+
+               getContentPane().setLayout(new BorderLayout());
+               JPanel VARNAs = new JPanel();
+               VARNAs.setLayout(new GridLayout(1,2));
+               VARNAs.add(_vpMaster);
+               VARNAs.add(_vpSlave);
+               getContentPane().add(VARNAs, BorderLayout.CENTER);
+               getContentPane().add(_tools, BorderLayout.SOUTH);
+
+               setVisible(true);
+
+               _vpMaster.getVARNAUI().UIRadiate();
+               _vpSlave.getVARNAUI().UIRadiate();              
+               
+               onStructureRedrawn();
+       }
+
+       public RNA getMasterRNA()
+       {
+               return getRNA(_currentDisplay);
+       }
+
+       public RNA getSlaveRNA1()
+       {
+               return getRNA((_currentDisplay+1)%2);
+       }
+
+       public RNA getSlaveRNA2()
+       {
+               return getRNA((_currentDisplay+2)%2);
+       }
+
+       
+       public RNA getRNA(int i) {
+         if (i==0)
+         {  return getRNA1();  }
+         else 
+         {  return getRNA2();  }
+       }
+
+       
+       public RNA getRNA1() {
+               if (!_str1Backup.equals(getStruct1())) {
+                       try {
+                               _RNA1.setRNA(getText1(), getStruct1());
+                               _RNA1.drawRNA(_vpMaster.getDrawMode(),_vpMaster.getConfig());
+                       } catch (ExceptionUnmatchedClosingParentheses e) {
+                               e.printStackTrace();
+                       } catch (ExceptionFileFormatOrSyntax e1) {
+                               _vpMaster.errorDialog(e1);
+                       } catch (ExceptionDrawingAlgorithm e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+                       _str1Backup = getStruct1();
+               }
+               return _RNA1;
+       }
+
+       public RNA getRNA2() {
+               if (!_str2Backup.equals(getStruct2())) {
+                       try {
+                               _RNA2.setRNA(getText2(), getStruct2());
+                               _RNA2.drawRNA(_vpMaster.getDrawMode(),_vpMaster.getConfig());
+                       } catch (ExceptionUnmatchedClosingParentheses e) {
+                               e.printStackTrace();
+                       } catch (ExceptionFileFormatOrSyntax e1) {
+                               _vpMaster.errorDialog(e1);
+                       } catch (ExceptionDrawingAlgorithm e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+                       _str2Backup = getStruct2();
+               }
+               return _RNA2;
+       }
+
+    public String getText(int i)
+    {
+       return "";
+    }
+
+    public String getStruct(int i)
+    {
+       if (i==0) 
+               return _struct1.getText();
+       else
+               return _struct2.getText();
+    }
+
+    
+       public String getText1()
+       {
+               return _seq1.getText();
+       }
+
+       public String getText2()
+       {
+               return _seq2.getText();
+       }
+
+       public String getStruct1() {
+               return cleanStruct(_struct1.getText());
+       }
+
+       public String getStruct2() {
+               return cleanStruct(_struct2.getText());
+       }
+
+       private String cleanStruct(String struct) {
+               struct = struct.replaceAll("[:-]", "");
+               return struct;
+       }
+
+       public String[][] getParameterInfo() {
+               String[][] info = {
+                               // Parameter Name Kind of Value Description,
+                               { "sequenceDBN", "String", "A raw RNA sequence" },
+                               { "structureDBN", "String",
+                                               "An RNA structure in dot bracket notation (DBN)" },
+                               { errorOpt, "boolean", "To show errors" }, };
+               return info;
+       }
+
+       public void init() {
+               _vpMaster.setBackground(_backgroundColor);
+               _error = true;
+       }
+
+       @SuppressWarnings("unused")
+       private Color getSafeColor(String col, Color def) {
+               Color result;
+               try {
+                       result = Color.decode(col);
+               } catch (Exception e) {
+                       try {
+                               result = Color.getColor(col, def);
+                       } catch (Exception e2) {
+                               return def;
+                       }
+               }
+               return result;
+       }
+
+       public VARNAPanel get_varnaPanel() {
+               return _vpMaster;
+       }
+
+       public void set_varnaPanel(VARNAPanel surface) {
+               _vpMaster = surface;
+       }
+
+       public JTextField get_struct() {
+               return _struct1;
+       }
+
+       public void set_struct(JTextField _struct) {
+               this._struct1 = _struct;
+       }
+
+       public JLabel get_info() {
+               return _info;
+       }
+
+       public void set_info(JLabel _info) {
+               this._info = _info;
+       }
+
+       public static void main(String[] args) {
+               SuperpositionDemo d = new SuperpositionDemo();
+               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               d.pack();
+               d.setVisible(true);
+       }
+
+       public void onStructureRedrawn() {
+               try{
+                                       Mapping m = Mapping.readMappingFromAlignment(
+                                                       this.getStruct((_currentDisplay+1)%2), getStruct((_currentDisplay)%2));
+                                       ControleurInterpolator.moveNearOtherRNA(getRNA((_currentDisplay)%2), getRNA((_currentDisplay+1)%2), m);
+                                       _vpSlave.repaint();
+                                       _vpMaster.repaint();
+               }
+               catch (MappingException e3) {System.out.println(e3.toString());}
+       }
+
+       public void onWarningEmitted(String s) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onLoad(String path) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onLoaded() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onUINewStructure(VARNAConfig v, RNA r) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onZoomLevelChanged(){
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onTranslationChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/VARNAConsoleDemo.java b/src2/fr/orsay/lri/varna/applications/VARNAConsoleDemo.java
new file mode 100644 (file)
index 0000000..487fa96
--- /dev/null
@@ -0,0 +1,266 @@
+package fr.orsay.lri.varna.applications;
+
+/*
+VARNA is a Java library for quick automated drawings RNA secondary structure 
+Copyright (C) 2007  Yann Ponty
+
+This program 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 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>. 
+*/
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JApplet;
+import javax.swing.JButton;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.VARNAConsole;
+import fr.orsay.lri.varna.controlers.ControleurDemoTextField;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+/**
+* An RNA 2d Panel demo applet
+* 
+* @author Yann Ponty & Darty Kévin
+* 
+*/
+
+public class VARNAConsoleDemo extends JApplet implements ActionListener  {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+       private static final String DEFAULT_SEQUENCE = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
+
+       private static final String DEFAULT_STRUCTURE = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
+
+       private VARNAPanel _vp;
+
+       private JPanel _tools = new JPanel();
+       private JPanel _input = new JPanel();
+
+       private JPanel _seqPanel = new JPanel();
+       private JPanel _structPanel = new JPanel();
+       private JLabel _info = new JLabel();
+       private JButton _go = new JButton("Go");
+       private JTextField _struct = new JTextField();
+       private JTextField _seq = new JTextField();
+       private JLabel _structLabel = new JLabel(" Str:");
+       private JLabel _seqLabel = new JLabel(" Seq:");
+
+       private VARNAConsole _console;
+
+       private static String errorOpt = "error";
+       private boolean _error;
+
+       private Color _backgroundColor = Color.white;
+
+       private int _algoCode;
+
+       public VARNAConsoleDemo() {
+               super();
+               try {
+                       _vp = new VARNAPanel(_seq.getText(), _struct.getText());
+                       _vp.setErrorsOn(false);
+               } catch (ExceptionNonEqualLength e) {
+                       _vp.errorDialog(e);
+               }
+               RNAPanelDemoInit();
+       }
+
+       private void RNAPanelDemoInit() {
+               
+               
+               int marginTools = 40;
+
+               setBackground(_backgroundColor);
+               _vp.setBackground(_backgroundColor);
+
+               try {
+                       _vp.getRNA().setRNA(_seq.getText(), _struct.getText());
+                       _vp.setErrorsOn(false);
+               } catch (Exception e1) {
+                       _vp.errorDialog(e1);
+               }
+
+               Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
+
+               _console = new VARNAConsole(_vp); 
+
+               
+               _go.addActionListener(this);
+               
+               _seqLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _seqLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _seq.setFont(textFieldsFont);
+               _seq.setText(_vp.getRNA().getSeq());
+
+               _seqPanel.setLayout(new BorderLayout());
+               _seqPanel.add(_seqLabel, BorderLayout.WEST);
+               _seqPanel.add(_seq, BorderLayout.CENTER);
+
+               _structLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _structLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _struct.setFont(textFieldsFont);
+               _struct.setText(_vp.getRNA().getStructDBN());
+               _structPanel.setLayout(new BorderLayout());
+               _structPanel.add(_structLabel, BorderLayout.WEST);
+               _structPanel.add(_struct, BorderLayout.CENTER);
+
+
+               _input.setLayout(new GridLayout(3, 0));
+               _input.add(_seqPanel);
+               _input.add(_structPanel);
+
+               _tools.setLayout(new BorderLayout());
+               _tools.add(_input, BorderLayout.CENTER);
+               _tools.add(_info, BorderLayout.SOUTH);
+               _tools.add(_go, BorderLayout.EAST);
+
+               getContentPane().setLayout(new BorderLayout());
+               getContentPane().add(_vp, BorderLayout.CENTER);
+               getContentPane().add(_tools, BorderLayout.SOUTH);
+
+               _vp.getVARNAUI().UIRadiate();
+               setPreferredSize(new Dimension(400,400));
+               
+               setVisible(true);
+               
+               _console.setVisible(true);
+               
+       }
+
+       public String[][] getParameterInfo() {
+               String[][] info = {
+                               // Parameter Name Kind of Value Description,
+                               { "sequenceDBN", "String", "A raw RNA sequence" },
+                               { "structureDBN", "String",
+                                               "An RNA structure in dot bracket notation (DBN)" },
+                               { errorOpt, "boolean", "To show errors" }, };
+               return info;
+       }
+
+       public void init() {
+               retrieveParametersValues();
+               _vp.setBackground(_backgroundColor);
+               _error = true;
+       }
+
+       private Color getSafeColor(String col, Color def) {
+               Color result;
+               try {
+                       result = Color.decode(col);
+               } catch (Exception e) {
+                       try {
+                               result = Color.getColor(col, def);
+                       } catch (Exception e2) {
+                               return def;
+                       }
+               }
+               return result;
+       }
+
+       private String getParameterValue(String key, String def) {
+               String tmp;
+               tmp = getParameter(key);
+               if (tmp == null) {
+                       return def;
+               } else {
+                       return tmp;
+               }
+       }
+
+       private void retrieveParametersValues() {
+               _error = Boolean.parseBoolean(getParameterValue(errorOpt, "false"));
+               _vp.setErrorsOn(_error);
+               _backgroundColor = getSafeColor(getParameterValue("background",
+                               _backgroundColor.toString()), _backgroundColor);
+               _vp.setBackground(_backgroundColor);
+               _seq.setText(getParameterValue("sequenceDBN", ""));
+               _struct.setText(getParameterValue("structureDBN", ""));
+               String _algo = getParameterValue("algorithm", "radiate");
+               if (_algo.equals("circular"))
+                       _algoCode = RNA.DRAW_MODE_CIRCULAR;
+               else if (_algo.equals("naview"))
+                       _algoCode = RNA.DRAW_MODE_NAVIEW;
+               else if (_algo.equals("line"))
+                       _algoCode = RNA.DRAW_MODE_LINEAR;
+               else
+                       _algoCode = RNA.DRAW_MODE_RADIATE;
+               if (_seq.getText().equals("") && _struct.getText().equals("")) {
+                       _seq.setText(DEFAULT_SEQUENCE);
+                       _struct.setText(DEFAULT_STRUCTURE);
+               }
+               try {
+                       _vp.drawRNA(_seq.getText(), _struct.getText(), _algoCode);
+               } catch (ExceptionNonEqualLength e) {
+                       e.printStackTrace();
+               }
+
+       }
+
+       public VARNAPanel get_varnaPanel() {
+               return _vp;
+       }
+
+       public void set_varnaPanel(VARNAPanel surface) {
+               _vp = surface;
+       }
+
+       public JTextField get_struct() {
+               return _struct;
+       }
+
+       public void set_struct(JTextField _struct) {
+               this._struct = _struct;
+       }
+
+       public JTextField get_seq() {
+               return _seq;
+       }
+
+       public void set_seq(JTextField _seq) {
+               this._seq = _seq;
+       }
+
+       public JLabel get_info() {
+               return _info;
+       }
+
+       public void set_info(JLabel _info) {
+               this._info = _info;
+       }
+
+       public void actionPerformed(ActionEvent arg0) {
+                 RNA r = new RNA();
+                 try {
+                       _vp.drawRNAInterpolated(_seq.getText(), _struct.getText());
+               } catch (ExceptionNonEqualLength e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+                 _vp.repaint();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/VARNAEditor.java b/src2/fr/orsay/lri/varna/applications/VARNAEditor.java
new file mode 100644 (file)
index 0000000..818cfda
--- /dev/null
@@ -0,0 +1,659 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.geom.Point2D.Double;
+import java.io.File;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Set;
+
+import javax.swing.DefaultListModel;
+import javax.swing.DefaultListSelectionModel;
+import javax.swing.Icon;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTextField;
+import javax.swing.ListModel;
+import javax.swing.ListSelectionModel;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.DefaultHighlighter;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.ReorderableJList;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNARNAListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNASelectionListener;
+import fr.orsay.lri.varna.models.BaseList;
+import fr.orsay.lri.varna.models.FullBackup;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VARNAEditor extends JFrame implements DropTargetListener, InterfaceVARNAListener, MouseListener {
+
+       /**
+        * 
+        */
+//     private static final_long serialVersionUID = -790155708306987257L;
+
+       private static final String DEFAULT_SEQUENCE = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
+
+       private static final String DEFAULT_STRUCTURE1 = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
+       private static final String DEFAULT_STRUCTURE2 = "..(((((...(((((...(((((........(((((...(((((.....)))))...)))))..................))))).....)))))...)))))..";
+       // private static final String DEFAULT_STRUCTURE1 = "((((....))))";
+       // private static final String DEFAULT_STRUCTURE2 =
+       // "((((..(((....)))..))))";
+
+       private VARNAPanel _vp;
+
+       private JPanel _tools = new JPanel();
+       private JPanel _input = new JPanel();
+
+       private JPanel _seqPanel = new JPanel();
+       private JPanel _strPanel = new JPanel();
+       private JLabel _info = new JLabel();
+       
+       private JTextField _str = new JTextField(DEFAULT_STRUCTURE1);
+       Object _hoverHighlightStr = null;
+       ArrayList<Object> _selectionHighlightStr = new ArrayList<Object>();
+       
+       private JTextField _seq = new JTextField(DEFAULT_SEQUENCE);
+       Object _hoverHighlightSeq = null;
+       ArrayList<Object> _selectionHighlightSeq = new ArrayList<Object>();
+       
+       
+       private JLabel _strLabel = new JLabel(" Str:");
+       private JLabel _seqLabel = new JLabel(" Seq:");
+       private JButton _deleteButton = new JButton("Delete");
+       private JButton _duplicateButton = new JButton("Duplicate");
+       
+       private JPanel _listPanel = new JPanel();
+       private ReorderableJList _sideList = null;
+
+
+
+       private static String errorOpt = "error";
+       @SuppressWarnings("unused")
+       private boolean _error;
+
+       private Color _backgroundColor = Color.white;
+
+       private static int _nextID = 1;
+       @SuppressWarnings("unused")
+       private int _algoCode;
+       
+       private BackupHolder _rnaList;
+
+
+       public VARNAEditor() {
+               super("VARNA Editor");
+               RNAPanelDemoInit();
+       }
+
+       private void RNAPanelDemoInit() 
+       {
+           DefaultListModel dlm = new DefaultListModel(); 
+           
+
+               int marginTools = 40;
+
+           DefaultListSelectionModel m = new DefaultListSelectionModel();
+           m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+           m.setLeadAnchorNotificationEnabled(false);
+           
+           
+               _sideList = new ReorderableJList();
+               _sideList.setModel(dlm);
+               _sideList.addMouseListener(this);
+           _sideList.setSelectionModel(m);
+           _sideList.setPreferredSize(new Dimension(100, 0));
+           _sideList.addListSelectionListener( new ListSelectionListener(){
+                       public void valueChanged(ListSelectionEvent arg0) {
+                               //System.out.println(arg0);
+                               if (!_sideList.isSelectionEmpty() && !arg0.getValueIsAdjusting())
+                               {
+                                       FullBackup  sel = (FullBackup) _sideList.getSelectedValue();
+                                       Mapping map = Mapping.DefaultOutermostMapping(_vp.getRNA().getSize(), sel.rna.getSize());
+                                       _vp.showRNAInterpolated(sel.rna,sel.config,map);
+                                       _seq.setText(sel.rna.getSeq());
+                                       _str.setText(sel.rna.getStructDBN(true));
+                               }
+                       }
+           });
+
+           _rnaList = new BackupHolder(dlm,_sideList);
+               RNA _RNA1 = new RNA("User defined 1");
+               RNA _RNA2 = new RNA("User defined 2");
+               try {
+                       _vp = new VARNAPanel("0",".");
+                       _RNA1.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE1);
+                       _RNA1.drawRNARadiate(_vp.getConfig());
+                       _RNA2.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE2);
+                       _RNA2.drawRNARadiate(_vp.getConfig());
+               } catch (ExceptionNonEqualLength e) {
+                       _vp.errorDialog(e);
+               } catch (ExceptionUnmatchedClosingParentheses e2) {
+               e2.printStackTrace();
+               } catch (ExceptionFileFormatOrSyntax e3) {
+               e3.printStackTrace();
+               }
+               _vp.setPreferredSize(new Dimension(400, 400));
+               // 
+               
+                // BH 2018 this will NOT be a clone in SwingJS
+           _rnaList.add(_vp.getConfig().clone(),_RNA2,generateDefaultName());
+           _rnaList.add(_vp.getConfig().clone(),_RNA1,generateDefaultName(),true);
+
+           JScrollPane listScroller = new JScrollPane(_sideList);
+           listScroller.setPreferredSize(new Dimension(150, 0));
+
+               setBackground(_backgroundColor);
+               _vp.setBackground(_backgroundColor);
+
+
+               Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
+
+               _seqLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _seqLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _seq.setFont(textFieldsFont);
+               _seq.setText(DEFAULT_SEQUENCE);
+               _seq.setEditable(false);
+               
+
+               _seqPanel.setLayout(new BorderLayout());
+               _seqPanel.add(_seqLabel, BorderLayout.WEST);
+               _seqPanel.add(_seq, BorderLayout.CENTER);
+
+               _strLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _strLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _str.setFont(textFieldsFont);
+               _str.setEditable(false);
+               _strPanel.setLayout(new BorderLayout());
+               _strPanel.add(_strLabel, BorderLayout.WEST);
+               _strPanel.add(_str, BorderLayout.CENTER);
+
+               _input.setLayout(new GridLayout(2, 0));
+               _input.add(_seqPanel);
+               _input.add(_strPanel);
+
+
+               _tools.setLayout(new BorderLayout());
+               _tools.add(_input, BorderLayout.CENTER);
+               _tools.add(_info, BorderLayout.SOUTH);
+
+               _deleteButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               _rnaList.removeSelected();
+                       }
+               });
+//             _duplicateButton.addActionListener(new ActionListener() {
+//                     public void actionPerformed(ActionEvent e) {
+//                                     _rnaList.add((VARNAConfig)_vp.getConfig().clone(),_vp.getRNA().clone(),_vp.getRNA().getName()+"-"+DateFormat.getTimeInstance(DateFormat.LONG).format(new Date()),true); 
+//                     }});
+               
+               JPanel ops = new JPanel();
+               ops.setLayout(new GridLayout(1,2));
+               ops.add(_deleteButton);
+               ops.add(_duplicateButton);
+
+               JLabel j = new JLabel("Structures",JLabel.CENTER);
+               _listPanel.setLayout(new BorderLayout());
+               
+               _listPanel.add(ops,BorderLayout.SOUTH);
+               _listPanel.add(j,BorderLayout.NORTH);
+               _listPanel.add(listScroller,BorderLayout.CENTER);
+
+
+               JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,_listPanel,_vp);
+               getContentPane().setLayout(new BorderLayout());
+               getContentPane().add(split, BorderLayout.CENTER);
+               getContentPane().add(_tools, BorderLayout.NORTH);
+
+               setVisible(true);
+               DropTarget dt = new DropTarget(_vp, this);
+               
+               _vp.addRNAListener(new InterfaceVARNARNAListener(){
+                       public void onSequenceModified(int index, String oldseq, String newseq) {
+                               _seq.setText(_vp.getRNA().getSeq());
+                       }
+
+                       public void onStructureModified(Set<ModeleBP> current,
+                                       Set<ModeleBP> addedBasePairs, Set<ModeleBP> removedBasePairs) {
+                               _str.setText(_vp.getRNA().getStructDBN(true));
+                       }
+
+                       public void onRNALayoutChanged(Hashtable<Integer, Double> previousPositions) {
+                       }
+                       
+               });
+               
+               _vp.addSelectionListener(new InterfaceVARNASelectionListener(){
+
+                       public void onHoverChanged(ModeleBase oldbase, ModeleBase newBase) {
+                               if (_hoverHighlightSeq!=null)
+                               {
+                                       _seq.getHighlighter().removeHighlight(_hoverHighlightSeq);
+                                       _hoverHighlightSeq = null;
+                               }
+                               if (_hoverHighlightStr!=null)
+                               {
+                                       _str.getHighlighter().removeHighlight(_hoverHighlightStr);
+                                       _hoverHighlightStr = null;
+                               }
+                               if (newBase!=null)
+                               {
+                                       try {
+                                               _hoverHighlightSeq = _seq.getHighlighter().addHighlight(newBase.getIndex(), newBase.getIndex()+1, new DefaultHighlighter.DefaultHighlightPainter(Color.green) );
+                                               _hoverHighlightStr = _str.getHighlighter().addHighlight(newBase.getIndex(), newBase.getIndex()+1, new DefaultHighlighter.DefaultHighlightPainter(Color.green) );
+                                       } catch (BadLocationException e) {
+                                               e.printStackTrace();
+                                       }
+                               }
+                       }
+
+                       public void onSelectionChanged(BaseList selection,
+                                       BaseList addedBases, BaseList removedBases) {
+                               for(Object tag: _selectionHighlightSeq)
+                               {
+                                       _seq.getHighlighter().removeHighlight(tag);
+                               }
+                               _selectionHighlightSeq.clear();
+                               for(Object tag: _selectionHighlightStr)
+                               {
+                                       _str.getHighlighter().removeHighlight(tag);
+                               }
+                               _selectionHighlightStr.clear();
+                               for (ModeleBase m: selection.getBases())
+                               {
+                                       try {
+                                               _selectionHighlightSeq.add(_seq.getHighlighter().addHighlight(m.getIndex(), m.getIndex()+1, new DefaultHighlighter.DefaultHighlightPainter(Color.orange) ));
+                                               _selectionHighlightStr.add(_str.getHighlighter().addHighlight(m.getIndex(), m.getIndex()+1, new DefaultHighlighter.DefaultHighlightPainter(Color.orange) ));
+                                       } catch (BadLocationException e) {
+                                               e.printStackTrace();
+                                       }
+                               }
+                       }
+                       
+               });
+               
+               _vp.addVARNAListener(this);
+       }
+       
+       public static String generateDefaultName()
+       {
+               return "User file #"+_nextID++;
+       }
+
+       public RNA getRNA() {
+               return (RNA)_sideList.getSelectedValue();
+       }
+
+
+
+       public String[][] getParameterInfo() {
+               String[][] info = {
+                               // Parameter Name Kind of Value Description,
+                               { "sequenceDBN", "String", "A raw RNA sequence" },
+                               { "structureDBN", "String",
+                                               "An RNA structure in dot bracket notation (DBN)" },
+                               { errorOpt, "boolean", "To show errors" }, };
+               return info;
+       }
+
+       public void init() {
+               _vp.setBackground(_backgroundColor);
+               _error = true;
+       }
+
+       @SuppressWarnings("unused")
+       private Color getSafeColor(String col, Color def) {
+               Color result;
+               try {
+                       result = Color.decode(col);
+               } catch (Exception e) {
+                       try {
+                               result = Color.getColor(col, def);
+                       } catch (Exception e2) {
+                               return def;
+                       }
+               }
+               return result;
+       }
+
+       public VARNAPanel get_varnaPanel() {
+               return _vp;
+       }
+
+       public void set_varnaPanel(VARNAPanel surface) {
+               _vp = surface;
+       }
+
+
+       public JTextField get_seq() {
+               return _seq;
+       }
+
+       public void set_seq(JTextField _seq) {
+               this._seq = _seq;
+       }
+
+       public JLabel get_info() {
+               return _info;
+       }
+
+       public void set_info(JLabel _info) {
+               this._info = _info;
+       }
+
+       public static void main(String[] args) {
+               VARNAEditor d = new VARNAEditor();
+               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               d.pack();
+               d.setVisible(true);
+       }
+       
+
+       public void dragEnter(DropTargetDragEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragExit(DropTargetEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragOver(DropTargetDragEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void drop(DropTargetDropEvent dtde) {
+           try {
+               Transferable tr = dtde.getTransferable();
+               DataFlavor[] flavors = tr.getTransferDataFlavors();
+               for (int i = 0; i < flavors.length; i++) {
+           if (flavors[i].isFlavorJavaFileListType()) {
+             dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
+             Object ob = tr.getTransferData(flavors[i]);
+             if (ob instanceof List)
+             {
+                 List list = (List) ob;
+                 for (int j = 0; j < list.size(); j++) {
+                 Object o = list.get(j);
+                 
+                 if (dtde.getSource() instanceof DropTarget)
+                 {
+                         DropTarget dt = (DropTarget) dtde.getSource();
+                         Component c = dt.getComponent();
+                         if (c instanceof VARNAPanel)
+                         {
+                                         String path = o.toString();
+                                 VARNAPanel vp = (VARNAPanel) c;
+                                         try{
+                                 FullBackup bck =  VARNAPanel.importSession((File) o); // BH SwingJS
+                                 _rnaList.add(bck.config, bck.rna,bck.name,true);
+                                         }
+                                         catch (ExceptionLoadingFailed e3)
+                                         {
+                                                 Collection<RNA> rnas = RNAFactory.loadSecStr((File) o); // BH SwingJS 
+                                                 if (rnas.isEmpty())
+                                                 {
+                                                         throw new ExceptionFileFormatOrSyntax("No RNA could be parsed from that source.");
+                                                 }
+                                                 
+                                                 int id = 1;
+                                                 for(RNA r: rnas)
+                                                 {
+                                                         r.drawRNA(vp.getConfig());
+                                                         String name = r.getName();
+                                                         if (name.equals(""))
+                                                         { 
+                                                                 name = path.substring(path.lastIndexOf(File.separatorChar)+1);
+                                                         }
+                                                         if (rnas.size()>1)
+                                                         {
+                                                                 name += " - Molecule# "+id++;
+                                                         }
+                                                         _rnaList.add(vp.getConfig().clone(),r,name,true);
+                                                 }
+                                         }                                       
+                         }
+                 }
+                 }
+             }
+             // If we made it this far, everything worked.
+             dtde.dropComplete(true);
+             return;
+           }
+               }
+               // Hmm, the user must not have dropped a file list
+               dtde.rejectDrop();
+             } catch (Exception e) {
+               e.printStackTrace();
+               dtde.rejectDrop();
+             }
+               
+       }
+
+       public void dropActionChanged(DropTargetDragEvent arg0) {
+       }
+
+       private class BackupHolder{
+               private DefaultListModel _rnaList;
+               private ArrayList<RNA> _rnas = new ArrayList<RNA>();
+               JList _l;
+               
+               public BackupHolder(DefaultListModel rnaList, JList l)
+               {
+                       _rnaList = rnaList;
+                       _l = l;
+               }
+               
+               public void add(VARNAConfig c, RNA r)
+               {
+                       add(c, r, r.getName(),false);
+               }
+
+               public void add(VARNAConfig c, RNA r,boolean select)
+               {
+                       add(c, r, r.getName(),select);
+               }
+
+               public void add(VARNAConfig c, RNA r, String name)
+               {
+                       add(c, r, name,false);                  
+               }
+               public void add(VARNAConfig c, RNA r, String name, boolean select)
+               {
+                       if (select){
+                               _l.removeSelectionInterval(0, _rnaList.size());
+                       }
+                       if (name.equals(""))
+                       {
+                               name = generateDefaultName();
+                       }
+                       FullBackup bck = new FullBackup(c,r,name);
+                       _rnas.add(0, r);
+                       _rnaList.add(0,bck);
+                       if (select){
+                         _l.setSelectedIndex(0);
+                       }
+               }
+
+               public void remove(int i)
+               {
+                       _rnas.remove(i);
+                       _rnaList.remove(i);
+                       
+               }
+               public DefaultListModel getModel()
+               {
+                       return _rnaList;
+               }
+               public boolean contains(RNA r)
+               {
+                       return _rnas.contains(r);
+               }
+               /*public int getSize()
+               {
+                       return _rnaList.getSize();
+               }*/
+               public FullBackup getElementAt(int i)
+               {
+                       return (FullBackup) _rnaList.getElementAt(i);
+               }
+               
+               public void removeSelected()
+               {
+                       int i = _l.getSelectedIndex();
+                       if (i!=-1)
+                       {
+                         if (_rnaList.getSize()==1)
+                         {
+                                 RNA r = new RNA();
+                                 try {
+                                       r.setRNA(" ", ".");
+                                 } catch (ExceptionUnmatchedClosingParentheses e1) {
+                                 } catch (ExceptionFileFormatOrSyntax e1) {
+                                 }
+                                 _vp.showRNA(r);
+                                 _vp.repaint();
+                         }
+                         else
+                         {  
+                                int newi = i+1;
+                                if (newi==_rnaList.getSize())
+                                {
+                                        newi = _rnaList.getSize()-2;
+                                }
+                                FullBackup bck = (FullBackup) _rnaList.getElementAt(newi);
+                                _l.setSelectedValue(bck,true);
+                         }
+                         _rnaList.remove(i);
+                       }
+
+               }
+       }
+
+       public void onStructureRedrawn() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onUINewStructure(VARNAConfig v, RNA r) {
+               _rnaList.add(v, r,"",true);
+       }
+
+       public void onWarningEmitted(String s) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseClicked(MouseEvent e) {
+                          if(e.getClickCount() == 2){
+                            int index = _sideList.locationToIndex(e.getPoint());
+                            ListModel dlm = _sideList.getModel();
+                            FullBackup item = (FullBackup) dlm.getElementAt(index);;
+                            _sideList.ensureIndexIsVisible(index);
+                            Object newName = JOptionPane.showInputDialog(
+                                           this,
+                                           "Specify a new name for this RNA",
+                                           "Rename RNA", 
+                                           JOptionPane.QUESTION_MESSAGE,
+                                           (Icon)null,
+                                           null,
+                                           item.toString());
+                            if (newName!=null)
+                            {
+                                item.name = newName.toString();
+                                this._sideList.repaint();
+                            }
+                            }
+       }
+
+       public void mouseEntered(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseExited(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mousePressed(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseReleased(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onZoomLevelChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onTranslationChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/VARNAGUI.java b/src2/fr/orsay/lri/varna/applications/VARNAGUI.java
new file mode 100644 (file)
index 0000000..e62503f
--- /dev/null
@@ -0,0 +1,791 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.AdjustmentEvent;
+import java.awt.event.AdjustmentListener;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.geom.Point2D.Double;
+import java.io.File;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Set;
+
+import javax.swing.DefaultListModel;
+import javax.swing.DefaultListSelectionModel;
+import javax.swing.Icon;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollBar;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTextField;
+import javax.swing.ListModel;
+import javax.swing.ListSelectionModel;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.DefaultHighlighter;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.ReorderableJList;
+import fr.orsay.lri.varna.components.ZoomWindow;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNARNAListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNASelectionListener;
+import fr.orsay.lri.varna.models.BaseList;
+import fr.orsay.lri.varna.models.FullBackup;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VARNAGUI extends JFrame implements DropTargetListener, InterfaceVARNAListener, MouseListener, AdjustmentListener {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+       private static final String DEFAULT_SEQUENCE = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
+
+       private static final String DEFAULT_STRUCTURE1 = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
+       private static final String DEFAULT_STRUCTURE2 = "..(((((...(((((...(((((........(((((...(((((.....)))))...)))))..................))))).....)))))...)))))..";
+       // private static final String DEFAULT_STRUCTURE1 = "((((....))))";
+       // private static final String DEFAULT_STRUCTURE2 =
+       // "((((..(((....)))..))))";
+
+       private VARNAPanel _vp;
+
+       private JPanel _tools = new JPanel();
+       private JPanel _input = new JPanel();
+
+       private JPanel _seqPanel = new JPanel();
+       private JPanel _strPanel = new JPanel();
+       private JLabel _info = new JLabel();
+       
+       private JTextField _str = new JTextField(DEFAULT_STRUCTURE1);
+       Object _hoverHighlightStr = null;
+       ArrayList<Object> _selectionHighlightStr = new ArrayList<Object>();
+       
+       private JTextField _seq = new JTextField(DEFAULT_SEQUENCE);
+       Object _hoverHighlightSeq = null;
+       ArrayList<Object> _selectionHighlightSeq = new ArrayList<Object>();
+       
+       
+       private ZoomWindow _zoomWindow;
+       private JLabel _strLabel = new JLabel(" Str:");
+       private JLabel _seqLabel = new JLabel(" Seq:");
+       private JButton _createButton = new JButton("Create");
+       private JButton _deleteButton = new JButton("Delete");
+       private JButton _duplicateButton = new JButton("Snapshot");
+       
+       private JPanel _listPanel = new JPanel();
+       private ReorderableJList _sideList = null;
+
+
+       private static String errorOpt = "error";
+       @SuppressWarnings("unused")
+       private boolean _error;
+
+       private Color _backgroundColor = Color.white;
+       
+       private JScrollBar _vert = new JScrollBar(JScrollBar.VERTICAL);
+       private JScrollBar _horiz = new JScrollBar(JScrollBar.HORIZONTAL);
+
+       private static int _nextID = 1;
+       @SuppressWarnings("unused")
+       private int _algoCode;
+       
+       private BackupHolder _rnaList;
+
+
+       public VARNAGUI() {
+               super("VARNA GUI");
+               RNAPanelDemoInit();
+       }
+
+       private void RNAPanelDemoInit() 
+       {
+           DefaultListModel dlm = new DefaultListModel(); 
+           
+
+               int marginTools = 40;
+
+           DefaultListSelectionModel m = new DefaultListSelectionModel();
+           m.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+           m.setLeadAnchorNotificationEnabled(false);
+           
+           
+               _sideList = new ReorderableJList();
+               _sideList.setModel(dlm);
+               _sideList.addMouseListener(this);
+           _sideList.setSelectionModel(m);
+           _sideList.setPreferredSize(null);
+           
+           _sideList.addListSelectionListener( new ListSelectionListener(){
+                       public void valueChanged(ListSelectionEvent arg0) {
+                               //System.out.println(arg0);
+                               if (!_sideList.isSelectionEmpty() && !arg0.getValueIsAdjusting())
+                               {
+                                       FullBackup  sel = (FullBackup) _sideList.getSelectedValue();
+                                       _vp.setConfig(sel.config);
+                                       showRNA(sel.rna);
+                                       _seq.setText(sel.rna.getSeq());
+                                       _str.setText(sel.rna.getStructDBN(true));
+                               }
+                       }
+           });
+
+           _rnaList = new BackupHolder(dlm,_sideList);
+               RNA _RNA1 = new RNA("User defined 1");
+               RNA _RNA2 = new RNA("User defined 2");
+               try {
+                       _vp = new VARNAPanel("0",".");
+                       _zoomWindow = new ZoomWindow(_vp);
+                       _RNA1.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE1);
+                       _RNA1.drawRNARadiate(_vp.getConfig());
+                       _RNA2.setRNA(DEFAULT_SEQUENCE, DEFAULT_STRUCTURE2);
+                       _RNA2.drawRNARadiate(_vp.getConfig());
+               } catch (ExceptionNonEqualLength e) {
+                       _vp.errorDialog(e);
+               } catch (ExceptionUnmatchedClosingParentheses e2) {
+               e2.printStackTrace();
+               } catch (ExceptionFileFormatOrSyntax e3) {
+               e3.printStackTrace();
+               }
+               _vp.setPreferredSize(new Dimension(400, 400));
+           _rnaList.add(_vp.getConfig().clone(),_RNA2,generateDefaultName());
+           _rnaList.add(_vp.getConfig().clone(),_RNA1,generateDefaultName(),true);
+           
+
+           JScrollPane listScroller = new JScrollPane(_sideList);//,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
+           listScroller.setPreferredSize(new Dimension(150, 0));
+
+               setBackground(_backgroundColor);
+               _vp.setBackground(_backgroundColor);
+
+
+               Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
+
+               _seqLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _seqLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _seq.setFont(textFieldsFont);
+               _seq.setText(DEFAULT_SEQUENCE);
+
+               _createButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               try {
+                               RNA nRNA = new RNA(generateDefaultName());
+                               nRNA.setRNA(_seq.getText(), _str.getText());
+                               nRNA.drawRNARadiate(_vp.getConfig());
+                               _rnaList.add(new VARNAConfig(),nRNA,true);
+                               } catch (ExceptionUnmatchedClosingParentheses e1) {
+                                       JOptionPane.showMessageDialog(_vp, e1.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
+                               } catch (ExceptionFileFormatOrSyntax e1) {
+                                       JOptionPane.showMessageDialog(_vp, e1.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
+                               }
+                       }
+               });
+
+
+               _seqPanel.setLayout(new BorderLayout());
+               _seqPanel.add(_seqLabel, BorderLayout.WEST);
+               _seqPanel.add(_seq, BorderLayout.CENTER);
+
+               _strLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _strLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _str.setFont(textFieldsFont);
+               _strPanel.setLayout(new BorderLayout());
+               _strPanel.add(_strLabel, BorderLayout.WEST);
+               _strPanel.add(_str, BorderLayout.CENTER);
+
+               _input.setLayout(new GridLayout(2, 0));
+               _input.add(_seqPanel);
+               _input.add(_strPanel);
+
+               JPanel goPanel = new JPanel();
+               goPanel.setLayout(new BorderLayout());
+
+               _tools.setLayout(new BorderLayout());
+               _tools.add(_input, BorderLayout.CENTER);
+               _tools.add(_info, BorderLayout.SOUTH);
+               _tools.add(goPanel, BorderLayout.EAST);
+
+               _deleteButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               _rnaList.removeSelected();
+                       }
+               });
+               // BH 2018 SwingJS can't clone, as it does not implement serialization 
+               if (/** @j2sNative false && */ true)
+                 _duplicateButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                                       _rnaList.add((VARNAConfig)_vp.getConfig().clone(),_vp.getRNA().clone(),_vp.getRNA().getName()+"-"+DateFormat.getTimeInstance(DateFormat.LONG).format(new Date()),true); 
+                       }});
+               
+               JPanel ops = new JPanel();
+               ops.setLayout(new GridLayout(1,2));
+               ops.add(_deleteButton);
+                if (/** @j2sNative false && */ true)
+                  ops.add(_duplicateButton);
+               
+               JPanel opspanel = new JPanel(new BorderLayout());
+               opspanel.add(ops,BorderLayout.NORTH);
+               opspanel.add(_zoomWindow,BorderLayout.SOUTH);
+               
+               _zoomWindow.setPreferredSize(new Dimension(-1,200));
+               
+
+               JLabel j = new JLabel("Structure Manager",JLabel.CENTER);
+               _listPanel.setLayout(new BorderLayout());
+               
+               _listPanel.add(opspanel,BorderLayout.SOUTH);
+               _listPanel.add(j,BorderLayout.NORTH);
+               _listPanel.add(listScroller,BorderLayout.CENTER);
+
+               goPanel.add(_createButton, BorderLayout.CENTER);
+
+               JPanel vpScroll = new JPanel();
+               vpScroll.setLayout(new BorderLayout());
+               _horiz.setVisible(false);
+               _horiz.addAdjustmentListener(this);
+               _vert.setVisible(false);
+               _vert.addAdjustmentListener(this);
+               vpScroll.add(_horiz,BorderLayout.SOUTH);
+               vpScroll.add(_vert,BorderLayout.EAST);
+               vpScroll.add(_vp,BorderLayout.CENTER);
+               JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,_listPanel,vpScroll);
+               getContentPane().setLayout(new BorderLayout());
+               getContentPane().add(split, BorderLayout.CENTER);
+               getContentPane().add(_tools, BorderLayout.NORTH);
+               
+
+               setVisible(true);
+               DropTarget dt = new DropTarget(_vp, this);
+               
+               _vp.addRNAListener(new InterfaceVARNARNAListener(){
+                       public void onSequenceModified(int index, String oldseq, String newseq) {
+                               //System.out.println("Sequence changed: Index:"+index+" ["+oldseq+"]=>["+newseq+"]");
+                       }
+
+                       public void onStructureModified(Set<ModeleBP> current,
+                                       Set<ModeleBP> addedBasePairs, Set<ModeleBP> removedBasePairs) {
+                               String result = "";
+                               //System.out.println("Structure changed: ");
+                               for (ModeleBP s:addedBasePairs)
+                               {  result +=s;  }
+                               //System.out.println("     Added: "+result);
+                               result = "";
+                               for (ModeleBP s:removedBasePairs)
+                               {  result +=s;  }
+                               //System.out.println("   Removed: "+result);
+                       }
+
+                       public void onRNALayoutChanged(Hashtable<Integer, Double> previousPositions) {
+                               //System.out.print("Layout changed, bases#: ");
+                               String result = "";
+                               for (Integer s:previousPositions.keySet())
+                               {  result +=s+" ";  }                           
+                               //System.out.println(result);
+                       }
+                       
+               });
+               
+               _vp.addSelectionListener(new InterfaceVARNASelectionListener(){
+
+                       public void onHoverChanged(ModeleBase oldbase, ModeleBase newBase) {
+                               if (_hoverHighlightSeq!=null)
+                               {
+                                       _seq.getHighlighter().removeHighlight(_hoverHighlightSeq);
+                                       _hoverHighlightSeq = null;
+                               }
+                               if (_hoverHighlightStr!=null)
+                               {
+                                       _str.getHighlighter().removeHighlight(_hoverHighlightStr);
+                                       _hoverHighlightStr = null;
+                               }
+                               if (newBase!=null)
+                               {
+                                       try {
+                                               int i = newBase.getIndex();
+                                               int[] shifts = _vp.getRNA().getStrandShifts();
+                                               _hoverHighlightSeq = _seq.getHighlighter().addHighlight(i+shifts[i], i+shifts[i]+1, new DefaultHighlighter.DefaultHighlightPainter(Color.green) );
+                                               _hoverHighlightStr = _str.getHighlighter().addHighlight(i+shifts[i], i+shifts[i]+1, new DefaultHighlighter.DefaultHighlightPainter(Color.green) );
+                                       } catch (BadLocationException e) {
+                                               e.printStackTrace();
+                                       }
+                               }
+                       }
+
+                       public void onSelectionChanged(BaseList selection,
+                                       BaseList addedBases, BaseList removedBases) {
+                               for(Object tag: _selectionHighlightSeq)
+                               {
+                                       _seq.getHighlighter().removeHighlight(tag);
+                               }
+                               _selectionHighlightSeq.clear();
+                               for(Object tag: _selectionHighlightStr)
+                               {
+                                       _str.getHighlighter().removeHighlight(tag);
+                               }
+                               _selectionHighlightStr.clear();
+                               int[] shifts = _vp.getRNA().getStrandShifts();
+                               for (ModeleBase m: selection.getBases())
+                               {
+                                       try {
+                                               int i = m.getIndex();
+                                               _selectionHighlightSeq.add(_seq.getHighlighter().addHighlight(i+shifts[i], i+shifts[i]+1, new DefaultHighlighter.DefaultHighlightPainter(Color.orange) ));
+                                               _selectionHighlightStr.add(_str.getHighlighter().addHighlight(i+shifts[i], i+shifts[i]+1, new DefaultHighlighter.DefaultHighlightPainter(Color.orange) ));
+                                       } catch (BadLocationException e) {
+                                               e.printStackTrace();
+                                       }
+                               }
+                       }
+                       
+               });
+               
+               _vp.addVARNAListener(this);
+               
+               new Thread(_zoomWindow).start();   
+       }
+       
+       protected void showRNA(RNA rna) {
+               _vp.showRNAInterpolated(rna);
+               _zoomWindow.repaint();
+       }
+
+
+       public void addRNA(RNA r, VARNAConfig cfg)
+       {
+               _rnaList.add(cfg,r); 
+       }
+       
+       public static String generateDefaultName()
+       {
+               return "User file #"+_nextID++;
+       }
+
+       public RNA getRNA() {
+               return (RNA)_sideList.getSelectedValue();
+       }
+
+
+
+       public String[][] getParameterInfo() {
+               String[][] info = {
+                               // Parameter Name Kind of Value Description,
+                               { "sequenceDBN", "String", "A raw RNA sequence" },
+                               { "structureDBN", "String",
+                                               "An RNA structure in dot bracket notation (DBN)" },
+                               { errorOpt, "boolean", "To show errors" }, };
+               return info;
+       }
+
+       public void init() {
+               _vp.setBackground(_backgroundColor);
+               _error = true;
+       }
+
+       @SuppressWarnings("unused")
+       private Color getSafeColor(String col, Color def) {
+               Color result;
+               try {
+                       result = Color.decode(col);
+               } catch (Exception e) {
+                       try {
+                               result = Color.getColor(col, def);
+                       } catch (Exception e2) {
+                               return def;
+                       }
+               }
+               return result;
+       }
+
+       public VARNAPanel get_varnaPanel() {
+               return _vp;
+       }
+
+       public void set_varnaPanel(VARNAPanel surface) {
+               _vp = surface;
+       }
+
+
+       public JTextField get_seq() {
+               return _seq;
+       }
+
+       public void set_seq(JTextField _seq) {
+               this._seq = _seq;
+       }
+
+       public JLabel get_info() {
+               return _info;
+       }
+
+       public void set_info(JLabel _info) {
+               this._info = _info;
+       }
+
+       public static void main(String[] args) {
+               List<Image> icons = new ArrayList<Image>();
+               //JOptionPane.showMessageDialog(null, ""+Toolkit.getDefaultToolkit().getImage("./VARNA16x16.png"), "Check", JOptionPane.INFORMATION_MESSAGE);
+               icons.add(Toolkit.getDefaultToolkit().getImage("./VARNA16x16.png"));
+               icons.add(Toolkit.getDefaultToolkit().getImage("./VARNA32x32.png"));
+               icons.add(Toolkit.getDefaultToolkit().getImage("./VARNA64x64.png"));
+               VARNAGUI d = new VARNAGUI();
+               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               d.pack();
+               d.setIconImages(icons);
+               d.setVisible(true);
+       }
+       
+
+       public void dragEnter(DropTargetDragEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragExit(DropTargetEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragOver(DropTargetDragEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void drop(DropTargetDropEvent dtde) {
+           try {
+               Transferable tr = dtde.getTransferable();
+               DataFlavor[] flavors = tr.getTransferDataFlavors();
+               for (int i = 0; i < flavors.length; i++) {
+           if (flavors[i].isFlavorJavaFileListType()) {
+             dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
+             Object ob = tr.getTransferData(flavors[i]);
+             if (ob instanceof List)
+             {
+                 List list = (List) ob;
+                 for (int j = 0; j < list.size(); j++) {
+                 Object o = list.get(j);
+                 
+                 if (dtde.getSource() instanceof DropTarget)
+                 {
+                         DropTarget dt = (DropTarget) dtde.getSource();
+                         Component c = dt.getComponent();
+                         if (c instanceof VARNAPanel)
+                         {
+                                         String path = o.toString();
+                                 VARNAPanel vp = (VARNAPanel) c;
+                                         try{
+                                 FullBackup bck =  VARNAPanel.importSession((File) o);  // BH SwingJS
+                                 _rnaList.add(bck.config, bck.rna,bck.name,true);
+                                         }
+                                         catch (ExceptionLoadingFailed e3)
+                                         {
+                                                 ArrayList<RNA> rnas = RNAFactory.loadSecStr((File) o); // BH SwingJS
+                                                 if (rnas.isEmpty())
+                                                 {
+                                                         throw new ExceptionFileFormatOrSyntax("No RNA could be parsed from that source.");
+                                                 }
+                                                 
+                                             dtde.dropComplete(true);
+                                                 _vp.getVARNAUI().UIChooseRNAs(rnas);
+                                             return;
+                                                 /*
+                                                 for(RNA r: rnas)
+                                                 {
+                                                         r.drawRNA(vp.getConfig());
+                                                         String name = r.getName();
+                                                         if (name.equals(""))
+                                                         { 
+                                                                 name = path.substring(path.lastIndexOf(File.separatorChar)+1);
+                                                         }
+                                                         if (rnas.size()>1)
+                                                         {
+                                                                 name += " - Molecule# "+id++;
+                                                         }
+                                                         _rnaList.add(vp.getConfig().clone(),r,name,true);
+                                                 }*/
+                                         }                                       
+                         }
+                 }
+                 }
+             }
+             // If we made it this far, everything worked.
+             dtde.dropComplete(true);
+             return;
+           }
+               }
+               // Hmm, the user must not have dropped a file list
+               dtde.rejectDrop();
+             } catch (Exception e) {
+               e.printStackTrace();
+               dtde.rejectDrop();
+             }
+               
+       }
+
+       public void dropActionChanged(DropTargetDragEvent arg0) {
+       }
+
+       private class BackupHolder{
+               private DefaultListModel _rnaList;
+               private ArrayList<RNA> _rnas = new ArrayList<RNA>();
+               JList _l;
+               
+               public BackupHolder(DefaultListModel rnaList, JList l)
+               {
+                       _rnaList = rnaList;
+                       _l = l;
+               }
+               
+               public void add(VARNAConfig c, RNA r)
+               {
+                       add(c, r, r.getName(),false);
+               }
+
+               public void add(VARNAConfig c, RNA r,boolean select)
+               {
+                       add(c, r, r.getName(),select);
+               }
+
+               public void add(VARNAConfig c, RNA r, String name)
+               {
+                       add(c, r, name,false);                  
+               }
+               public void add(VARNAConfig c, RNA r, String name, boolean select)
+               {
+                       if (!_rnas.contains(r))
+                       {
+                       if (select){
+                               _l.removeSelectionInterval(0, _rnaList.size());
+                       }
+                       if (name.equals(""))
+                       {
+                               name = generateDefaultName();
+                       }
+                       FullBackup bck = new FullBackup(c,r,name);
+                       _rnas.add(0, r);
+                       _rnaList.add(0,bck);
+                       _l.doLayout();
+                       if (select){
+                         _l.setSelectedIndex(0);
+                       }
+                       }
+               }
+
+               public void remove(int i)
+               {
+                       _rnas.remove(i);
+                       _rnaList.remove(i);
+                       
+               }
+               public DefaultListModel getModel()
+               {
+                       return _rnaList;
+               }
+               public boolean contains(RNA r)
+               {
+                       return _rnas.contains(r);
+               }
+               /*public int getSize()
+               {
+                       return _rnaList.getSize();
+               }*/
+               public FullBackup getElementAt(int i)
+               {
+                       return (FullBackup) _rnaList.getElementAt(i);
+               }
+               
+               public void removeSelected()
+               {
+                       int i = _l.getSelectedIndex();
+                       if (i!=-1)
+                       {
+                         if (_rnaList.getSize()==1)
+                         {
+                                 RNA r = new RNA();
+                                 try {
+                                       r.setRNA(" ", ".");
+                                 } catch (ExceptionUnmatchedClosingParentheses e1) {
+                                 } catch (ExceptionFileFormatOrSyntax e1) {
+                                 }
+                                 showRNA(r);
+                         }
+                         else
+                         {  
+                                int newi = i+1;
+                                if (newi==_rnaList.getSize())
+                                {
+                                        newi = _rnaList.getSize()-2;
+                                }
+                                FullBackup bck = (FullBackup) _rnaList.getElementAt(newi);
+                                _l.setSelectedValue(bck,true);
+                         }
+                         _rnaList.remove(i);
+                       }
+
+               }
+       }
+
+       public void onStructureRedrawn() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onUINewStructure(VARNAConfig v, RNA r) {
+               _rnaList.add(v, r,r.getName(),true);
+               onZoomLevelChanged();
+       }
+
+       public void onWarningEmitted(String s) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseClicked(MouseEvent e) {
+                          if(e.getClickCount() == 2){
+                            int index = _sideList.locationToIndex(e.getPoint());
+                            ListModel dlm = _sideList.getModel();
+                            FullBackup item = (FullBackup) dlm.getElementAt(index);;
+                            _sideList.ensureIndexIsVisible(index);
+                            Object newName = JOptionPane.showInputDialog(
+                                           this,
+                                           "Specify a new name for this RNA",
+                                           "Rename RNA", 
+                                           JOptionPane.QUESTION_MESSAGE,
+                                           (Icon)null,
+                                           null,
+                                           item.toString());
+                            if (newName!=null)
+                            {
+                                item.name = newName.toString();
+                                this._sideList.repaint();
+                            }
+                            }
+       }
+
+       public void mouseEntered(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseExited(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mousePressed(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseReleased(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onZoomLevelChanged() {
+               if (_vp.getZoom()>1.02)
+               {
+                 Rectangle r = _vp.getZoomedInTranslationBox();
+                 _horiz.setMinimum(r.x);
+                 _horiz.setMaximum(r.x+r.width+_vp.getWidth());
+                 _horiz.getModel().setExtent(_vp.getWidth());
+                 _horiz.getModel().setValue(_vp.getTranslation().x);             
+                 _horiz.doLayout();
+                 _horiz.setVisible(true);
+                 
+                 _vert.setMinimum(r.y);
+                 _vert.setMaximum(r.y+r.height+_vp.getHeight());
+                 _vert.getModel().setExtent(_vp.getHeight());
+                 _vert.getModel().setValue(_vp.getTranslation().y);              
+                 _vert.doLayout();
+                 _vert.setVisible(true);
+               }
+               else
+               {
+                 _horiz.setVisible(false);
+                 _vert.setVisible(false);
+               }
+       }
+
+       public void onTranslationChanged() {
+               if (_vp.getZoom()>1.02)
+               {
+                       int nx = _horiz.getMaximum()-(_vp.getTranslation().x-_horiz.getMinimum())-_vp.getWidth();
+                       int ny = _vert.getMaximum()-(_vp.getTranslation().y-_vert.getMinimum())-_vp.getHeight();
+                       _horiz.getModel().setValue(nx);
+                       _horiz.doLayout();
+                       _vert.getModel().setValue(ny);
+                       _vert.doLayout();
+               }
+       }
+
+       public void adjustmentValueChanged(AdjustmentEvent arg0) {
+               if (arg0.getSource()==_horiz)
+               {
+                       _vp.setTranslation(new Point(_horiz.getMaximum()-(arg0.getValue()-_horiz.getMinimum())-_vp.getWidth(),_vp.getTranslation().y));
+                       _vp.repaint();
+               }
+               else if (arg0.getSource()==_vert)
+               {
+                       _vp.setTranslation(new Point(_vp.getTranslation().x,_vert.getMaximum()-(arg0.getValue()-_vert.getMinimum())-_vp.getHeight()));
+                       _vp.repaint();
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/VARNAOnlineDemo.java b/src2/fr/orsay/lri/varna/applications/VARNAOnlineDemo.java
new file mode 100644 (file)
index 0000000..2d02ce7
--- /dev/null
@@ -0,0 +1,255 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications;
+
+/*
+ VARNA is a Java library for quick automated drawings RNA secondary structure 
+ Copyright (C) 2007  Yann Ponty
+
+ This program 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 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program.  If not, see <http://www.gnu.org/licenses/>. 
+ */
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridLayout;
+
+import javax.swing.JApplet;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurDemoTextField;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+/**
+ * An RNA 2d Panel demo applet
+ * 
+ * @author Yann Ponty & Darty Kévin
+ * 
+ */
+
+public class VARNAOnlineDemo extends JApplet {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+       private static final String DEFAULT_SEQUENCE = "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
+
+       private static final String DEFAULT_STRUCTURE = "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
+
+       private VARNAPanel _vp;
+
+       private JPanel _tools = new JPanel();
+       private JPanel _input = new JPanel();
+
+       private JPanel _seqPanel = new JPanel();
+       private JPanel _structPanel = new JPanel();
+       private JLabel _info = new JLabel();
+       private JTextField _struct = new JTextField();
+       private JTextField _seq = new JTextField();
+       private JLabel _structLabel = new JLabel(" Str:");
+       private JLabel _seqLabel = new JLabel(" Seq:");
+
+       private static String errorOpt = "error";
+       private boolean _error;
+
+       private Color _backgroundColor = Color.white;
+
+       private int _algoCode;
+
+       public VARNAOnlineDemo() {
+               super();
+               try {
+                       _vp = new VARNAPanel(_seq.getText(), _struct.getText());
+                       _vp.setErrorsOn(false);
+               } catch (ExceptionNonEqualLength e) {
+                       _vp.errorDialog(e);
+               }
+               RNAPanelDemoInit();
+       }
+
+       private void RNAPanelDemoInit() {
+               int marginTools = 40;
+
+               setBackground(_backgroundColor);
+               _vp.setBackground(_backgroundColor);
+
+               try {
+                       _vp.getRNA().setRNA(_seq.getText(), _struct.getText());
+                       _vp.setErrorsOn(false);
+               } catch (Exception e1) {
+                       _vp.errorDialog(e1);
+               }
+
+               Font textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
+
+               _seqLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _seqLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _seq.setFont(textFieldsFont);
+               _seq.setText(_vp.getRNA().getSeq());
+
+               _seqPanel.setLayout(new BorderLayout());
+               _seqPanel.add(_seqLabel, BorderLayout.WEST);
+               _seqPanel.add(_seq, BorderLayout.CENTER);
+
+               _structLabel.setPreferredSize(new Dimension(marginTools, 15));
+               _structLabel.setHorizontalTextPosition(JLabel.LEFT);
+               _struct.setFont(textFieldsFont);
+               _struct.setText(_vp.getRNA().getStructDBN());
+               _structPanel.setLayout(new BorderLayout());
+               _structPanel.add(_structLabel, BorderLayout.WEST);
+               _structPanel.add(_struct, BorderLayout.CENTER);
+
+               ControleurDemoTextField controleurTextField = new ControleurDemoTextField(this);
+               _seq.addCaretListener(controleurTextField);
+               _struct.addCaretListener(controleurTextField);
+
+               _input.setLayout(new GridLayout(3, 0));
+               _input.add(_seqPanel);
+               _input.add(_structPanel);
+
+               _tools.setLayout(new BorderLayout());
+               _tools.add(_input, BorderLayout.CENTER);
+               _tools.add(_info, BorderLayout.SOUTH);
+
+               getContentPane().setLayout(new BorderLayout());
+               getContentPane().add(_vp, BorderLayout.CENTER);
+               getContentPane().add(_tools, BorderLayout.SOUTH);
+
+               setVisible(true);
+               _vp.getVARNAUI().UIRadiate();
+       }
+
+       public String[][] getParameterInfo() {
+               String[][] info = {
+                               // Parameter Name Kind of Value Description,
+                               { "sequenceDBN", "String", "A raw RNA sequence" },
+                               { "structureDBN", "String",
+                                               "An RNA structure in dot bracket notation (DBN)" },
+                               { errorOpt, "boolean", "To show errors" }, };
+               return info;
+       }
+
+       public void init() {
+               retrieveParametersValues();
+               _vp.setBackground(_backgroundColor);
+               _error = true;
+       }
+
+       private Color getSafeColor(String col, Color def) {
+               Color result;
+               try {
+                       result = Color.decode(col);
+               } catch (Exception e) {
+                       try {
+                               result = Color.getColor(col, def);
+                       } catch (Exception e2) {
+                               return def;
+                       }
+               }
+               return result;
+       }
+
+       private String getParameterValue(String key, String def) {
+               String tmp;
+               tmp = getParameter(key);
+               if (tmp == null) {
+                       return def;
+               } else {
+                       return tmp;
+               }
+       }
+
+       private void retrieveParametersValues() {
+               _error = Boolean.parseBoolean(getParameterValue(errorOpt, "false"));
+               _vp.setErrorsOn(_error);
+               _backgroundColor = getSafeColor(getParameterValue("background",
+                               _backgroundColor.toString()), _backgroundColor);
+               _vp.setBackground(_backgroundColor);
+               _seq.setText(getParameterValue("sequenceDBN", ""));
+               _struct.setText(getParameterValue("structureDBN", ""));
+               String _algo = getParameterValue("algorithm", "radiate");
+               if (_algo.equals("circular"))
+                       _algoCode = RNA.DRAW_MODE_CIRCULAR;
+               else if (_algo.equals("naview"))
+                       _algoCode = RNA.DRAW_MODE_NAVIEW;
+               else if (_algo.equals("line"))
+                       _algoCode = RNA.DRAW_MODE_LINEAR;
+               else
+                       _algoCode = RNA.DRAW_MODE_RADIATE;
+               if (_seq.getText().equals("") && _struct.getText().equals("")) {
+                       _seq.setText(DEFAULT_SEQUENCE);
+                       _struct.setText(DEFAULT_STRUCTURE);
+               }
+               try {
+                       _vp.drawRNA(_seq.getText(), _struct.getText(), _algoCode);
+               } catch (ExceptionNonEqualLength e) {
+                       e.printStackTrace();
+               }
+
+       }
+
+       public VARNAPanel get_varnaPanel() {
+               return _vp;
+       }
+
+       public void set_varnaPanel(VARNAPanel surface) {
+               _vp = surface;
+       }
+
+       public JTextField get_struct() {
+               return _struct;
+       }
+
+       public void set_struct(JTextField _struct) {
+               this._struct = _struct;
+       }
+
+       public JTextField get_seq() {
+               return _seq;
+       }
+
+       public void set_seq(JTextField _seq) {
+               this._seq = _seq;
+       }
+
+       public JLabel get_info() {
+               return _info;
+       }
+
+       public void set_info(JLabel _info) {
+               this._info = _info;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/VARNAPrinter.java b/src2/fr/orsay/lri/varna/applications/VARNAPrinter.java
new file mode 100644 (file)
index 0000000..6dbc332
--- /dev/null
@@ -0,0 +1,51 @@
+package fr.orsay.lri.varna.applications;
+
+import java.awt.*;
+import javax.swing.*;
+import java.awt.print.*;
+
+public class VARNAPrinter implements Printable {
+  private Component componentToBePrinted;
+
+  public static void printComponent(Component c) {
+    new VARNAPrinter(c).print();
+  }
+  
+  public VARNAPrinter(Component componentToBePrinted) {
+    this.componentToBePrinted = componentToBePrinted;
+  }
+  
+  public void print() {
+    PrinterJob printJob = PrinterJob.getPrinterJob();
+    printJob.setPrintable(this);
+    if (printJob.printDialog())
+      try {
+        printJob.print();
+      } catch(PrinterException pe) {
+        //System.out.println("Error printing: " + pe);
+      }
+  }
+
+  public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
+    if (pageIndex > 0) {
+      return(NO_SUCH_PAGE);
+    } else {
+      Graphics2D g2d = (Graphics2D)g;
+      g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
+      disableDoubleBuffering(componentToBePrinted);
+      componentToBePrinted.paint(g2d);
+      enableDoubleBuffering(componentToBePrinted);
+      return(PAGE_EXISTS);
+    }
+  }
+
+  public static void disableDoubleBuffering(Component c) {
+    RepaintManager currentManager = RepaintManager.currentManager(c);
+    currentManager.setDoubleBufferingEnabled(false);
+  }
+
+  public static void enableDoubleBuffering(Component c) {
+    RepaintManager currentManager = RepaintManager.currentManager(c);
+    currentManager.setDoubleBufferingEnabled(true);
+  }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/VARNAcmd.java b/src2/fr/orsay/lri/varna/applications/VARNAcmd.java
new file mode 100644 (file)
index 0000000..7b16c61
--- /dev/null
@@ -0,0 +1,529 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications;
+
+
+import java.awt.Graphics2D;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.FileImageOutputStream;
+import javax.swing.JFrame;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionJPEGEncoding;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.exceptions.ExceptionWritingForbidden;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.interfaces.InterfaceParameterLoader;
+import fr.orsay.lri.varna.models.FullBackup;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.VARNAConfigLoader;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VARNAcmd implements InterfaceParameterLoader {
+       
+       public class ExitCode extends Exception{
+               /**
+                * 
+                */
+               private static final long serialVersionUID = -3011196062868355584L;
+               private int _c;
+               private String _msg;
+               public ExitCode(int c,String msg){
+                       _c = c;
+                       _msg = msg;
+               }
+               public int getExitCode(){
+                       return _c;
+               }
+               public String getExitMessage(){
+                       return _msg;
+               }
+       }
+       
+       
+       private Hashtable<String, String> _optsValues = new Hashtable<String, String>();
+       private Hashtable<String, String> _basicOptsInv = new Hashtable<String, String>();
+       private String _inFile = "";
+       private String _outFile = "";
+       int _baseWidth = 400;
+       double _scale = 1.0;
+       float _quality = 0.9f;
+
+       private String[] _basicOptions = { VARNAConfigLoader.algoOpt,
+                       VARNAConfigLoader.bpStyleOpt, VARNAConfigLoader.bondColorOpt,
+                       VARNAConfigLoader.backboneColorOpt, VARNAConfigLoader.periodNumOpt,
+                       VARNAConfigLoader.baseInnerColorOpt,
+                       VARNAConfigLoader.baseOutlineColorOpt,
+
+       };
+
+       public VARNAcmd(Vector<String> args) throws ExitCode {
+               for (int j = 0; j < _basicOptions.length; j++) {
+                       _basicOptsInv.put(_basicOptions[j], _basicOptions[j]);
+               }
+               int i = 0;
+               while (i < args.size()) {
+                       String opt = args.elementAt(i);
+                       if (opt.charAt(0) != '-') {
+                               errorExit("Missing or unknown option \"" + opt + "\"");
+                       }
+                       if (opt.equals("-h")) {
+                               displayLightHelpExit();
+                       }
+                       if (opt.equals("-x")) {
+                               displayDetailledHelpExit();
+                       } else {
+                               if (i + 1 >= args.size()) {
+                                       errorExit("Missing argument for option \"" + opt + "\"");
+                               }
+                               String val = args.get(i + 1);
+                               if (opt.equals("-i")) {
+                                       _inFile = val;
+                               } else if (opt.equals("-o")) {
+                                       _outFile = val;
+                               } else if (opt.equals("-quality")) {
+                                       _quality = Float.parseFloat(val);
+                               } else if (opt.equals("-resolution")) {
+                                       _scale = Float.parseFloat(val);
+                               } else {
+                                       addOption(opt, val);
+                               }
+                       }
+                       i += 2;
+               }
+       }
+
+       public void addOption(String key, String value) {
+               if (key.equals("-i")) {
+                       _inFile = value;
+               } else if (key.equals("-o")) {
+                       _outFile = value;
+               } else {
+                       _optsValues.put(key.substring(1), value);
+               }
+       }
+
+       private String getDescription() {
+               return "VARNA v"
+                               + VARNAConfig.MAJOR_VERSION
+                               + "."
+                               + VARNAConfig.MINOR_VERSION
+                               + " Assisted drawing of RNA secondary structure (Command Line version)";
+       }
+
+       private String indent(int k) {
+               String result = "";
+               for (int i = 0; i < k; i++) {
+                       result += "  ";
+               }
+               return result;
+       }
+
+       private String complete(String s, int k) {
+               String result = s;
+               while (result.length() < k) {
+                       result += " ";
+               }
+               return result;
+       }
+
+       Vector<String[]> matrix = new Vector<String[]>();
+
+       private void addLine(String opt, String val) {
+               String[] line = { opt, val };
+               matrix.add(line);
+       }
+
+       private static int MAX_WIDTH = 100;
+
+       @SuppressWarnings("unchecked")
+       private void printMatrix(int ind) {
+               String[][] values = new String[matrix.size()][];
+               matrix.toArray(values);
+               Arrays.sort(values, new Comparator() {
+                       public int compare(Object o1, Object o2) {
+                               String[] tab1 = (String[]) o1;
+                               String[] tab2 = (String[]) o2;
+                               return tab1[0].compareTo(tab2[0]);
+                       }
+               });
+
+               int maxSize = 0;
+               for (int i = 0; i < values.length; i++) {
+                       String[] elem = values[i];
+                       maxSize = Math.max(maxSize, elem[0].length());
+               }
+               maxSize += ind + 2;
+               for (int i = 0; i < values.length; i++) {
+                       String[] elem = values[i];
+                       String opt = elem[0];
+                       String msg = elem[1];
+                       opt = complete("", ind) + "-" + complete(opt, maxSize - ind);
+                       System.out.println(opt  + msg.substring(0, Math.min(MAX_WIDTH - opt.length(), msg.length())));
+                       if (opt.length() + msg.length() >= MAX_WIDTH) {
+                               int off = MAX_WIDTH - opt.length();
+                               while (off < msg.length()) {
+                                       String nmsg = msg.substring(off, Math.min(off + MAX_WIDTH
+                                                       - opt.length(), msg.length()));
+                                       System.out.println(complete("", opt.length())+nmsg);
+                                       off += MAX_WIDTH - opt.length();
+                               }
+                       }
+               } 
+               matrix = new Vector<String[]>();
+       }
+
+       private void printUsage() {
+               System.out
+                               .println("Usage: java -cp . [-i InFile|-sequenceDBN XXX -structureDBN YYY] -o OutFile [Options]");
+               System.out.println("Where:");
+               System.out.println(indent(1)
+                               + "OutFile\tSupported formats: {JPEG,PNG,EPS,XFIG,SVG}");
+               System.out
+                               .println(indent(1)
+                                               + "InFile\tSecondary structure file: Supported formats: {BPSEQ,CT,RNAML,DBN}");
+
+       }
+
+       private void printHelpOptions() {
+               System.out.println("\nMain options:");
+               addLine("h", "Displays a short description of main options and exits");
+               addLine("x", "Displays a detailled description of all options");
+               printMatrix(2);
+       }
+
+       private void printMainOptions(String[][] info) {
+               System.out.println("\nMain options:");
+               addLine("h", "Displays a short description of main options and exits");
+               addLine("x", "Displays a detailled description of all options");
+               for (int i = 0; i < info.length; i++) {
+                       String key = info[i][0];
+                       if (_basicOptsInv.containsKey(key)) {
+                               addLine(key, info[i][2]);
+                       }
+               }
+               printMatrix(2);
+       }
+
+       private void printAdvancedOptions(String[][] info) {
+               System.out.println("\nAdvanced options:");
+               for (int i = 0; i < info.length; i++) {
+                       String key = info[i][0];
+                       if (!_basicOptsInv.containsKey(key)) {
+                               addLine(key, info[i][2]);
+                       }
+               }
+               addLine("quality", "Sets quality (non-vector file formats only)");
+               addLine("resolution", "Sets resolution (non-vector file formats only)");
+               printMatrix(2);
+       }
+
+       private void displayLightHelpExit() throws ExitCode {
+               String[][] info = VARNAConfigLoader.getParameterInfo();
+               System.out.println(getDescription());
+               printUsage();
+               printMainOptions(info);
+               throw(new ExitCode(1,""));
+       }
+
+       private void displayDetailledHelpExit() throws ExitCode {
+               String[][] info = VARNAConfigLoader.getParameterInfo();
+               System.out.println(getDescription());
+               printUsage();
+               printMainOptions(info);
+               printAdvancedOptions(info);
+               throw(new ExitCode(1,""));
+       }
+
+       private void errorExit(String msg) throws ExitCode {
+               System.out.println(getDescription());
+               System.out.println("Error: " + msg + "\n");
+               printUsage();
+               printHelpOptions();
+               throw(new ExitCode(1,""));
+       }
+
+       public String getParameterValue(String key, String def) {
+               if (_optsValues.containsKey(key)) {
+                       return _optsValues.get(key);
+               }
+               return def;
+       }
+
+       public String formatOutputPath(String base,int index, int total)
+       {
+               String result = base;
+               
+               if (total>1)
+               {
+                       int indexDot = base.lastIndexOf('.');
+                       String pref;
+                       String ext;
+                       if (indexDot!=-1)
+                       {
+                         pref = base.substring(0,indexDot);
+                         ext = base.substring(indexDot);
+                       }
+                       else{
+                               pref=base;
+                               ext="";
+                       }
+                       result = pref+"-"+index+ext;
+               }
+               System.err.println("Output file: "+result);
+               return result;
+       }
+       
+       public void run() throws IOException, ExitCode {
+               VARNAConfigLoader VARNAcfg = new VARNAConfigLoader(this);
+               ArrayList<VARNAPanel> vpl;
+               ArrayList<FullBackup> confs = new ArrayList<FullBackup>();
+               try {
+                       if (!_inFile.equals("")) {
+                               if (!_inFile.toLowerCase().endsWith(".varna")) {
+                                       Collection<RNA> rnas = RNAFactory.loadSecStr(_inFile);
+                                        if (rnas.isEmpty())
+                                        {
+                                                FullBackup f = null;
+                                                               try{
+                                                               f = VARNAPanel.importSession(new FileInputStream(_inFile), _inFile);
+                                                               confs.add(f);
+                                                               }
+                                                               catch(Exception e)
+                                                               {
+                                                                       e.printStackTrace();
+                                                               }
+                                               if (f==null)
+                                               {
+                                                throw new ExceptionFileFormatOrSyntax("No RNA could be parsed from file '"+_inFile+"'.");
+                                               }
+                                        }
+                                        else{
+                                                for (RNA r: rnas)
+                                                {
+                                                        confs.add(new FullBackup(r,_inFile));
+                                                }
+                                        }
+                               }
+                               else{
+                                       confs.add(VARNAPanel.importSession(_inFile));
+                               }
+                       } else {
+                               RNA r = new RNA();
+                               r.setRNA(this.getParameterValue("sequenceDBN",
+                                               ""), this.getParameterValue(
+                                               "structureDBN", ""));
+                               confs.add(new FullBackup(r,"From Params"));
+                       }
+                       if (!_outFile.equals(""))
+                       {
+                       int index = 1;
+                       for (FullBackup r: confs)
+                       {
+                               VARNAcfg.setRNA(r.rna);
+                               vpl = VARNAcfg.createVARNAPanels();
+                               if (vpl.size() > 0) {
+                               VARNAPanel _vp = vpl.get(0);
+                               if (r.hasConfig())
+                               {
+                                       _vp.setConfig(r.config);
+                               }
+                               RNA _rna = _vp.getRNA();
+                               Rectangle2D.Double bbox = _vp.getRNA().getBBox();
+                               //System.out.println(_vp.getRNA().getBBox());
+                               
+                               if (_outFile.toLowerCase().endsWith(".jpeg")
+                                               || _outFile.toLowerCase().endsWith(".jpg")
+                                               || _outFile.toLowerCase().endsWith(".png"))
+                               { 
+                                       _vp.setTitleFontSize((int)(_scale*_vp.getTitleFont().getSize())); 
+                                   _vp.setSize((int)(_baseWidth*_scale), (int)((_scale*_baseWidth*bbox.height)/((double)bbox.width)));
+                               }
+                               
+                               if (_outFile.toLowerCase().endsWith(".eps")) {
+                                       _rna.saveRNAEPS(formatOutputPath(_outFile,index, confs.size()), _vp.getConfig());
+                               } else if (_outFile.toLowerCase().endsWith(".xfig")
+                                               || _outFile.toLowerCase().endsWith(".fig")) {
+                                       _rna.saveRNAXFIG(formatOutputPath(_outFile,index, confs.size()), _vp.getConfig());
+                               } else if (_outFile.toLowerCase().endsWith(".svg")) {
+                                       _rna.saveRNASVG(formatOutputPath(_outFile,index, confs.size()), _vp.getConfig());
+                               } else if (_outFile.toLowerCase().endsWith(".jpeg")
+                                               || _outFile.toLowerCase().endsWith(".jpg")) {
+                                       this.saveToJPEG(formatOutputPath(_outFile,index, confs.size()), _vp);
+                               } else if (_outFile.toLowerCase().endsWith(".png")) {
+                                       this.saveToPNG(formatOutputPath(_outFile,index, confs.size()), _vp);
+                               } else if (_outFile.toLowerCase().endsWith(".varna")) {
+                                       _vp.saveSession(formatOutputPath(_outFile,index, confs.size()));
+                               } else {
+                                       errorExit("Unknown extension for output file \"" + _outFile
+                                                       + "\"");
+                               }
+                       }
+                       index++;
+                       }
+                       }
+                       // No output file => Open GUI
+                       else
+                       {
+                               VARNAGUI d = new VARNAGUI();
+                               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+                               d.pack();
+                               d.setVisible(true);
+                               for (FullBackup b: confs)
+                               {
+                                       RNA r = b.rna;
+                                       VARNAcfg.setRNA(r);
+                                       vpl = VARNAcfg.createVARNAPanels();
+                                       if (vpl.size() > 0) {
+                                               VARNAPanel _vp = vpl.get(0);
+                                               VARNAConfig cfg = _vp.getConfig();
+                                               if (b.hasConfig())
+                                               {
+                                                       cfg = b.config;
+                                               }
+                                               RNA rna = _vp.getRNA();
+                                               d.addRNA(rna, cfg);
+                                               
+                                       }
+                               }
+                       }
+               } catch (ExceptionWritingForbidden e) {
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (ExceptionJPEGEncoding e) {
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (ExceptionParameterError e) {
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (ExceptionModeleStyleBaseSyntaxError e) {
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (ExceptionNonEqualLength e) {
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (ExceptionUnmatchedClosingParentheses e) {
+                       e.printStackTrace();
+                       System.exit(1);
+               } catch (ExceptionExportFailed e) {
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (ExceptionPermissionDenied e) {
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (ExceptionLoadingFailed e) {
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       e.setPath(_inFile);
+                       e.printStackTrace();
+                       throw(new ExitCode(1,""));
+               } catch (FileNotFoundException e) {
+                       throw(new ExitCode(1,"Error: Missing input file \""+_inFile+"\"."));
+               }
+               
+               if (!_outFile.equals(""))
+                       throw(new ExitCode(0,""));
+               
+               
+       
+       }
+
+       public void saveToJPEG(String filename, VARNAPanel vp)
+                       throws ExceptionJPEGEncoding, ExceptionExportFailed {
+               
+               BufferedImage myImage = new BufferedImage((int) Math.round(vp
+                               .getWidth()
+                               ), (int) Math.round(vp.getHeight() ),
+                               BufferedImage.TYPE_INT_RGB);
+               Graphics2D g2 = myImage.createGraphics();
+               vp.paintComponent(g2);
+               try {
+                       FileImageOutputStream out = new FileImageOutputStream(new File(filename));
+                       ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
+                       ImageWriteParam params = writer.getDefaultWriteParam();
+                       params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
+                       params.setCompressionQuality(_quality);
+                       writer.setOutput(out);
+                       IIOImage myIIOImage = new IIOImage(myImage, null, null);
+                       writer.write(null, myIIOImage, params);
+                       out.close();
+               } catch (IOException e) {
+                       throw new ExceptionExportFailed(e.getMessage(), filename);
+               }
+
+       }
+
+       public void saveToPNG(String filename, VARNAPanel vp)
+                       throws ExceptionExportFailed {
+               BufferedImage myImage = new BufferedImage((int) Math.round(vp
+                               .getWidth()), (int) Math.round(vp.getHeight() ),
+                               BufferedImage.TYPE_INT_RGB);
+               Graphics2D g2 = myImage.createGraphics();
+               vp.paintComponent(g2);
+               g2.dispose();
+               try {
+                       ImageIO.write(myImage, "PNG", new File(filename));
+               } catch (IOException e) {
+                       e.printStackTrace();
+               }
+       }
+
+       public static void main(String[] argv) {
+               Vector<String> opts = new Vector<String>();
+               for (int i = 0; i < argv.length; i++) {
+                       opts.add(argv[i]);
+               }
+               try {
+                       VARNAcmd app = new VARNAcmd(opts);
+                       app.run();
+               } catch (IOException e) {
+                       e.printStackTrace();
+               } catch (ExitCode e) {
+                       System.err.println(e.getExitMessage());
+                       System.exit(e.getExitCode());
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqAnnotationDataModel.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqAnnotationDataModel.java
new file mode 100644 (file)
index 0000000..15c0522
--- /dev/null
@@ -0,0 +1,112 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.awt.Color;
+import java.awt.datatransfer.DataFlavor;
+import java.util.Hashtable;
+import java.util.Random;
+
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation.ChemProbAnnotationType;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class FragSeqAnnotationDataModel extends FragSeqModel {
+  private String _id;
+  private String _name;
+  private Hashtable<Integer, ChemProbModel> _values = new Hashtable<Integer, ChemProbModel>();  
+  
+  
+  public FragSeqAnnotationDataModel(String id, String name)
+  {
+       _id = id;
+       _name = name;
+  }
+
+  public FragSeqAnnotationDataModel()
+  {
+       this(Long.toHexString(Double.doubleToLongBits(Math.random())),Long.toHexString(Double.doubleToLongBits(Math.random())));
+  }
+
+  public void addValue(ChemProbModel cpm)
+  {
+         _values.put(cpm._baseNumber1,cpm);
+  }
+
+  static Random _rnd = new Random();
+  
+  public static void addRandomAnnotations(RNA r,FragSeqAnnotationDataModel data){
+         int nb = r.getSize()/5+_rnd.nextInt(r.getSize()/3);
+         Color[] colors = {Color.orange,Color.black,Color.blue.darker(),Color.green.darker(), Color.gray};
+         ChemProbAnnotationType[] types  = ChemProbAnnotationType.values();
+         for(int i=0;i<nb;i++)
+         {
+                 int index = _rnd.nextInt(r.getSize()-1);
+                 int number1 = r.getBaseNumber(index);
+                 int number2 = r.getBaseNumber(index+1);
+                 ChemProbModel cpm = data.new ChemProbModel(number1,number2,colors[_rnd.nextInt(colors.length)],2*_rnd.nextDouble(),types[_rnd.nextInt(types.length)],true);
+                 data.addValue(cpm);
+         }
+  }
+
+  
+  public String toString()
+  {
+         return _name;
+  }
+  
+  public String getID()
+  {
+         return _id;
+  }
+
+  public void applyTo(RNA r)
+  {
+       r.clearChemProbAnnotations();
+       for (ChemProbModel c : _values.values())
+       {
+               c.applyTo(r);
+       }
+  }
+
+  
+  public class ChemProbModel
+  {
+               private Color _color;
+               private double _intensity;
+               private ChemProbAnnotationType _type;
+               private boolean _out;
+               private int _baseNumber1;
+               private int _baseNumber2;
+               
+               public ChemProbModel (int baseNumber1,int baseNumber2, Color color, double intensity, ChemProbAnnotationType type, boolean out)
+               {
+                       _color= color;
+                       _intensity = intensity;
+                       _type= type;
+                       _out= out;
+                       _baseNumber1 = baseNumber1;
+                       _baseNumber2 = baseNumber2;
+               }
+
+               public void applyTo(RNA r)
+               {
+                       System.out.println(this);
+                       int i = r.getIndexFromBaseNumber(_baseNumber1);
+                       int j = r.getIndexFromBaseNumber(_baseNumber2);
+                       if (i!=-1 && j!=-1)
+                       {
+                               ModeleBase mb1 = r.getBaseAt(i);
+                               ModeleBase mb2 = r.getBaseAt(j);
+                               r.addChemProbAnnotation(new ChemProbAnnotation(mb1, mb2, _type, _intensity,_color, _out));
+                       }
+               }
+               
+               public String toString()
+               {
+                       return ""+_baseNumber1+": col="+_color+" int="+_intensity+" type="+_type+" out="+_out;
+               }
+  }
+  
+  public static DataFlavor Flavor = new DataFlavor(FragSeqAnnotationDataModel.class, "RNA Chem Prob Data");
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqCellEditor.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqCellEditor.java
new file mode 100644 (file)
index 0000000..4f9ff3c
--- /dev/null
@@ -0,0 +1,53 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.awt.Component;
+import java.awt.event.MouseEvent;
+import java.io.File;
+import java.util.EventObject;
+
+import javax.swing.JButton;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTree;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeCellEditor;
+import javax.swing.tree.DefaultTreeCellRenderer;
+
+class FragSeqCellEditor extends DefaultTreeCellEditor {  
+       
+       FragSeqTreeModel _m;
+       
+       private FragSeqCellRenderer _base;
+
+    public FragSeqCellEditor(JTree tree, DefaultTreeCellRenderer renderer, FragSeqTreeModel m) {
+               super(tree, renderer);
+               _base= new FragSeqCellRenderer(tree,m);
+               _m=m;
+       }
+    
+    
+    public Component getTreeCellEditorComponent(JTree tree,  
+            Object value, boolean sel, boolean expanded, boolean leaf,  
+            int row)  
+    {  
+     
+    JPanel renderer = (JPanel) _base.baseElements(tree,_m,value,sel,expanded,leaf,row,true);
+    return renderer;  
+    }
+
+    public boolean isCellEditable(EventObject evt)
+    {
+        if (evt instanceof MouseEvent) {
+            int clickCount;
+            // For single-click activation
+            clickCount = 1;
+
+            return ((MouseEvent)evt).getClickCount() >= clickCount;
+        }
+        return true;
+
+    }
+
+    
+}  
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqCellRenderer.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqCellRenderer.java
new file mode 100644 (file)
index 0000000..d1e92bf
--- /dev/null
@@ -0,0 +1,225 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.awt.BasicStroke;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.File;
+
+import javax.swing.BorderFactory;
+import javax.swing.Icon;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTree;
+import javax.swing.UIManager;
+import javax.swing.border.Border;
+import javax.swing.plaf.basic.BasicTreeUI;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeCellRenderer;
+
+class FragSeqCellRenderer extends DefaultTreeCellRenderer {  
+          
+       JTree _j;
+       FragSeqTreeModel _m;
+       
+       private static FragSeqCellRenderer _default = new FragSeqCellRenderer(null,null);
+
+       
+
+       public FragSeqCellRenderer (JTree j, FragSeqTreeModel m)
+       {
+               _j = j;
+               _m = m;
+       }
+       
+       public JComponent baseElements(JTree tree,FragSeqTreeModel m,  
+            Object value, boolean sel, boolean expanded, boolean leaf,  
+            int row, boolean hasFocus)
+       {
+               JLabel initValue = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
+        JPanel result = new JPanel();
+        result.setLayout(new BorderLayout());
+        initValue.setBorder(null);
+        result.setBorder(null);
+        result.setBackground(initValue.getBackground());
+        /*if (hasFocus)
+        { 
+               //renderer.setBackground(Color.blue);            
+               //result.setBorder(BorderFactory.createLineBorder(Color.blue));
+            result.setBackground(UIManager.getColor("Tree.selectionBackground"));
+            result.setBorder(BorderFactory.createLineBorder(initValue.getBackground()));
+            initValue.setOpaque(true);
+        }
+        else
+        {
+               result.setBackground(Color.white);
+               result.setBorder(BorderFactory.createLineBorder(initValue.getBackground()));
+            
+        }*/
+        DefaultMutableTreeNode t = (DefaultMutableTreeNode)value;
+        Object o = t.getUserObject();
+        if (( o instanceof String))    
+        {  
+            if (expanded)  
+            {  
+               initValue.setIcon(_default.getOpenIcon());  
+            }  
+            else  
+            {  
+               initValue.setIcon(_default.getClosedIcon());  
+            }  
+            result.add(initValue,BorderLayout.WEST);
+               JButton del = new JButton();
+               del.setIcon(new SimpleIcon(Color.red,26,false));
+               Dimension d = getPreferredSize();
+               d.width=24;
+               del.setPreferredSize(d);
+               del.addActionListener(new FolderCloses((String)o,tree,m));
+            result.add(del,BorderLayout.EAST);
+        }  
+        else  if (( o instanceof FragSeqRNASecStrModel))
+        {  
+               initValue.setIcon(new SimpleIcon(Color.blue.darker()));  
+               result.add(initValue,BorderLayout.WEST);
+        }
+        else  if (( o instanceof FragSeqFileModel))
+        {  
+               initValue.setIcon(_default.getLeafIcon());  
+            FragSeqFileModel mod = (FragSeqFileModel) o;
+            result.add(initValue,BorderLayout.WEST);
+            if (mod.hasChanged())
+            {
+                 JButton refresh = new JButton("Refresh");
+              result.add(refresh,BorderLayout.EAST);
+            }
+        }
+        else  if (( o instanceof FragSeqModel))
+        {
+               FragSeqModel mod = (FragSeqModel) o;
+               initValue.setIcon(new SimpleIcon());  
+            result.add(initValue,BorderLayout.WEST);           
+        }
+        return result;
+       }
+       
+    public Component getDefaultTreeCellRendererComponent(JTree tree,  
+            Object value, boolean sel, boolean expanded, boolean leaf,  
+            int row, boolean hasFocus)  
+    {
+      return super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
+    }
+
+       public Component getTreeCellRendererComponent(JTree tree,  
+            Object value, boolean sel, boolean expanded, boolean leaf,  
+            int row, boolean hasFocus)  
+    {
+       
+        return baseElements(tree,_m,value,sel,expanded,leaf,row,hasFocus);  
+    }  
+    public Dimension getPreferredSize(int row) {
+        Dimension size = super.getPreferredSize();
+        size.width = _j.getWidth();
+        System.out.println(size);
+        return size;
+    }
+
+
+//    @Override
+//    public void setBounds(final int x, final int y, final int width, final int height) {
+//    super.setBounds(x, y, Math.min(_j.getWidth()-x, width), height);
+//    }
+    
+    
+    public class FolderCloses implements ActionListener{
+       String _path;
+       JComponent _p;
+       FragSeqTreeModel _m;
+       
+       public FolderCloses(String path, JComponent p, FragSeqTreeModel m)
+       {
+               _path = path;
+               _p = p;
+               _m = m;
+       }
+               public void actionPerformed(ActionEvent e) {
+                       if (JOptionPane.showConfirmDialog(_p, "This folder will cease to be watched. Confirm?", "Closing folder", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
+                       {
+                               _m.removeFolder(_path);
+                               System.out.println(_j);
+                               _j.updateUI();
+                       }
+               }
+                   
+    }
+
+    
+    public class SimpleIcon implements Icon{
+
+        private int _w = 16;
+        private int _h = 16;
+
+        private BasicStroke stroke = new BasicStroke(3);
+        private Color _r;
+        private boolean _drawBackground = true;
+
+        public SimpleIcon()
+        {
+               this(Color.magenta.darker());
+        }
+        public SimpleIcon(Color r)
+        {
+               this(r,16,true);
+        }
+        public SimpleIcon(Color r, int dim, boolean drawBackground)
+        {
+               this(r,dim,dim,drawBackground);
+        }
+
+        public SimpleIcon(Color r, int width, int height,boolean drawBackground)
+        {
+               _r=r;
+               _w=width;
+               _h=height;
+               _drawBackground=drawBackground;
+        }
+
+        public void paintIcon(Component c, Graphics g, int x, int y) {
+            Graphics2D g2d = (Graphics2D) g.create();
+
+            if (_drawBackground)
+            {
+            g2d.setColor(Color.WHITE);
+            g2d.fillRect(x +1 ,y + 1,_w -2 ,_h -2);
+
+            g2d.setColor(Color.BLACK);
+            g2d.drawRect(x +1 ,y + 1,_w -2 ,_h -2);
+            }
+
+            g2d.setColor(_r);
+
+            g2d.setStroke(stroke);
+            g2d.drawLine(x +10, y + 10, x + _w -10, y + _h -10);
+            g2d.drawLine(x +10, y + _h -10, x + _w -10, y + 10);
+
+            g2d.dispose();
+        }
+
+        public int getIconWidth() {
+            return _w;
+        }
+
+        public int getIconHeight() {
+            return _h;
+        }
+    }
+}  
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqFileModel.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqFileModel.java
new file mode 100644 (file)
index 0000000..6374db8
--- /dev/null
@@ -0,0 +1,158 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.awt.datatransfer.DataFlavor;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Random;
+import java.util.regex.Pattern;
+
+import javax.swing.tree.DefaultMutableTreeNode;
+
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class FragSeqFileModel implements Comparable<FragSeqFileModel> {
+       private ArrayList<FragSeqModel> _models = new ArrayList<FragSeqModel>();
+         protected Date _lastModified;
+         protected boolean _outOfSync = false;
+         protected String _caption = "";
+         protected String _path = "";
+         protected String _folder = "";
+         protected boolean _cached = false;
+
+         
+         public static Date lastModif(String path)
+         {
+                return new Date(new File(path).lastModified()) ;
+         }
+         
+         public FragSeqFileModel(String folder, String path)
+         {
+               this(folder,path,lastModif(path));
+         }
+         
+         
+         private static Random _rnd = new Random();
+         
+         public FragSeqFileModel(String folder, String path,Date lastModified)
+         {
+                 _lastModified = lastModified;
+                 _outOfSync = false;
+                 _folder =folder;
+                 _path = path;
+                 String[] s = path.split(Pattern.quote(File.separator));
+                 if (s.length>0)
+                   _caption = s[s.length-1];
+         }
+         
+         public void load()
+         {
+                 ArrayList<RNA> rnas = null;
+                 try {
+                         rnas = createRNAs();
+                       for (RNA r: rnas)
+                       {  
+                               this.addModel(new FragSeqRNASecStrModel(r));
+                                 int nb =_rnd.nextInt(5); 
+                                 for(int i=0;i<nb;i++)
+                                 {
+                                         FragSeqAnnotationDataModel data = new FragSeqAnnotationDataModel(r.getID(),""+i+"-"+r.getID());
+                                         FragSeqAnnotationDataModel.addRandomAnnotations(r,data);
+                                         addModel(data);
+                                 }               
+                       }
+               } catch (ExceptionUnmatchedClosingParentheses e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (FileNotFoundException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionExportFailed e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionPermissionDenied e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionLoadingFailed e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+                 _cached = true;
+         }
+         
+         public boolean hasChanged()
+         {
+                 return _outOfSync;
+         }
+         
+         public boolean checkForModifications()
+         {
+               if (!lastModif(_path).equals(_lastModified) && !_outOfSync)
+               {
+                       _outOfSync = true;
+                         return true;
+               }
+               return false;
+         }
+         
+         
+         public String toString()
+         {
+                 return _caption + (this._outOfSync?"*":"");
+         }
+         
+         
+         public String getCaption()
+         {
+                 return _caption;
+         }
+
+         public String getFolder()
+         {
+                 return _folder;
+         }
+
+         public String getPath()
+         {
+                 return _path;
+         }
+
+
+       public int compareTo(FragSeqFileModel o) {
+               return _caption.compareTo(o._caption);
+       }
+         
+       public ArrayList<FragSeqModel> getModels()
+       {
+               if (!_cached)
+               {  load();  }
+               return _models;
+       }
+       public void addModel(FragSeqModel f)
+       {
+               _models.add(f);
+       }
+
+       
+       private ArrayList<RNA> createRNAs() throws ExceptionUnmatchedClosingParentheses, ExceptionFileFormatOrSyntax, FileNotFoundException, ExceptionExportFailed, ExceptionPermissionDenied, ExceptionLoadingFailed
+         {
+                 Collection<RNA> r = RNAFactory.loadSecStr(_path);
+                 for (RNA r2 : r)
+                 {
+                         r2.drawRNARadiate();
+                 }
+                 return new ArrayList<RNA>(r);
+         }
+         
+}
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqGUI.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqGUI.java
new file mode 100644 (file)
index 0000000..db2c3ee
--- /dev/null
@@ -0,0 +1,958 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ComponentEvent;
+import java.awt.event.ComponentListener;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.WindowEvent;
+import java.awt.event.WindowListener;
+import java.io.IOException;
+import java.util.ArrayList;
+
+import javax.swing.BorderFactory;
+import javax.swing.ButtonGroup;
+import javax.swing.DefaultListSelectionModel;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTextPane;
+import javax.swing.JToolBar;
+import javax.swing.JTree;
+import javax.swing.ListSelectionModel;
+import javax.swing.LookAndFeel;
+import javax.swing.SwingUtilities;
+import javax.swing.TransferHandler;
+import javax.swing.UIManager;
+import javax.swing.UIManager.LookAndFeelInfo;
+import javax.swing.UnsupportedLookAndFeelException;
+import javax.swing.event.TreeModelEvent;
+import javax.swing.event.TreeModelListener;
+import javax.swing.event.TreeSelectionEvent;
+import javax.swing.event.TreeSelectionListener;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.ExpandVetoException;
+import javax.swing.tree.TreePath;
+import javax.swing.tree.TreeSelectionModel;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.applications.BasicINI;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.models.FullBackup;
+
+
+public class FragSeqGUI extends JFrame implements TreeModelListener, MouseListener,DropTargetListener, WindowListener, ComponentListener, ActionListener, TreeSelectionListener {
+
+       private enum Commands
+       {
+               NEW_FOLDER,
+               ADD_PANEL_UP,
+               ADD_PANEL_DOWN,
+               REMOVE_PANEL_UP,
+               REMOVE_PANEL_DOWN,
+               SORT_ID,
+               SORT_FILENAME,
+               REFRESH_ALL,
+               CHANGE_LNF,
+               TEST_XML,
+       };
+       
+       
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+
+               
+       private String _INIFilename = "FragSeqUI.ini";
+       private boolean redrawOnSlide = false;
+       private int dividerWidth = 5;
+       
+       private JPanel _varnaUpperPanels = new JPanel();
+       private JPanel _varnaLowerPanels = new JPanel();
+
+       private JPanel _listPanel = new JPanel();
+       private JPanel _infoPanel = new JPanel();
+       private FragSeqTree _sideList = null;
+
+       
+       private FragSeqTreeModel _treeModel;
+       private JToolBar _toolbar = new JToolBar();
+       private JFileChooser _choice = new JFileChooser();
+       
+       private JScrollPane _listScroller;
+
+       private JList _selectedElems;
+       private JSplitPane _splitLeft;
+       private JSplitPane _splitRight;
+       private JSplitPane _splitVARNA;
+       
+       private JComboBox _lnf; 
+
+
+       public FragSeqGUI() {
+               super("VARNA Explorer");
+               RNAPanelDemoInit();
+       }
+
+       
+       private void RNAPanelDemoInit() 
+       {
+               JFrame.setDefaultLookAndFeelDecorated(true);
+               this.addWindowListener(this);
+           
+               _selectedElems = new JList();
+
+               _lnf = new JComboBox(UIManager.getInstalledLookAndFeels());
+               
+               // Initializing Custom Tree Model
+               _treeModel = new FragSeqTreeModel();
+               _treeModel.addTreeModelListener(this);
+               
+               _sideList = new FragSeqTree(_treeModel);
+               _sideList.addMouseListener(this);
+               _sideList.setLargeModel(true);
+               _sideList.setEditable(true);
+               _sideList.addTreeWillExpandListener(_treeModel);
+               FragSeqCellRenderer renderer = new FragSeqCellRenderer(_sideList,_treeModel);
+               //_sideList.setUI(new CustomTreeUI());
+               _sideList.setCellRenderer(renderer);
+               _sideList.setCellEditor(new FragSeqCellEditor(_sideList,renderer,_treeModel));
+               TreeSelectionModel m = _sideList.getSelectionModel();
+               m.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
+               _sideList.setSelectionModel(m);
+               m.addTreeSelectionListener(this);
+               _sideList.setShowsRootHandles(true);
+               _sideList.setDragEnabled(true);
+               _sideList.setRootVisible(false);
+               _sideList.setTransferHandler(new TransferHandler(null) 
+               {
+                       public int getSourceActions(JComponent c) {
+                               return COPY_OR_MOVE;
+                       }
+                       protected Transferable createTransferable(JComponent c) {
+                               JTree tree = (JTree) c;
+                               TreePath tp =tree.getSelectionPath();
+                               if (tp!=null)
+                               {
+                                       DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
+                                       if (node.getUserObject() instanceof FragSeqRNASecStrModel) {
+                                               return new Transferable(){
+                                                       public DataFlavor[] getTransferDataFlavors() {
+                                                               DataFlavor[] dt = {FragSeqRNASecStrModel.Flavor};
+                                                               return dt;
+                                                       }
+                                                       public Object getTransferData(DataFlavor df)
+                                                       throws UnsupportedFlavorException, IOException {
+                                                               if (!isDataFlavorSupported(df))
+                                                                       throw new UnsupportedFlavorException(df);
+                                                               DefaultMutableTreeNode node = (DefaultMutableTreeNode) _sideList.getSelectionPath().getLastPathComponent();
+                                                               return node.getUserObject();
+                                                       }
+                                                       public boolean isDataFlavorSupported(DataFlavor df) {
+                                                               return FragSeqRNASecStrModel.Flavor.equals(df);
+                                                       }
+                                               };
+                                       } else  if (node.getUserObject() instanceof FragSeqAnnotationDataModel) {
+                                                       return new Transferable(){
+                                                               public DataFlavor[] getTransferDataFlavors() {
+                                                                       DataFlavor[] dt = { FragSeqAnnotationDataModel.Flavor};
+                                                                       return dt;
+                                                               }
+                                                               public Object getTransferData(DataFlavor df)
+                                                               throws UnsupportedFlavorException, IOException {
+                                                                       if (!isDataFlavorSupported(df))
+                                                                               throw new UnsupportedFlavorException(df);
+                                                                       DefaultMutableTreeNode node = (DefaultMutableTreeNode) _sideList.getSelectionPath().getLastPathComponent();
+                                                                       return node.getUserObject();
+                                                               }
+                                                               public boolean isDataFlavorSupported(DataFlavor df) {
+                                                                       return FragSeqAnnotationDataModel.Flavor.equals(df);
+                                                               }
+                                                       };
+                                               } else {
+                                               return null;
+                                       }
+                               }
+                               return null;
+                       }
+               });
+
+               // Various buttons
+               JButton refreshAllFoldersButton = new JButton("Refresh All");
+               refreshAllFoldersButton.setActionCommand(""+Commands.REFRESH_ALL);
+               refreshAllFoldersButton.addActionListener(this);
+               
+               JButton watchFolderButton = new JButton("Add folder");
+               watchFolderButton.setActionCommand("" +Commands.NEW_FOLDER);
+               watchFolderButton.addActionListener(this);
+               
+               JButton addUpperButton = new JButton("+Up");
+               addUpperButton.setActionCommand(""+Commands.ADD_PANEL_UP);
+               addUpperButton.addActionListener(this);
+               
+               JButton removeUpperButton = new JButton("-Up");
+               removeUpperButton.setActionCommand(""+Commands.REMOVE_PANEL_UP);
+               removeUpperButton.addActionListener(this);
+               
+               JButton addLowerButton = new JButton("+Down");
+               addLowerButton.setActionCommand(""+Commands.ADD_PANEL_DOWN);
+               addLowerButton.addActionListener(this);
+               
+               JButton removeLowerButton = new JButton("-Down");
+               removeLowerButton.setActionCommand(""+Commands.REMOVE_PANEL_DOWN);
+               removeLowerButton.addActionListener(this);
+               
+               JButton changeLNFButton = new JButton("Change");
+               changeLNFButton.setActionCommand(""+Commands.CHANGE_LNF);
+               changeLNFButton.addActionListener(this);
+
+               JButton XMLButton = new JButton("Test XML");
+               XMLButton.setActionCommand(""+Commands.TEST_XML);
+               XMLButton.addActionListener(this);
+
+               _toolbar.setFloatable(false);
+               _toolbar.add(refreshAllFoldersButton);
+               _toolbar.addSeparator();
+               _toolbar.add(addUpperButton);
+               _toolbar.add(removeUpperButton);
+               _toolbar.add(addLowerButton);
+               _toolbar.add(removeLowerButton);
+               _toolbar.addSeparator();
+               _toolbar.add(XMLButton);
+               _toolbar.addSeparator();
+               _toolbar.add(_lnf);
+               _toolbar.add(changeLNFButton);
+               
+               // Scroller for File tree
+           _listScroller = new JScrollPane(_sideList,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
+           _listScroller.setPreferredSize(new Dimension(300, 200));
+           _listScroller.addComponentListener(this);
+
+               
+               _listPanel.setLayout(new BorderLayout());
+               
+               _listPanel.add(_listScroller,BorderLayout.CENTER);
+               _listPanel.add(_selectedElems,BorderLayout.SOUTH);
+               _listPanel.setBorder(BorderFactory.createTitledBorder("Structures"));
+               _listPanel.setPreferredSize(new Dimension(300, 0));
+               
+               _varnaUpperPanels.setLayout(new GridLayout());
+               _varnaUpperPanels.setPreferredSize(new Dimension(800, 600));
+               
+               _varnaLowerPanels.setLayout(new GridLayout());
+               _varnaLowerPanels.setPreferredSize(new Dimension(800, 000));
+               
+           JRadioButton sortFileName = new JRadioButton("Directory");
+           sortFileName.setActionCommand("sortfilename");
+           sortFileName.setSelected(true);
+           sortFileName.setOpaque(false);
+           sortFileName.setActionCommand(""+Commands.SORT_FILENAME);
+           sortFileName.addActionListener(this);
+           JRadioButton sortID = new JRadioButton("ID");
+           sortID.setActionCommand("sortid");
+           sortID.setOpaque(false);
+           sortID.setActionCommand(""+Commands.SORT_ID);
+           sortID.addActionListener(this);
+
+           ButtonGroup group = new ButtonGroup();
+           group.add(sortFileName);
+           group.add(sortID);
+               
+               JToolBar listTools = new JToolBar();
+               listTools.setFloatable(false);
+               listTools.add(watchFolderButton);
+               listTools.addSeparator();
+           listTools.add(new JLabel("Sort by"));
+               listTools.add(sortFileName);
+               listTools.add(sortID);
+
+               JPanel sidePanel = new JPanel();
+               sidePanel.setLayout(new BorderLayout());
+               sidePanel.add(listTools,BorderLayout.NORTH);
+               sidePanel.add(_listPanel,BorderLayout.CENTER);
+               
+               
+               JPanel mainVARNAPanel = new JPanel();
+               mainVARNAPanel.setLayout(new BorderLayout());
+               _splitVARNA = new JSplitPane(JSplitPane.VERTICAL_SPLIT,redrawOnSlide,_varnaUpperPanels,_varnaLowerPanels);
+               _splitVARNA.setDividerSize(dividerWidth);
+               _splitVARNA.setResizeWeight(1.0);
+               _splitLeft = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,redrawOnSlide,sidePanel,_splitVARNA);
+               _splitLeft.setResizeWeight(0.1);
+               _splitLeft.setDividerSize(dividerWidth);
+               _splitRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,redrawOnSlide,_splitLeft,_infoPanel);
+               _splitRight.setResizeWeight(0.85);
+               _splitRight.setDividerSize(dividerWidth);
+               
+               _infoPanel.setLayout(new GridLayout(0,1));
+               
+               this.restoreConfig();           
+               this.getContentPane().setLayout(new BorderLayout());
+               this.getContentPane().add(_splitRight, BorderLayout.CENTER);
+               this.getContentPane().add(_toolbar, BorderLayout.NORTH);
+               addUpperPanel();
+               addUpperPanel();
+               this.setVisible(true);
+       }
+       
+       public FragSeqGUI getSelf()
+       {
+               return this;
+       }
+       
+       public VARNAHolder createIntegratedPanel(int height)
+       {
+               VARNAHolder vh = new VARNAHolder(this);
+               _varnaPanels.add(vh);
+               return vh;
+       }
+       
+       
+       public void removeUpperPanel()
+       {
+               if (_varnaUpperPanels.getComponentCount()>1)
+               {
+                       VARNAHolder vh = (VARNAHolder) _varnaUpperPanels.getComponent(_varnaUpperPanels.getComponentCount()-1);
+                       _infoPanel.remove(vh.getInfoPane());
+                       _varnaUpperPanels.remove(vh);
+                       _splitLeft.validate();
+                       _splitRight.validate();
+               }
+       }
+
+       public void addUpperPanel()
+       {
+               VARNAHolder vh = createIntegratedPanel(100);
+               _varnaUpperPanels.add(vh);
+               _infoPanel.add(vh.getInfoPane());
+               _splitRight.validate();
+               _splitLeft.validate();
+       }
+
+       
+       public void removeLowerPanel()
+       {
+               if (_varnaLowerPanels.getComponentCount()>0)
+               {
+                       _varnaLowerPanels.remove(_varnaLowerPanels.getComponentCount()-1);
+                       if (_varnaLowerPanels.getComponentCount()==0)
+                       {
+                               _splitVARNA.setDividerLocation(1.0);
+                               _splitVARNA.validate();
+                               _splitVARNA.repaint();
+                       }
+                       _splitLeft.validate();
+               }
+       }
+
+       public void addLowerPanel()
+       {
+               if (_varnaLowerPanels.getComponentCount()==0)
+               {
+                       _splitVARNA.setDividerLocation(0.7);
+                       _splitVARNA.validate();
+               }
+               _varnaLowerPanels.add(createIntegratedPanel(400));
+               _splitLeft.validate();
+       }
+
+
+       public void treeNodesChanged(TreeModelEvent e) {
+              DefaultMutableTreeNode node;
+               node = (DefaultMutableTreeNode)
+                        (e.getTreePath().getLastPathComponent());
+
+               /*
+                * If the event lists children, then the changed
+                * node is the child of the node we have already
+                * gotten.  Otherwise, the changed node and the
+                * specified node are the same.
+                */
+               try {
+                   int index = e.getChildIndices()[0];
+                   node = (DefaultMutableTreeNode)
+                          (node.getChildAt(index));
+               } catch (NullPointerException exc) {}
+
+       }
+       
+       
+
+
+       public void addFolder(String path) {
+               addFolder( path, true); 
+       }
+
+    public void addFolder(String path,
+            boolean shouldBeVisible) 
+    {
+       DefaultMutableTreeNode childNode = _treeModel.addFolder(path);
+       
+               if ((childNode!=null) && shouldBeVisible ) {
+                         System.out.println("  Expanding: "+childNode.getUserObject());
+                         TreePath tp = new TreePath(childNode.getPath());
+                       _sideList.scrollPathToVisible(tp);                      
+                       _sideList.expandRow(_sideList.getRowForPath(tp));
+                       _sideList.updateUI();
+                       _sideList.validate();
+               }
+    }
+
+       public void treeNodesInserted(TreeModelEvent e) {
+               System.out.println(e);
+               
+       }
+
+       public void treeNodesRemoved(TreeModelEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void treeStructureChanged(TreeModelEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseClicked(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mousePressed(MouseEvent e) {
+               
+       }
+
+       int index = 0;
+       
+       public void mouseReleased(MouseEvent e) {
+               // TODO Auto-generated method stub
+               if (e.getSource() == this._sideList)
+               {
+                       if (e.getClickCount() == 1)
+                       {
+                               /*TreePath t = _sideList.getSelectionPath();
+                               if (t!=null)
+                               {
+                               DefaultMutableTreeNode node = (DefaultMutableTreeNode) t.getLastPathComponent();
+                               if (node.getUserObject() instanceof FragSeqFileModel)
+                               {
+                                       int row = _sideList.getRowForPath(t);
+                                       System.out.println("[A]"+row);
+                                       if (!_sideList.isExpanded(row))
+                                       {
+                                               try {
+                                                       _sideList.fireTreeWillExpand(t);
+                                                       _sideList.expandPath(t);
+                                               } catch (ExpandVetoException e1) {
+                                                       // TODO Auto-generated catch block
+                                                       e1.printStackTrace();
+                                               }
+                                       }
+                                       else 
+                                       {
+                                               try {
+                                                       _sideList.fireTreeWillCollapse(t);
+                                                       _sideList.collapsePath(t);
+                                               } catch (ExpandVetoException e1) {
+                                                       // TODO Auto-generated catch block
+                                                       e1.printStackTrace();
+                                               }
+                                       }
+                               }
+                               }*/
+                       }
+                       else if (e.getClickCount() == 2)
+                       {
+                               TreePath t = _sideList.getSelectionPath();
+                               if (t!= null)
+                               {
+                                       DefaultMutableTreeNode node = (DefaultMutableTreeNode) t.getLastPathComponent();
+                                       if (node.getUserObject() instanceof FragSeqFileModel)
+                                       {
+                                               if (!_sideList.isExpanded(t))
+                                               {
+                                                       try {
+                                                               _sideList.fireTreeWillExpand(t);
+                                                               _sideList.expandPath(t);
+                                                       } catch (ExpandVetoException e1) {
+                                                               e1.printStackTrace();
+                                                       }
+                                               }
+                                               else 
+                                               {
+                                                       try {
+                                                               _sideList.fireTreeWillCollapse(t);
+                                                               _sideList.collapsePath(t);
+                                                       } catch (ExpandVetoException e1) {
+                                                               e1.printStackTrace();
+                                                       }
+                                               }
+                                       }
+                                       else if (node.getUserObject() instanceof FragSeqModel)
+                                       {
+                                               FragSeqModel model = (FragSeqModel) node.getUserObject();
+                                               
+                                               // Figuring out which panel to add object to...
+                                               int res;
+                                               if (model instanceof FragSeqRNASecStrModel)
+                                               {
+                                                       res = index % (_varnaUpperPanels.getComponentCount()+_varnaLowerPanels.getComponentCount());
+                                               }
+                                               else 
+                                               {
+                                                       res = (index+_varnaUpperPanels.getComponentCount()+_varnaLowerPanels.getComponentCount()-1) % (_varnaUpperPanels.getComponentCount()+_varnaLowerPanels.getComponentCount());
+                                               }
+                                               Component c = null;
+                                               if (res<_varnaUpperPanels.getComponentCount())
+                                               {
+                                                       c = (VARNAHolder)_varnaUpperPanels.getComponent(res);
+                                               }
+                                               else
+                                               {
+                                                       res -= _varnaUpperPanels.getComponentCount();
+                                                       c = (VARNAHolder)_varnaLowerPanels.getComponent(res);
+                                               }
+                                               
+                                               if (c instanceof VARNAHolder)
+                                               {
+                                                       VARNAHolder h = (VARNAHolder) c;
+                                                       if (model instanceof FragSeqRNASecStrModel)
+                                                       {
+                                                               h.setSecStrModel((FragSeqRNASecStrModel)model);
+                                                               index ++;
+                                                       }
+                                                       else if (model instanceof FragSeqAnnotationDataModel)
+                                                       {
+                                                               h.setDataModel((FragSeqAnnotationDataModel)model);
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+               }
+       }
+
+       
+       
+       
+       class VARNAHolder extends JPanel
+       {
+               VARNAPanel vp;
+               FragSeqRNASecStrModel _m;
+               FragSeqAnnotationDataModel _data;
+               JPanel _infoPanel;
+               JTextPane _infoTxt;
+               
+               
+               public VARNAHolder(DropTargetListener f)
+               {
+                       super();
+                       vp = new VARNAPanel();
+                       vp.addFocusListener(new FocusListener(){
+                               public void focusGained(FocusEvent e) {
+                                       //focus(_m);
+                               }
+                               public void focusLost(FocusEvent e) {
+                               }});
+                       vp.setPreferredSize(new Dimension(800, 400));
+
+                       _infoTxt = new JTextPane(); 
+                       _infoTxt.setPreferredSize(new Dimension(200,0));
+                       _infoTxt.setContentType("text/html");
+
+                       JScrollPane scroll = new JScrollPane(_infoTxt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
+
+                       _infoPanel = new JPanel();
+                       _infoPanel.setLayout(new BorderLayout());
+                       _infoPanel.setPreferredSize(new Dimension(200,0));
+                       _infoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
+                       _infoPanel.add(scroll,BorderLayout.CENTER);
+                       _infoPanel.validate();
+
+                       this.setLayout(new BorderLayout());
+                       this.setPreferredSize(new Dimension(300,600));
+                       this.setBorder(BorderFactory.createTitledBorder("None"));                       
+                       this.add(vp, BorderLayout.CENTER);
+                       
+                       DropTarget dt = new DropTarget(vp, f);
+               }
+               
+               VARNAPanel getVARNAPanel()
+               {
+                       return vp;
+               }
+               void setSecStrModel(FragSeqRNASecStrModel m)
+               {
+                       _m = m;
+                       vp.showRNAInterpolated(m.getRNA());
+                       setBorder(BorderFactory.createTitledBorder(m.toString()));
+                       _infoTxt.setText(m.getRNA().getHTMLDescription());
+                       _infoPanel.setBorder(BorderFactory.createTitledBorder("Info ("+_m+")"));
+                       vp.requestFocus();
+               }
+               void setDataModel(FragSeqAnnotationDataModel data)
+               {
+                       _data = data;
+                       data.applyTo(vp.getRNA());
+                       vp.repaint();
+                       vp.requestFocus();
+               }
+               FragSeqModel getModel()
+               {
+                       setBorder(BorderFactory.createTitledBorder(_m.toString()));
+                       return _m;
+               }
+               public void setInfoTxt(String s)
+               {
+                       _infoTxt.setText(vp.getRNA().getHTMLDescription());
+                       _infoTxt.validate();
+               }
+               public JPanel getInfoPane()
+               {
+                       return _infoPanel;
+               }
+               
+       }
+       
+
+       private ArrayList<VARNAHolder> _varnaPanels = new ArrayList<VARNAHolder>(); 
+       
+       private VARNAHolder getHolder(Component vp)
+       {
+               if (vp instanceof VARNAHolder)
+               {
+                       int i= _varnaPanels.indexOf(vp);
+                       if (i!=-1)
+                       {
+                               return _varnaPanels.get(i);
+                       }
+               }
+               if (vp instanceof VARNAPanel)
+               {
+                       for (VARNAHolder vh: _varnaPanels)
+                       {
+                               if (vh.getVARNAPanel()==vp)
+                               return vh;
+                       }
+               }
+               return null;
+       }
+
+
+       
+       public void mouseEntered(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseExited(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragEnter(DropTargetDragEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragExit(DropTargetEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragOver(DropTargetDragEvent arg0) {
+               
+       }
+
+       public void drop(DropTargetDropEvent arg0) {
+                       try {
+                               
+                               DropTarget o = (DropTarget)arg0.getSource();
+                               if (o.getComponent() instanceof VARNAPanel)
+                               {
+                                       VARNAHolder h = getHolder(o.getComponent());
+                                       if (h!=null)
+                                       {
+                                               System.out.println("[X]");
+                                               Transferable t = arg0.getTransferable();
+                                               if (t.isDataFlavorSupported(FragSeqRNASecStrModel.Flavor))
+                                               {
+                                                       Object data = t.getTransferData(FragSeqRNASecStrModel.Flavor);
+                                                       if (data instanceof FragSeqRNASecStrModel)
+                                                       {
+                                                               h.setSecStrModel((FragSeqRNASecStrModel) data);
+                                                       }
+                                               }
+                                               else if (t.isDataFlavorSupported(FragSeqAnnotationDataModel.Flavor))
+                                               {                                                       
+                                                       System.out.println("[Y]");
+                                                       Object data = t.getTransferData(FragSeqAnnotationDataModel.Flavor);
+                                                       if (data instanceof FragSeqAnnotationDataModel)
+                                                       {
+                                                               FragSeqAnnotationDataModel d = (FragSeqAnnotationDataModel) data;
+                                                               h.setDataModel(d);
+                                                       }
+                                               }
+                                       }
+                               }
+                       } catch (UnsupportedFlavorException e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       } catch (IOException e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       } 
+       }
+
+       public void dropActionChanged(DropTargetDragEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowOpened(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowClosing(WindowEvent e) {
+               saveConfig();
+               System.exit(0);
+       }
+
+       public void windowClosed(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowIconified(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowDeiconified(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowActivated(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowDeactivated(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       private void restoreConfig()
+       {
+               BasicINI config = BasicINI.loadINI(_INIFilename);
+       ArrayList<String> vals = config.getItemList("folders");
+               System.out.print("[C]"+vals);
+       
+           for(String path:vals)
+               {
+               System.out.println("Loading folder "+path);
+                 addFolder(path);
+               }
+           _sideList.validate();
+           _listScroller.validate();
+       }
+
+       private void saveConfig()
+       {
+               BasicINI data = new BasicINI();
+               int i=0;
+               for (String folderPath: _treeModel.getFolders())
+               {
+                 data.addItem("folders", "val"+i, folderPath);
+                 i++;
+               }
+               BasicINI.saveINI(data, _INIFilename);
+       }
+
+
+       public void componentResized(ComponentEvent e) {
+               _sideList.validate();
+       }
+
+
+       public void componentMoved(ComponentEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void componentShown(ComponentEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void componentHidden(ComponentEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void actionPerformed(ActionEvent e) {
+               String cmd = e.getActionCommand();
+               System.out.println(cmd);
+               if (cmd.equals(""+Commands.NEW_FOLDER))
+               {
+                       _choice.setDialogTitle("Watch new folder...");
+                       _choice.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+                       _choice.setAcceptAllFileFilterUsed(false);
+                       try {
+                               if (_choice.showOpenDialog(getSelf()) == JFileChooser.APPROVE_OPTION) { 
+                                       addFolder(_choice.getSelectedFile().getCanonicalPath());
+                               }
+                               else {
+                                       System.out.println("No Selection ");
+                               }
+                       } catch (IOException e1) {
+                               e1.printStackTrace();
+                       }
+               }
+               else if (cmd.equals(""+Commands.ADD_PANEL_DOWN))
+               {
+                       addLowerPanel();
+               }
+               else if (cmd.equals(""+Commands.ADD_PANEL_UP))
+               {
+                       addUpperPanel();
+               }
+               else if (cmd.equals(""+Commands.REMOVE_PANEL_DOWN))
+               {
+                       removeLowerPanel();
+               }
+               else if (cmd.equals(""+Commands.REMOVE_PANEL_UP))
+               {
+                       removeUpperPanel();
+               }
+               else if (cmd.equals(""+Commands.SORT_FILENAME))
+               {
+                       _sideList.switchToPath();
+               }
+               else if (cmd.equals(""+Commands.SORT_ID))
+               {
+                       _sideList.switchToID();
+               }
+               else if (cmd.equals(""+Commands.TEST_XML))
+               {
+                       String path = "temp.xml";
+                       VARNAHolder vh = (VARNAHolder) _varnaUpperPanels.getComponent(0);
+                       vh.vp.toXML(path);
+                       try {
+                               FullBackup b = vh.vp.importSession(path);
+                               VARNAHolder vh2 = (VARNAHolder) _varnaUpperPanels.getComponent(1);
+                               vh2.vp.setConfig(b.config);
+                               vh2.vp.showRNAInterpolated(b.rna);
+                               vh2.vp.repaint();
+                       } catch (ExceptionLoadingFailed e1) {
+                               e1.printStackTrace();
+                       }
+               }
+               else if (cmd.equals(""+Commands.CHANGE_LNF))
+               {
+                       try {
+                               
+                               Object o  = _lnf.getModel().getSelectedItem();
+                               System.out.println(o);
+                               UIManager.setLookAndFeel(((LookAndFeelInfo)_lnf.getModel().getSelectedItem()).getClassName());
+                               SwingUtilities.updateComponentTreeUI(this);
+                               this.pack();
+                       } catch (UnsupportedLookAndFeelException e1) {
+                               // TODO Auto-generated catch block
+                               e1.printStackTrace();
+                       } catch (ClassNotFoundException e2) {
+                               // TODO Auto-generated catch block
+                               e2.printStackTrace();
+                       } catch (InstantiationException e3) {
+                               // TODO Auto-generated catch block
+                               e3.printStackTrace();
+                       } catch (IllegalAccessException e4) {
+                               // TODO Auto-generated catch block
+                               e4.printStackTrace();
+                       }
+               }
+               else
+               {
+                       JOptionPane.showMessageDialog(this, "Command '"+cmd+"' not implemented yet.");
+               }
+       }
+
+
+       public void valueChanged(TreeSelectionEvent e) {
+               int[] t = _sideList.getSelectionRows();
+               if (t==null)
+               {
+                       System.out.print("null");
+               }
+               else
+               {
+                       System.out.print("[");
+                       for(int i=0;i<t.length;i++)
+                       {
+                               System.out.print(t[i]+",");
+                       }
+                       System.out.println("]");
+               }
+       }
+
+       
+       public static void main(String[] args) {
+               FragSeqGUI d = new FragSeqGUI();
+               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               d.pack();
+               d.setVisible(true);
+       }
+
+
+}
+
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqModel.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqModel.java
new file mode 100644 (file)
index 0000000..fdb7272
--- /dev/null
@@ -0,0 +1,32 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Date;
+import java.util.regex.Pattern;
+
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public abstract class FragSeqModel implements Comparable<FragSeqModel> {
+
+        public abstract String getID();
+        
+        public int compareTo(FragSeqModel o) {
+                       // TODO Auto-generated method stub
+                       return 0;
+               }
+  
+}
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqNode.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqNode.java
new file mode 100644 (file)
index 0000000..efdd6b0
--- /dev/null
@@ -0,0 +1,17 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import javax.swing.tree.DefaultMutableTreeNode;
+
+public class FragSeqNode extends DefaultMutableTreeNode
+{
+       
+       public FragSeqNode(Object o)
+       {
+               super(o);
+       }
+       
+       public boolean isLeaf()
+       {
+               return (this.getUserObject() instanceof FragSeqModel);
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqRNASecStrModel.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqRNASecStrModel.java
new file mode 100644 (file)
index 0000000..6c3c6f2
--- /dev/null
@@ -0,0 +1,51 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.regex.Pattern;
+
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class FragSeqRNASecStrModel extends FragSeqModel {
+       private RNA _r =null;
+       
+  public FragSeqRNASecStrModel(RNA r)
+  {
+       _r = r;
+  }
+
+
+  public String toString()
+  {
+         return _r.getName();
+  }
+  
+  public String getID()
+  {
+         return _r.getID();
+  }
+  
+
+  public RNA getRNA()
+  {
+         return _r;
+  }
+  public static DataFlavor Flavor = new DataFlavor(FragSeqRNASecStrModel.class, "RNA Sec Str Object");
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqTree.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqTree.java
new file mode 100644 (file)
index 0000000..d9bed27
--- /dev/null
@@ -0,0 +1,108 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.awt.Graphics;
+import java.awt.Rectangle;
+import java.awt.dnd.DragGestureEvent;
+import java.awt.dnd.DragGestureListener;
+import java.awt.dnd.DragGestureRecognizer;
+import java.awt.dnd.DragSource;
+import java.awt.dnd.MouseDragGestureRecognizer;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.util.Enumeration;
+
+import javax.swing.JComponent;
+import javax.swing.JTree;
+import javax.swing.plaf.basic.BasicTreeUI;
+import javax.swing.tree.AbstractLayoutCache;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.TreePath;
+
+public class FragSeqTree extends JTree implements MouseListener {
+       private Watcher _w;
+       
+       
+       public FragSeqTree(FragSeqTreeModel m)
+       {
+               super(m);
+               _w = new Watcher(m ); 
+               _w.start();
+       }
+       
+       public DefaultMutableTreeNode getSelectedNode()
+       {
+               TreePath t = getSelectionPath();
+               if (t!= null)
+               {
+                       return (DefaultMutableTreeNode) t.getLastPathComponent();
+               }
+               return null;
+       }
+
+       public void mouseClicked(MouseEvent e) {
+               int x = e.getX();
+               int y = e.getY();
+               TreePath tp = this.getPathForLocation(x, y);
+               if (tp!=null)
+               {
+                       DefaultMutableTreeNode n = (DefaultMutableTreeNode) tp.getLastPathComponent();
+                       
+               }
+       }
+       
+       public void switchToPath()
+       {
+               FragSeqTreeModel m = (FragSeqTreeModel) getModel();
+               cancelEditing();
+               m.setRoot(m.getPathViewRoot());
+               
+               Enumeration en = m.getRoot().depthFirstEnumeration();
+               while(en.hasMoreElements())
+               {
+                       FragSeqNode n = (FragSeqNode) en.nextElement();
+                       if(m.isExpanded(n))
+                       {
+                               expandPath(new TreePath(n.getPath()));
+                       }
+               }
+       }
+
+       public void switchToID()
+       {
+               FragSeqTreeModel m = (FragSeqTreeModel) getModel();
+               cancelEditing();
+               m.setRoot(m.getIDViewRoot());
+               Enumeration en = m.getRoot().depthFirstEnumeration();
+               while(en.hasMoreElements())
+               {
+                       FragSeqNode n = (FragSeqNode) en.nextElement();
+                       if(m.isExpanded(n))
+                       {
+                               expandPath(new TreePath(n.getPath()));
+                       }
+               }
+       }
+       
+       public void mousePressed(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseReleased(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseEntered(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseExited(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqTreeModel.java b/src2/fr/orsay/lri/varna/applications/fragseq/FragSeqTreeModel.java
new file mode 100644 (file)
index 0000000..6586c04
--- /dev/null
@@ -0,0 +1,256 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.PriorityQueue;
+import java.util.Random;
+import java.util.TreeSet;
+
+import javax.swing.event.TreeExpansionEvent;
+import javax.swing.event.TreeWillExpandListener;
+import javax.swing.tree.DefaultTreeModel;
+import javax.swing.tree.ExpandVetoException;
+import javax.swing.tree.TreeNode;
+import javax.swing.tree.TreePath;
+
+public class FragSeqTreeModel extends DefaultTreeModel implements TreeWillExpandListener{
+       
+         private FragSeqNode _rootIDs = new FragSeqNode("IDs");
+         private FragSeqNode _rootFolders = new FragSeqNode("Folders");
+
+       private TreeSet<String> _folders = new TreeSet<String>();
+  private Hashtable<String,FragSeqNode> _folderPathToFolderNode = new Hashtable<String,FragSeqNode>();
+
+  private Hashtable<String,FragSeqNode> _idsToNode = new Hashtable<String,FragSeqNode>();
+  private Hashtable<String,ArrayList<FragSeqNode>> _pathToIDFileNodes = new Hashtable<String,ArrayList<FragSeqNode>>();
+  
+  public enum SORT_MODE{
+         PATH,
+         ID
+  }
+  
+  private SORT_MODE _mode = SORT_MODE.PATH; 
+       
+  public FragSeqTreeModel()
+  {
+         this(new FragSeqNode("Folders"));  
+         
+  }
+  public FragSeqTreeModel(TreeNode t)
+  {
+         super(t);
+         this.setRoot(_rootFolders);
+  }
+  
+  
+  public FragSeqNode getPathViewRoot()
+  {
+         return _rootFolders;
+  }
+
+  public FragSeqNode getIDViewRoot()
+  {
+         return _rootIDs;
+  }
+
+  public void switchToIDView()
+  {
+         if (_mode!=SORT_MODE.ID)
+         {
+                 this.setRoot(this._rootIDs);
+                 
+         }
+         _mode=SORT_MODE.ID;
+         
+  }
+
+  private void removeAllNodes(ArrayList<FragSeqNode> toBeRemoved)
+  {
+         for(FragSeqNode leafNode : toBeRemoved)
+         {
+                 FragSeqNode parent = (FragSeqNode) leafNode.getParent();
+                 parent.remove(leafNode);
+                 if (parent.getChildCount()==0)
+                 {
+                         parent.removeFromParent();
+                         _folderPathToFolderNode.remove(parent);
+                         if (parent.getUserObject() instanceof String)
+                         {
+                                 String path = parent.getUserObject().toString();
+                         }
+                 }
+                 else
+                 {
+                         reload(parent);
+                 }
+         }       
+  }
+
+  
+  public FragSeqNode getNodeForId(String id)
+  {
+         if(!_idsToNode.containsKey(id))
+         {
+                 FragSeqNode idNode = new FragSeqNode(id);
+                 _idsToNode.put(id, idNode);
+                 _rootIDs.add(idNode);
+         }
+         FragSeqNode idNode = _idsToNode.get(id);
+         return idNode;
+  }
+
+  public void removeFolder(String path)
+  {
+         ArrayList<FragSeqNode> toBeRemoved = new ArrayList<FragSeqNode>(); 
+         Enumeration en = _folderPathToFolderNode.get(path).children();
+         while(en.hasMoreElements())
+         {
+                 FragSeqNode n = (FragSeqNode) en.nextElement();
+                 toBeRemoved.add(n);
+         }
+         removeAllNodes(toBeRemoved);
+         _folders.remove(path);
+  }
+  
+  
+  public FragSeqNode insertGroupNode(String crit, TreeSet<String> t)
+  {
+         FragSeqNode groupNode = new FragSeqNode(crit);
+         FragSeqNode parent = getRoot();
+         int pos = t.headSet(crit).size();
+         parent.insert(groupNode, pos);         
+         reload(groupNode);
+         return groupNode;
+  }
+  
+
+  
+  public void insertFileNode(FragSeqNode parent, FragSeqFileModel m)
+  {
+         FragSeqNode leafNode = new FragSeqNode(m);
+         parent.add(leafNode);
+  }
+
+  public FragSeqNode addFolder(String path)
+  {
+         FragSeqNode groupNode = null;
+         try {
+                 if (!_folders.contains(path))
+                 {
+                         File dir = new File(path);
+                         if (dir.isDirectory())
+                         {
+                                 path = dir.getCanonicalPath();
+                                 _folders.add(path);
+                                 groupNode = insertGroupNode(path, _folders);
+                                 _folderPathToFolderNode.put(path,groupNode);
+                                 for(File f:dir.listFiles(_f))
+                                 {
+                                         addFile(path,f.getCanonicalPath());
+                                 }
+                         }
+                 }
+         } catch (IOException e) {
+                 e.printStackTrace();
+         }
+         return groupNode;
+  }
+    
+  private void addFile(String folder, String path)
+  {
+         System.out.println("  => "+path);
+         FragSeqFileModel m = new FragSeqFileModel(folder,path);
+         addFolder(folder);
+         insertFileNode(_folderPathToFolderNode.get(folder), m);
+  }
+  
+  public FragSeqNode getRoot()
+  {
+         return (FragSeqNode) super.getRoot();
+  }
+  
+  public ArrayList<String> getFolders()
+  {
+         ArrayList<String> result = new ArrayList<String>(_folders);
+         return result;
+  }
+  
+  
+   FilenameFilter _f = new FilenameFilter(){
+               public boolean accept(File dir, String name) {
+                       return name.toLowerCase().endsWith(".dbn") 
+                       || name.toLowerCase().endsWith(".ct")
+                       || name.toLowerCase().endsWith(".bpseq")
+                       || name.toLowerCase().endsWith(".rnaml");       
+               }};
+         
+  public FilenameFilter getFileNameFilter()
+  {
+       return _f;
+  }
+
+  public void setFileNameFilter(FilenameFilter f)
+  {
+       _f = f;
+  }
+
+  
+private Hashtable<FragSeqNode,Boolean> _isExpanded = new Hashtable<FragSeqNode,Boolean>();
+  
+public boolean isExpanded(FragSeqNode n)
+{
+  if(_isExpanded.containsKey(n))
+  {
+       return _isExpanded.get(n);
+  }
+  else
+         return false;
+}
+
+public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
+       if (event.getSource() instanceof FragSeqTree)
+       {
+               FragSeqTree tree = (FragSeqTree) event.getSource();
+               TreePath t = event.getPath();
+               FragSeqNode n = (FragSeqNode) t.getLastPathComponent();
+               _isExpanded.put(n, true);
+               Object o = n.getUserObject();
+               if (o instanceof FragSeqFileModel)
+               {
+                       FragSeqFileModel f = (FragSeqFileModel) o;
+                       if (!f._cached)
+                       {                         
+                               String path = f.getPath();
+                               if (!_pathToIDFileNodes.containsKey(path))
+                               {
+                                       _pathToIDFileNodes.put(path, new ArrayList<FragSeqNode>());
+                               }
+                               ArrayList<FragSeqNode> nodesForID = _pathToIDFileNodes.get(path);
+                               for(FragSeqModel m: f.getModels())
+                               { 
+                                       n.add(new FragSeqNode(m));
+                                       FragSeqNode nid = getNodeForId(m.getID());
+                                       nid.add(new FragSeqNode(m));
+                                       nodesForID.add(nid);
+                               } 
+                       }
+               }
+       }
+}
+
+public void treeWillCollapse(TreeExpansionEvent event)
+               throws ExpandVetoException {
+       // TODO Auto-generated method stub
+       TreePath t = event.getPath();
+       FragSeqNode n = (FragSeqNode) t.getLastPathComponent();
+       _isExpanded.put(n, false);
+       
+       
+}
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/fragseq/Watcher.java b/src2/fr/orsay/lri/varna/applications/fragseq/Watcher.java
new file mode 100644 (file)
index 0000000..443ba27
--- /dev/null
@@ -0,0 +1,47 @@
+package fr.orsay.lri.varna.applications.fragseq;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.ArrayList;
+
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+public class Watcher  extends Thread {
+       
+       private FragSeqTreeModel _model;
+       private boolean _terminated = false; 
+       
+       public Watcher(FragSeqTreeModel model)
+       {
+               _model = model;
+       }
+       
+       public void run() {
+               while (!_terminated)
+               {
+                       ArrayList<String> folders = _model.getFolders();
+                       for (String path: folders)
+                       {
+                         _model.addFolder(path);
+                         System.out.println("Watching ["+path+"]");
+                       }
+                       try {
+                               this.sleep(1000);
+                       } catch (InterruptedException e) {
+                       }
+               }
+               
+       }
+       
+
+
+       
+       
+       public void finish()
+       {
+               _terminated = true;
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUI.java b/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUI.java
new file mode 100644 (file)
index 0000000..26a7334
--- /dev/null
@@ -0,0 +1,750 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.applications.newGUI;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ComponentEvent;
+import java.awt.event.ComponentListener;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.WindowEvent;
+import java.awt.event.WindowListener;
+import java.io.IOException;
+import java.util.ArrayList;
+
+import javax.swing.BorderFactory;
+import javax.swing.ButtonGroup;
+import javax.swing.DefaultListSelectionModel;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTextPane;
+import javax.swing.JToolBar;
+import javax.swing.JTree;
+import javax.swing.ListSelectionModel;
+import javax.swing.TransferHandler;
+import javax.swing.UIManager;
+import javax.swing.UIManager.LookAndFeelInfo;
+import javax.swing.event.TreeModelEvent;
+import javax.swing.event.TreeModelListener;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.TreePath;
+import javax.swing.tree.TreeSelectionModel;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.applications.BasicINI;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+
+
+public class VARNAGUI extends JFrame implements TreeModelListener, MouseListener,DropTargetListener, WindowListener, ComponentListener, ActionListener {
+
+       private enum Commands
+       {
+               NEW_FOLDER,
+               ADD_PANEL_UP,
+               ADD_PANEL_DOWN,
+               REMOVE_PANEL_UP,
+               REMOVE_PANEL_DOWN,
+               SORT_ID,
+               SORT_FILENAME,
+               REFRESH_ALL,
+       };
+       
+       
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -790155708306987257L;
+
+
+               
+       private String _INIFilename = "FragSeqUI.ini";
+       private Color _backgroundColor = Color.white;
+       private boolean redrawOnSlide = false;
+       private int dividerWidth = 5;
+       
+       private JPanel _varnaUpperPanels = new JPanel();
+       private JPanel _varnaLowerPanels = new JPanel();
+
+       private JPanel _listPanel = new JPanel();
+       private JPanel _infoPanel = new JPanel();
+       private VARNAGUITree _sideList = null;
+
+       
+       private VARNAGUITreeModel _treeModel;
+       private JToolBar _toolbar = new JToolBar();
+       private JFileChooser _choice = new JFileChooser();
+       
+       private JScrollPane _listScroller;
+
+       private JList _selectedElems;
+       private JSplitPane _splitLeft;
+       private JSplitPane _splitRight;
+       private JSplitPane _splitVARNA;
+       
+
+
+       public VARNAGUI() {
+               super("VARNA Explorer");
+               RNAPanelDemoInit();
+       }
+
+       
+       private void RNAPanelDemoInit() 
+       {
+               JFrame.setDefaultLookAndFeelDecorated(true);
+               this.addWindowListener(this);
+           
+               _selectedElems = new JList();
+               
+               // Initializing Custom Tree Model
+               _treeModel = new VARNAGUITreeModel();
+               _treeModel.addTreeModelListener(this);
+               
+               _sideList = new VARNAGUITree(_treeModel);
+               _sideList.addMouseListener(this);
+               _sideList.setLargeModel(true);
+               _sideList.setEditable(true);
+               VARNAGUIRenderer renderer = new VARNAGUIRenderer(_sideList,_treeModel);
+               //_sideList.setUI(new CustomTreeUI());
+               _sideList.setCellRenderer(renderer);
+               _sideList.setCellEditor(new VARNAGUICellEditor(_sideList,renderer,_treeModel));
+               TreeSelectionModel m = _sideList.getSelectionModel();
+               m.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
+               _sideList.setSelectionModel(m);
+               _sideList.setShowsRootHandles(true);
+               _sideList.setDragEnabled(true);
+               _sideList.setRootVisible(false);
+               _sideList.setTransferHandler(new TransferHandler(null) 
+               {
+                       public int getSourceActions(JComponent c) {
+                               return COPY_OR_MOVE;
+                       }
+                       protected Transferable createTransferable(JComponent c) {
+                               JTree tree = (JTree) c;
+                               TreePath tp =tree.getSelectionPath();
+                               if (tp!=null)
+                               {
+                                       DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
+                                       if (node.getUserObject() instanceof VARNAGUIModel) {
+                                               return new Transferable(){
+                                                       public DataFlavor[] getTransferDataFlavors() {
+                                                               DataFlavor[] dt = {VARNAGUIModel.Flavor};
+                                                               return dt;
+                                                       }
+                                                       public Object getTransferData(DataFlavor df)
+                                                       throws UnsupportedFlavorException, IOException {
+                                                               if (!isDataFlavorSupported(df))
+                                                                       throw new UnsupportedFlavorException(df);
+                                                               DefaultMutableTreeNode node = (DefaultMutableTreeNode) _sideList.getSelectionPath().getLastPathComponent();
+                                                               return node.getUserObject();
+                                                       }
+                                                       public boolean isDataFlavorSupported(DataFlavor df) {
+                                                               return VARNAGUIModel.Flavor.equals(df);
+                                                       }
+                                               };
+                                       } else {
+                                               return null;
+                                       }
+                               }
+                               return null;
+                       }
+               });
+
+               // Various buttons
+               JButton refreshAllFoldersButton = new JButton("Refresh All");
+               refreshAllFoldersButton.setActionCommand(""+Commands.REFRESH_ALL);
+               refreshAllFoldersButton.addActionListener(this);
+               JButton watchFolderButton = new JButton("Add folder");
+               watchFolderButton.setActionCommand("" +Commands.NEW_FOLDER);
+               watchFolderButton.addActionListener(this);
+               JButton addUpperButton = new JButton("+Up");
+               addUpperButton.setActionCommand(""+Commands.ADD_PANEL_UP);
+               addUpperButton.addActionListener(this);
+               JButton removeUpperButton = new JButton("-Up");
+               removeUpperButton.setActionCommand(""+Commands.REMOVE_PANEL_UP);
+               removeUpperButton.addActionListener(this);
+               JButton addLowerButton = new JButton("+Down");
+               addLowerButton.setActionCommand(""+Commands.ADD_PANEL_DOWN);
+               addLowerButton.addActionListener(this);
+               JButton removeLowerButton = new JButton("-Down");
+               removeLowerButton.setActionCommand(""+Commands.REMOVE_PANEL_DOWN);
+               removeLowerButton.addActionListener(this);
+
+               _toolbar.setFloatable(false);
+               _toolbar.add(refreshAllFoldersButton);
+               _toolbar.addSeparator();
+               _toolbar.add(addUpperButton);
+               _toolbar.add(removeUpperButton);
+               _toolbar.add(addLowerButton);
+               _toolbar.add(removeLowerButton);
+               
+               // Scroller for File tree
+           _listScroller = new JScrollPane(_sideList,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
+           _listScroller.setPreferredSize(new Dimension(300, 200));
+           _listScroller.addComponentListener(this);
+
+               
+               _listPanel.setLayout(new BorderLayout());
+               
+               _listPanel.add(_listScroller,BorderLayout.CENTER);
+               _listPanel.add(_selectedElems,BorderLayout.SOUTH);
+               _listPanel.setBorder(BorderFactory.createTitledBorder("Structures"));
+               _listPanel.setPreferredSize(new Dimension(300, 0));
+               
+               _varnaUpperPanels.setLayout(new GridLayout());
+               _varnaUpperPanels.setPreferredSize(new Dimension(800, 600));
+               
+               _varnaLowerPanels.setLayout(new GridLayout());
+               _varnaLowerPanels.setPreferredSize(new Dimension(800, 000));
+               
+           JRadioButton sortFileName = new JRadioButton("Filename");
+           sortFileName.setActionCommand("sortfilename");
+           sortFileName.setSelected(true);
+           sortFileName.setOpaque(false);
+           sortFileName.setActionCommand(""+Commands.SORT_FILENAME);
+           sortFileName.addActionListener(this);
+           JRadioButton sortID = new JRadioButton("ID");
+           sortID.setActionCommand("sortid");
+           sortID.setOpaque(false);
+           sortID.setActionCommand(""+Commands.SORT_ID);
+           sortID.addActionListener(this);
+
+           ButtonGroup group = new ButtonGroup();
+           group.add(sortFileName);
+           group.add(sortID);
+               
+               JToolBar listTools = new JToolBar();
+               listTools.setFloatable(false);
+               listTools.add(watchFolderButton);
+               listTools.addSeparator();
+           listTools.add(new JLabel("Sort by"));
+               listTools.add(sortFileName);
+               listTools.add(sortID);
+
+               JPanel sidePanel = new JPanel();
+               sidePanel.setLayout(new BorderLayout());
+               sidePanel.add(listTools,BorderLayout.NORTH);
+               sidePanel.add(_listPanel,BorderLayout.CENTER);
+               
+               
+               JPanel mainVARNAPanel = new JPanel();
+               mainVARNAPanel.setLayout(new BorderLayout());
+               _splitVARNA = new JSplitPane(JSplitPane.VERTICAL_SPLIT,redrawOnSlide,_varnaUpperPanels,_varnaLowerPanels);
+               _splitVARNA.setDividerSize(dividerWidth);
+               _splitVARNA.setResizeWeight(1.0);
+               _splitLeft = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,redrawOnSlide,sidePanel,_splitVARNA);
+               _splitLeft.setResizeWeight(0.1);
+               _splitLeft.setDividerSize(dividerWidth);
+               _splitRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,redrawOnSlide,_splitLeft,_infoPanel);
+               _splitRight.setResizeWeight(0.85);
+               _splitRight.setDividerSize(dividerWidth);
+               
+               _infoPanel.setLayout(new GridLayout(0,1));
+               
+               this.restoreConfig();           
+               this.setBackground(_backgroundColor);
+               this.getContentPane().setLayout(new BorderLayout());
+               this.getContentPane().add(_splitRight, BorderLayout.CENTER);
+               this.getContentPane().add(_toolbar, BorderLayout.NORTH);
+               addUpperPanel();
+               this.setVisible(true);
+       }
+       
+       public VARNAGUI getSelf()
+       {
+               return this;
+       }
+       
+       public VARNAHolder createIntegratedPanel(int height)
+       {
+               VARNAHolder vh = new VARNAHolder(this);
+               _varnaPanels.add(vh);
+               return vh;
+       }
+       
+       
+       public void removeUpperPanel()
+       {
+               if (_varnaUpperPanels.getComponentCount()>1)
+               {
+                       VARNAHolder vh = (VARNAHolder) _varnaUpperPanels.getComponent(_varnaUpperPanels.getComponentCount()-1);
+                       _infoPanel.remove(vh.getInfoPane());
+                       _varnaUpperPanels.remove(vh);
+                       _splitLeft.validate();
+                       _splitRight.validate();
+               }
+       }
+
+       public void addUpperPanel()
+       {
+               VARNAHolder vh = createIntegratedPanel(100);
+               _varnaUpperPanels.add(vh);
+               _infoPanel.add(vh.getInfoPane());
+               _splitRight.validate();
+               _splitLeft.validate();
+       }
+
+       
+       public void removeLowerPanel()
+       {
+               if (_varnaLowerPanels.getComponentCount()>0)
+               {
+                       _varnaLowerPanels.remove(_varnaLowerPanels.getComponentCount()-1);
+                       if (_varnaLowerPanels.getComponentCount()==0)
+                       {
+                               _splitVARNA.setDividerLocation(1.0);
+                               _splitVARNA.validate();
+                               _splitVARNA.repaint();
+                       }
+                       _splitLeft.validate();
+               }
+       }
+
+       public void addLowerPanel()
+       {
+               if (_varnaLowerPanels.getComponentCount()==0)
+               {
+                       _splitVARNA.setDividerLocation(0.7);
+                       _splitVARNA.validate();
+               }
+               _varnaLowerPanels.add(createIntegratedPanel(400));
+               _splitLeft.validate();
+       }
+
+       public static void main(String[] args) {
+               try {
+                   for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
+                       if ("Nimbus".equals(info.getName())) {
+                           UIManager.setLookAndFeel(info.getClassName());
+                           break;
+                       }
+                   }
+               } catch (Exception e) {
+                   // If Nimbus is not available, you can set the GUI to another look and feel.
+               }
+               VARNAGUI d = new VARNAGUI();
+               d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               d.pack();
+               d.setVisible(true);
+       }
+
+       public void treeNodesChanged(TreeModelEvent e) {
+              DefaultMutableTreeNode node;
+               node = (DefaultMutableTreeNode)
+                        (e.getTreePath().getLastPathComponent());
+
+               /*
+                * If the event lists children, then the changed
+                * node is the child of the node we have already
+                * gotten.  Otherwise, the changed node and the
+                * specified node are the same.
+                */
+               try {
+                   int index = e.getChildIndices()[0];
+                   node = (DefaultMutableTreeNode)
+                          (node.getChildAt(index));
+               } catch (NullPointerException exc) {}
+
+       }
+       
+       
+
+
+       public void addFolder(String path) {
+               addFolder( path, true); 
+       }
+
+    public void addFolder(String path,
+            boolean shouldBeVisible) 
+    {
+       DefaultMutableTreeNode childNode = _treeModel.addFolder(path);
+       
+               if ((childNode!=null) && shouldBeVisible ) {
+                         System.out.println("  Expanding: "+childNode.getUserObject());
+                         TreePath tp = new TreePath(childNode.getPath());
+                       _sideList.scrollPathToVisible(tp);                      
+                       _sideList.expandRow(_sideList.getRowForPath(tp));
+                       _sideList.updateUI();
+                       _sideList.validate();
+               }
+    }
+
+       public void treeNodesInserted(TreeModelEvent e) {
+               System.out.println(e);
+               
+       }
+
+       public void treeNodesRemoved(TreeModelEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void treeStructureChanged(TreeModelEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseClicked(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mousePressed(MouseEvent e) {
+               
+       }
+
+       int index = 0;
+       
+       public void mouseReleased(MouseEvent e) {
+               // TODO Auto-generated method stub
+               if (e.getSource() == this._sideList)
+               {
+                       if (e.getClickCount() == 2)
+                       {
+                               TreePath t = _sideList.getSelectionPath();
+                               if (t!= null)
+                               {
+                                       DefaultMutableTreeNode node = (DefaultMutableTreeNode) t.getLastPathComponent();
+                                       if (node.getUserObject() instanceof VARNAGUIModel)
+                                       {
+                                               VARNAGUIModel model = (VARNAGUIModel) node.getUserObject();
+                                               int res = index % (_varnaUpperPanels.getComponentCount()+_varnaLowerPanels.getComponentCount());
+                                               Component c = null;
+                                               if (res<_varnaUpperPanels.getComponentCount())
+                                               {
+                                                       c = (VARNAHolder)_varnaUpperPanels.getComponent(res);
+                                               }
+                                               else
+                                               {
+                                                       res -= _varnaUpperPanels.getComponentCount();
+                                                       c = (VARNAHolder)_varnaLowerPanels.getComponent(res);
+                                               }
+                                               if (c instanceof VARNAHolder)
+                                               {
+                                                       VARNAHolder h = (VARNAHolder) c;
+                                                       h.setModel(model);
+                                               }
+                                               index ++;
+                                       }
+                               }
+                       }
+               }
+       }
+
+       
+       
+       
+       class VARNAHolder extends JPanel
+       {
+               VARNAPanel vp;
+               VARNAGUIModel _m;
+               JPanel _infoPanel;
+               JTextPane _infoTxt;
+               public VARNAHolder(DropTargetListener f)
+               {
+                       super();
+                       vp = new VARNAPanel();
+                       vp.addFocusListener(new FocusListener(){
+                               public void focusGained(FocusEvent e) {
+                                       //focus(_m);
+                               }
+                               public void focusLost(FocusEvent e) {
+                               }});
+                       vp.setPreferredSize(new Dimension(800, 400));
+                       vp.setBackground(_backgroundColor);
+
+                       _infoTxt = new JTextPane(); 
+                       _infoTxt.setPreferredSize(new Dimension(200,0));
+                       _infoTxt.setContentType("text/html");
+
+                       JScrollPane scroll = new JScrollPane(_infoTxt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
+
+                       _infoPanel = new JPanel();
+                       _infoPanel.setLayout(new BorderLayout());
+                       _infoPanel.setPreferredSize(new Dimension(200,0));
+                       _infoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
+                       _infoPanel.add(scroll,BorderLayout.CENTER);
+                       _infoPanel.validate();
+
+                       this.setLayout(new BorderLayout());
+                       this.setPreferredSize(new Dimension(300,600));
+                       this.setBorder(BorderFactory.createTitledBorder("None"));                       
+                       this.add(vp, BorderLayout.CENTER);
+                       
+                       DropTarget dt = new DropTarget(vp, f);
+               }
+               
+               VARNAPanel getVARNAPanel()
+               {
+                       return vp;
+               }
+               void setModel(VARNAGUIModel m)
+               {
+                       _m = m;
+                       vp.showRNAInterpolated(m.getRNA());
+                       setBorder(BorderFactory.createTitledBorder(m.toString()));
+                       _infoTxt.setText(m.getRNA().getHTMLDescription());
+                       _infoPanel.setBorder(BorderFactory.createTitledBorder("Info ("+_m+")"));
+                       vp.requestFocus();
+               }
+               VARNAGUIModel getModel()
+               {
+                       setBorder(BorderFactory.createTitledBorder(_m.toString()));
+                       return _m;
+               }
+               public void setInfoTxt(String s)
+               {
+                       _infoTxt.setText(vp.getRNA().getHTMLDescription());
+                       _infoTxt.validate();
+               }
+               public JPanel getInfoPane()
+               {
+                       return _infoPanel;
+               }
+               
+       }
+       
+
+       private ArrayList<VARNAHolder> _varnaPanels = new ArrayList<VARNAHolder>(); 
+       
+       private VARNAHolder getHolder(Component vp)
+       {
+               if (vp instanceof VARNAHolder)
+               {
+                       int i= _varnaPanels.indexOf(vp);
+                       if (i!=-1)
+                       {
+                               return _varnaPanels.get(i);
+                       }
+               }
+               if (vp instanceof VARNAPanel)
+               {
+                       for (VARNAHolder vh: _varnaPanels)
+                       {
+                               if (vh.getVARNAPanel()==vp)
+                               return vh;
+                       }
+               }
+               return null;
+       }
+
+
+       
+       public void mouseEntered(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseExited(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragEnter(DropTargetDragEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragExit(DropTargetEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void dragOver(DropTargetDragEvent arg0) {
+               
+       }
+
+       public void drop(DropTargetDropEvent arg0) {
+                       try {
+                               
+                               DropTarget o = (DropTarget)arg0.getSource();
+                               if (o.getComponent() instanceof VARNAPanel)
+                               {
+                                       VARNAHolder h = getHolder(o.getComponent());
+                                       if (h!=null)
+                                       {
+                                               h.setModel((VARNAGUIModel) arg0.getTransferable().getTransferData(VARNAGUIModel.Flavor));
+                                       }
+                               }
+                       } catch (UnsupportedFlavorException e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       } catch (IOException e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       } 
+       }
+
+       public void dropActionChanged(DropTargetDragEvent arg0) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowOpened(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowClosing(WindowEvent e) {
+               saveConfig();
+               System.exit(0);
+       }
+
+       public void windowClosed(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowIconified(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowDeiconified(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowActivated(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void windowDeactivated(WindowEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       private void restoreConfig()
+       {
+               BasicINI config = BasicINI.loadINI(_INIFilename);
+       ArrayList<String> vals = config.getItemList("folders");
+               System.out.print("[C]"+vals);
+       
+           for(String path:vals)
+               {
+               System.out.println("Loading folder "+path);
+                 addFolder(path);
+               }
+           _sideList.validate();
+           _listScroller.validate();
+       }
+
+       private void saveConfig()
+       {
+               BasicINI data = new BasicINI();
+               int i=0;
+               for (String folderPath: _treeModel.getFolders())
+               {
+                 data.addItem("folders", "val"+i, folderPath);
+                 i++;
+               }
+               BasicINI.saveINI(data, _INIFilename);
+       }
+
+
+       public void componentResized(ComponentEvent e) {
+               _sideList.validate();
+       }
+
+
+       public void componentMoved(ComponentEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void componentShown(ComponentEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void componentHidden(ComponentEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void actionPerformed(ActionEvent e) {
+               String cmd = e.getActionCommand();
+               System.out.println(cmd);
+               if (cmd.equals(""+Commands.NEW_FOLDER))
+               {
+                       _choice.setDialogTitle("Watch new folder...");
+                       _choice.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+                       _choice.setAcceptAllFileFilterUsed(false);
+                       try {
+                               if (_choice.showOpenDialog(getSelf()) == JFileChooser.APPROVE_OPTION) { 
+                                       addFolder(_choice.getSelectedFile().getCanonicalPath());
+                               }
+                               else {
+                                       System.out.println("No Selection ");
+                               }
+                       } catch (IOException e1) {
+                               e1.printStackTrace();
+                       }
+               }
+               else if (cmd.equals(""+Commands.ADD_PANEL_DOWN))
+               {
+                       addLowerPanel();
+               }
+               else if (cmd.equals(""+Commands.ADD_PANEL_UP))
+               {
+                       addUpperPanel();
+               }
+               else if (cmd.equals(""+Commands.REMOVE_PANEL_DOWN))
+               {
+                       removeLowerPanel();
+               }
+               else if (cmd.equals(""+Commands.REMOVE_PANEL_UP))
+               {
+                       removeUpperPanel();
+               }
+               else
+               {
+                       JOptionPane.showMessageDialog(this, "Command '"+cmd+"' not implemented yet.");
+               }
+       }
+}
+
diff --git a/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUICellEditor.java b/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUICellEditor.java
new file mode 100644 (file)
index 0000000..4b1d3b5
--- /dev/null
@@ -0,0 +1,53 @@
+package fr.orsay.lri.varna.applications.newGUI;
+
+import java.awt.Component;
+import java.awt.event.MouseEvent;
+import java.io.File;
+import java.util.EventObject;
+
+import javax.swing.JButton;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTree;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeCellEditor;
+import javax.swing.tree.DefaultTreeCellRenderer;
+
+class VARNAGUICellEditor extends DefaultTreeCellEditor {  
+       
+       VARNAGUITreeModel _m;
+       
+       private VARNAGUIRenderer _base;
+
+    public VARNAGUICellEditor(JTree tree, DefaultTreeCellRenderer renderer, VARNAGUITreeModel m) {
+               super(tree, renderer);
+               _base= new VARNAGUIRenderer(tree,m);
+               _m=m;
+       }
+    
+    
+    public Component getTreeCellEditorComponent(JTree tree,  
+            Object value, boolean sel, boolean expanded, boolean leaf,  
+            int row)  
+    {  
+     
+    JPanel renderer = (JPanel) _base.baseElements(tree,_m,value,sel,expanded,leaf,row,true);
+    return renderer;  
+    }
+
+    public boolean isCellEditable(EventObject evt)
+    {
+        if (evt instanceof MouseEvent) {
+            int clickCount;
+            // For single-click activation
+            clickCount = 1;
+
+            return ((MouseEvent)evt).getClickCount() >= clickCount;
+        }
+        return true;
+
+    }
+
+    
+}  
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUIModel.java b/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUIModel.java
new file mode 100644 (file)
index 0000000..edfd56f
--- /dev/null
@@ -0,0 +1,142 @@
+package fr.orsay.lri.varna.applications.newGUI;
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Date;
+import java.util.regex.Pattern;
+
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VARNAGUIModel implements Comparable<VARNAGUIModel> {
+  private Date _lastModified;
+  private boolean _outOfSync = false;
+  private RNA _r = null;
+  private String _caption = "";
+  private String _path = "";
+  private String _folder = "";
+
+  
+  public static Date lastModif(String path)
+  {
+        return new Date(new File(path).lastModified()) ;
+  }
+  
+  public VARNAGUIModel(String folder, String path)
+  {
+       this(folder,path,lastModif(path));
+  }
+  
+  public VARNAGUIModel(String folder, String path,Date lastModified)
+  {
+         _lastModified = lastModified;
+         _outOfSync = false;
+         _folder =folder;
+         _path = path;
+         String[] s = path.split(Pattern.quote(File.separator));
+         if (s.length>0)
+           _caption = s[s.length-1];
+  }
+  
+  public boolean hasChanged()
+  {
+         return _outOfSync;
+  }
+  
+  public boolean checkForModifications()
+  {
+       if (!lastModif(_path).equals(_lastModified) && !_outOfSync)
+       {
+               _outOfSync = true;
+                 return true;
+       }
+       return false;
+  }
+  
+  
+  public RNA getRNA()
+  {
+         if (_r ==null)
+         {
+                 try {
+                       createRNA();
+               } catch (ExceptionUnmatchedClosingParentheses e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (FileNotFoundException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionExportFailed e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionPermissionDenied e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (ExceptionLoadingFailed e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+         }
+         return _r;
+  }
+  
+  private RNA createRNA() throws ExceptionUnmatchedClosingParentheses, ExceptionFileFormatOrSyntax, FileNotFoundException, ExceptionExportFailed, ExceptionPermissionDenied, ExceptionLoadingFailed
+  {
+         Collection<RNA> r = RNAFactory.loadSecStr(_path);
+         if (r.size()>0)
+         {
+                 _r = r.iterator().next();
+                 _r.drawRNARadiate();
+         }
+         else
+         {
+                 throw new ExceptionFileFormatOrSyntax("No valid RNA defined in this file.");
+         }
+         return _r;
+  }
+  
+  public String toString()
+  {
+         return _caption + (this._outOfSync?"*":"");
+  }
+  
+  public String getID()
+  {
+         return getRNA().getID();
+  }
+  
+  public String getCaption()
+  {
+         return _caption;
+  }
+
+  public String getFolder()
+  {
+         return _folder;
+  }
+
+  public static DataFlavor Flavor = new DataFlavor(VARNAGUIModel.class, "VARNA Object");
+
+
+public int compareTo(VARNAGUIModel o) {
+       return _caption.compareTo(o._caption);
+}
+  
+
+  
+}
diff --git a/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUIRenderer.java b/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUIRenderer.java
new file mode 100644 (file)
index 0000000..9ea6a47
--- /dev/null
@@ -0,0 +1,141 @@
+package fr.orsay.lri.varna.applications.newGUI;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.File;
+
+import javax.swing.BorderFactory;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTree;
+import javax.swing.UIManager;
+import javax.swing.border.Border;
+import javax.swing.plaf.basic.BasicTreeUI;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeCellRenderer;
+
+class VARNAGUIRenderer extends DefaultTreeCellRenderer {  
+          
+       JTree _j;
+       VARNAGUITreeModel _m;
+       
+       private static VARNAGUIRenderer _default = new VARNAGUIRenderer(null,null);
+
+       
+
+       public VARNAGUIRenderer (JTree j, VARNAGUITreeModel m)
+       {
+               _j = j;
+               _m = m;
+       }
+       
+       public JComponent baseElements(JTree tree,VARNAGUITreeModel m,  
+            Object value, boolean sel, boolean expanded, boolean leaf,  
+            int row, boolean hasFocus)
+       {
+               JLabel initValue = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
+        JPanel result = new JPanel();
+        result.setLayout(new BorderLayout());
+        initValue.setBorder(null);
+        if (hasFocus)
+        { 
+               //renderer.setBackground(Color.blue);            
+               result.setBorder(BorderFactory.createLineBorder(Color.blue));
+            result.setBackground(UIManager.getColor("Tree.selectionBackground"));
+            initValue.setOpaque(true);
+        }
+        else
+        {
+               result.setBackground(Color.white);
+               result.setBorder(BorderFactory.createLineBorder(initValue.getBackground()));
+            
+        }
+        DefaultMutableTreeNode t = (DefaultMutableTreeNode)value;
+        Object o = t.getUserObject();
+        if (!( o instanceof VARNAGUIModel))    
+        {  
+            if (expanded)  
+            {  
+               initValue.setIcon(_default.getOpenIcon());  
+            }  
+            else  
+            {  
+               initValue.setIcon(_default.getClosedIcon());  
+            }  
+            result.add(initValue,BorderLayout.WEST);
+               JButton del = new JButton("X");
+               del.addActionListener(new FolderCloses((String)o,tree,m));
+            result.add(del,BorderLayout.EAST);
+        }  
+        else  
+        {  
+               VARNAGUIModel mod = (VARNAGUIModel) o;
+               initValue.setIcon(_default.getLeafIcon());  
+            result.add(initValue,BorderLayout.WEST);
+            if (mod.hasChanged())
+            {
+                 JButton refresh = new JButton("Refresh");
+              result.add(refresh,BorderLayout.EAST);
+            }
+        }
+        return result;
+       }
+       
+    public Component getDefaultTreeCellRendererComponent(JTree tree,  
+            Object value, boolean sel, boolean expanded, boolean leaf,  
+            int row, boolean hasFocus)  
+    {
+      return super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
+    }
+
+       public Component getTreeCellRendererComponent(JTree tree,  
+            Object value, boolean sel, boolean expanded, boolean leaf,  
+            int row, boolean hasFocus)  
+    {
+       
+        return baseElements(tree,_m,value,sel,expanded,leaf,row,hasFocus);  
+    }  
+    public Dimension getPreferredSize(int row) {
+        Dimension size = super.getPreferredSize();
+        size.width = _j.getWidth();
+        System.out.println(size);
+        return size;
+    }
+
+
+//    @Override
+//    public void setBounds(final int x, final int y, final int width, final int height) {
+//    super.setBounds(x, y, Math.min(_j.getWidth()-x, width), height);
+//    }
+    
+    
+    public class FolderCloses implements ActionListener{
+       String _path;
+       JComponent _p;
+       VARNAGUITreeModel _m;
+       
+       public FolderCloses(String path, JComponent p, VARNAGUITreeModel m)
+       {
+               _path = path;
+               _p = p;
+               _m = m;
+       }
+               public void actionPerformed(ActionEvent e) {
+                       if (JOptionPane.showConfirmDialog(_p, "This folder will cease to be watched. Confirm?", "Closing folder", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
+                       {
+                               _m.removeFolder(_path);
+                               System.out.println(_j);
+                               _j.updateUI();
+                       }
+               }
+                   
+    }
+}  
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUITree.java b/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUITree.java
new file mode 100644 (file)
index 0000000..0fd2468
--- /dev/null
@@ -0,0 +1,74 @@
+package fr.orsay.lri.varna.applications.newGUI;
+
+import java.awt.Graphics;
+import java.awt.Rectangle;
+import java.awt.dnd.DragGestureEvent;
+import java.awt.dnd.DragGestureListener;
+import java.awt.dnd.DragGestureRecognizer;
+import java.awt.dnd.DragSource;
+import java.awt.dnd.MouseDragGestureRecognizer;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+
+import javax.swing.JComponent;
+import javax.swing.JTree;
+import javax.swing.plaf.basic.BasicTreeUI;
+import javax.swing.tree.AbstractLayoutCache;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.TreePath;
+
+public class VARNAGUITree extends JTree implements MouseListener {
+       private Watcher _w;
+       
+       
+       public VARNAGUITree(VARNAGUITreeModel m)
+       {
+               super(m);
+               _w = new Watcher(m ); 
+               _w.start();
+       }
+       
+       public DefaultMutableTreeNode getSelectedNode()
+       {
+               TreePath t = getSelectionPath();
+               if (t!= null)
+               {
+                       return (DefaultMutableTreeNode) t.getLastPathComponent();
+               }
+               return null;
+       }
+
+       public void mouseClicked(MouseEvent e) {
+               int x = e.getX();
+               int y = e.getY();
+               TreePath tp = this.getPathForLocation(x, y);
+               if (tp!=null)
+               {
+                       DefaultMutableTreeNode n = (DefaultMutableTreeNode) tp.getLastPathComponent();
+                       
+               }
+       }
+
+       public void mousePressed(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseReleased(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseEntered(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void mouseExited(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUITreeModel.java b/src2/fr/orsay/lri/varna/applications/newGUI/VARNAGUITreeModel.java
new file mode 100644 (file)
index 0000000..e307543
--- /dev/null
@@ -0,0 +1,169 @@
+package fr.orsay.lri.varna.applications.newGUI;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.PriorityQueue;
+import java.util.TreeSet;
+
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeModel;
+import javax.swing.tree.TreePath;
+
+public class VARNAGUITreeModel extends DefaultTreeModel{
+       
+  private TreeSet<String> _folders = new TreeSet<String>();
+  private TreeSet<String> _ids = new TreeSet<String>();
+  private Hashtable<String,TreeSet<VARNAGUIModel>> _criterionToFiles = new Hashtable<String,TreeSet<VARNAGUIModel>>();
+  private Hashtable<String,DefaultMutableTreeNode> _criterionToNodes = new Hashtable<String,DefaultMutableTreeNode>();
+  private ArrayList<DefaultMutableTreeNode> _fileNodes = new ArrayList<DefaultMutableTreeNode>();
+  
+  public enum SORT_MODE{
+         PATH,
+         ID
+  }
+  
+  private SORT_MODE _mode = SORT_MODE.PATH; 
+       
+  public VARNAGUITreeModel()
+  {
+         super(new DefaultMutableTreeNode("Folders"));
+  }
+
+
+  public void removeFolder(String path)
+  {
+         if (_mode==SORT_MODE.PATH)
+         {
+                 int pos = _folders.headSet(path).size();
+                 DefaultMutableTreeNode parent = (DefaultMutableTreeNode) getRoot().getChildAt(pos);
+                 parent.removeAllChildren();
+                 reload(parent);
+                 getRoot().remove(parent);
+                 _criterionToNodes.remove(path);
+                 _criterionToFiles.remove(path);
+         }
+         else if (_mode==SORT_MODE.ID)
+         {
+                 ArrayList<DefaultMutableTreeNode> toBeRemoved = new ArrayList<DefaultMutableTreeNode>(); 
+                 for(DefaultMutableTreeNode leafNode : _fileNodes)
+                 {
+                         VARNAGUIModel m = (VARNAGUIModel)leafNode.getUserObject();
+                         if (m.getFolder().equals(path))
+                         {
+                                 toBeRemoved.add(leafNode);
+                         }
+                 }
+                 for(DefaultMutableTreeNode leafNode : toBeRemoved)
+                 {
+                         _fileNodes.remove(leafNode);
+                         DefaultMutableTreeNode parent = (DefaultMutableTreeNode) leafNode.getParent();
+                         parent.remove(leafNode);
+                 }
+         }
+         _folders.remove(path);
+  }
+  
+  
+  public DefaultMutableTreeNode insertGroupNode(String crit, TreeSet<String> t)
+  {
+         DefaultMutableTreeNode groupNode = new DefaultMutableTreeNode(crit);
+         DefaultMutableTreeNode parent = getRoot();
+         int pos = t.headSet(crit).size();
+         parent.insert(groupNode, pos);         
+         reload(groupNode);
+         return groupNode;
+  }
+
+  public void insertLeafNode(DefaultMutableTreeNode parent, VARNAGUIModel m, TreeSet<VARNAGUIModel> t)
+  {
+         DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode(m);
+         int pos = t.headSet(m).size();
+         parent.insert(leafNode, pos);
+         _fileNodes.add(leafNode);
+  }
+
+  public DefaultMutableTreeNode addFolder(String path)
+  {
+         DefaultMutableTreeNode groupNode = null;
+         try {
+                 if (!_folders.contains(path))
+                 {
+                         System.out.println("Folder: "+path);
+                         File dir = new File(path);
+                         if (dir.isDirectory())
+                         {
+                                 path = dir.getCanonicalPath();
+                                 _folders.add(path);
+                                 if (_mode==SORT_MODE.PATH)
+                                 {
+                                         System.out.println("  Adding: "+path);
+                                         groupNode = insertGroupNode(path, _folders);
+                                         _criterionToNodes.put(path,groupNode);
+                                         _criterionToFiles.put(path, new TreeSet<VARNAGUIModel>());
+                                 }
+                                 for(File f:dir.listFiles(_f))
+                                 {
+                                         addFile(path,f.getCanonicalPath());
+                                 }
+                         }
+                 }
+         } catch (IOException e) {
+                 e.printStackTrace();
+         }
+         return groupNode;
+  }
+    
+  private void addFile(String folder, String path)
+  {
+         System.out.println("  => "+path);
+         VARNAGUIModel m = new VARNAGUIModel(folder,path);
+         if (_mode==SORT_MODE.PATH)
+         {
+                 addFolder(folder);
+                 insertLeafNode(_criterionToNodes.get(folder), m, _criterionToFiles.get(folder));
+         }
+         else if (_mode==SORT_MODE.ID)
+         {
+                 String id = m.getID();
+                 if (!_criterionToNodes.containsKey(id))
+                 {
+                         _criterionToNodes.put(id, insertGroupNode(id, _ids));
+                 }
+                 insertLeafNode(_criterionToNodes.get(id), m, _criterionToFiles.get(id));
+         }
+  }
+  
+  public DefaultMutableTreeNode getRoot()
+  {
+         return (DefaultMutableTreeNode) super.getRoot();
+  }
+  
+  public ArrayList<String> getFolders()
+  {
+         ArrayList<String> result = new ArrayList<String>(_folders);
+         return result;
+  }
+  
+  
+   FilenameFilter _f = new FilenameFilter(){
+               public boolean accept(File dir, String name) {
+                       return name.toLowerCase().endsWith(".dbn") 
+                       || name.toLowerCase().endsWith(".ct")
+                       || name.toLowerCase().endsWith(".bpseq")
+                       || name.toLowerCase().endsWith(".rnaml");       
+               }};
+         
+  public FilenameFilter getFileNameFilter()
+  {
+       return _f;
+  }
+
+  public void setFileNameFilter(FilenameFilter f)
+  {
+       _f = f;
+  }
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/newGUI/Watcher.java b/src2/fr/orsay/lri/varna/applications/newGUI/Watcher.java
new file mode 100644 (file)
index 0000000..563b5a9
--- /dev/null
@@ -0,0 +1,47 @@
+package fr.orsay.lri.varna.applications.newGUI;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.ArrayList;
+
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+public class Watcher  extends Thread {
+       
+       private VARNAGUITreeModel _model;
+       private boolean _terminated = false; 
+       
+       public Watcher(VARNAGUITreeModel model)
+       {
+               _model = model;
+       }
+       
+       public void run() {
+               while (!_terminated)
+               {
+                       ArrayList<String> folders = _model.getFolders();
+                       for (String path: folders)
+                       {
+                         _model.addFolder(path);
+                         System.out.println("Watching ["+path+"]");
+                       }
+                       try {
+                               this.sleep(1000);
+                       } catch (InterruptedException e) {
+                       }
+               }
+               
+       }
+       
+
+
+       
+       
+       public void finish()
+       {
+               _terminated = true;
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/Connection.java b/src2/fr/orsay/lri/varna/applications/templateEditor/Connection.java
new file mode 100644 (file)
index 0000000..56200aa
--- /dev/null
@@ -0,0 +1,23 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+
+
+public class Connection {
+       public GraphicalTemplateElement _h1;
+       public GraphicalTemplateElement.RelativePosition _edge1;
+       public GraphicalTemplateElement _h2;
+       public GraphicalTemplateElement.RelativePosition _edge2;
+       
+       public Connection(GraphicalTemplateElement h1, GraphicalTemplateElement.RelativePosition edge1,GraphicalTemplateElement h2, GraphicalTemplateElement.RelativePosition edge2)
+       {
+               _h1 = h1;
+               _h2 = h2;
+               _edge1 = edge1;
+               _edge2 = edge2;
+       }
+       
+       public boolean equals( Connection c)
+       {
+               return ((_h1==c._h1)&&(_h2==c._h2)&&(_edge1==c._edge1)&&(_edge2==c._edge2));
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/Couple.java b/src2/fr/orsay/lri/varna/applications/templateEditor/Couple.java
new file mode 100644 (file)
index 0000000..2f60b01
--- /dev/null
@@ -0,0 +1,35 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+
+
+public class Couple<T,U> {
+       public T first;
+       public U second;
+       private static final int HASH_PRIME = 1000003;
+    
+       
+       public Couple(T a, U b)
+       {
+               first = a;
+               second = b;
+       }
+
+       public boolean equals( Object c)
+       {
+               if (!(c instanceof Couple))
+               {
+                       return false;
+               }
+               Couple<T,U> cc = (Couple<T,U>) c; 
+               return (cc.first.equals(first) && (cc.second.equals(second)));
+       }
+
+       public int hashCode()
+       {
+               return HASH_PRIME*first.hashCode()+second.hashCode();
+       }
+       
+       public String toString()
+       {
+               return "("+first+","+second+")";
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/GraphicalTemplateElement.java b/src2/fr/orsay/lri/varna/applications/templateEditor/GraphicalTemplateElement.java
new file mode 100644 (file)
index 0000000..7e92960
--- /dev/null
@@ -0,0 +1,254 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics2D;
+import java.awt.Polygon;
+import java.awt.Shape;
+import java.awt.Stroke;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import fr.orsay.lri.varna.exceptions.ExceptionEdgeEndpointAlreadyConnected;
+import fr.orsay.lri.varna.exceptions.ExceptionInvalidRNATemplate;
+import fr.orsay.lri.varna.models.templates.RNATemplate.EdgeEndPointPosition;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement.EdgeEndPoint;
+
+public abstract class GraphicalTemplateElement {
+               
+       public boolean _debug = false;
+    protected HashMap<RelativePosition,Color> _mainColors = new HashMap<RelativePosition,Color>();
+    
+    public Color _dominantColor = new Color(0.5f,0.5f,0.5f,0.9f);
+       
+       public enum RelativePosition {
+               RP_OUTER,RP_INNER_GENERAL,RP_INNER_MOVE,RP_EDIT_START,RP_EDIT_END,RP_CONNECT_START5,RP_CONNECT_START3,RP_CONNECT_END5,RP_CONNECT_END3,
+               RP_EDIT_TANGENT_3,RP_EDIT_TANGENT_5;
+       };
+       
+       static final Color  BACKBONE_COLOR = Color.gray;
+       static final Color  CONTROL_COLOR = Color.decode("#D0D0FF");
+       static final Font  NUMBER_FONT = new Font("Arial", Font.BOLD,18);
+       static final Color NUMBER_COLOR = Color.gray;
+       static final Color  BASE_PAIR_COLOR = Color.blue;
+       static final Color  BASE_COLOR = Color.gray;
+       static final Color  BASE_FILL_COLOR = Color.white;
+       static final Color  BASE_FILL_3_COLOR = Color.red;
+       static final Color  BASE_FILL_5_COLOR = Color.green;
+       static final Color  MAGNET_COLOR = CONTROL_COLOR;
+
+       public void setDominantColor(Color c)
+       {
+               _dominantColor = c;
+       }
+
+       public Color getDominantColor()
+       {
+               return _dominantColor;
+       }
+
+       public abstract RelativePosition getRelativePosition(double x, double y);
+       
+       public abstract void draw(Graphics2D g2d, boolean selected);
+       public abstract Polygon getBoundingPolygon();
+       public abstract void translate(double x, double y);
+       public abstract RelativePosition getClosestEdge(double x, double y);
+       public abstract ArrayList<RelativePosition> getConnectedEdges();
+       public abstract RNATemplateElement getTemplateElement();
+       public void setMainColor(RelativePosition edge,Color c)
+       {
+               _mainColors.put(edge, c);
+       }
+
+       public abstract Shape getArea();
+       
+       public void attach(GraphicalTemplateElement e, RelativePosition edgeOrig, RelativePosition edgeDest) throws ExceptionEdgeEndpointAlreadyConnected, ExceptionInvalidRNATemplate
+       {
+               _attachedElements.put(edgeOrig, new Couple<RelativePosition,GraphicalTemplateElement>(edgeDest,e));
+       }
+       
+       
+       /**
+        * Same as attach(), but without touching the underlying
+        * RNATemplateElement objects.
+        * This is useful if the underlying RNATemplate already contains edges
+        * but not the graphical template.
+        */
+       public void graphicalAttach(GraphicalTemplateElement e, RelativePosition edgeOrig, RelativePosition edgeDest)
+       {
+               _attachedElements.put(edgeOrig, new Couple<RelativePosition,GraphicalTemplateElement>(edgeDest,e));
+       }
+       
+       public void detach(RelativePosition edge)
+       {
+               if (_attachedElements.containsKey(edge))
+               {
+                       Couple<RelativePosition,GraphicalTemplateElement> c = _attachedElements.get(edge);
+                       _attachedElements.remove(edge);
+                       c.second.detach(c.first);
+               }
+       }
+       public Couple<RelativePosition,GraphicalTemplateElement> getAttachedElement(RelativePosition localedge)
+       {
+               if (_attachedElements.containsKey(localedge))
+                       return _attachedElements.get(localedge);
+               return null;
+       }
+       public boolean hasAttachedElement(RelativePosition localedge)
+       {
+               return _attachedElements.containsKey(localedge);
+       }
+       public abstract EdgeEndPoint getEndPoint(RelativePosition r);
+       public abstract boolean isIn(RelativePosition r);
+       
+       public void draw(Graphics2D g2d)
+       {
+               draw(g2d,false);
+       }
+       
+       private HashMap<RelativePosition,Couple<RelativePosition,GraphicalTemplateElement>> _attachedElements = new HashMap<RelativePosition,Couple<RelativePosition,GraphicalTemplateElement>>();
+
+       
+       private Dimension getStringDimension(Graphics2D g, String s) {
+               FontMetrics fm = g.getFontMetrics();
+               Rectangle2D r = fm.getStringBounds(s, g);
+               return (new Dimension((int) r.getWidth(), (int) fm.getAscent()
+                               - fm.getDescent()));
+       }
+
+       
+
+       public void drawStringCentered(Graphics2D g2, String res, double x,
+                       double y) {
+               Dimension d = getStringDimension(g2, res);
+               x -= (double) d.width / 2.0;
+               y += (double) d.height / 2.0;
+               if (_debug)
+                       g2.drawRect((int) x, (int) y - d.height, d.width, d.height);
+               g2.drawString(res, (int) Math.round(x), (int) Math.round(y));
+       }
+       
+       protected Stroke  _boldStroke = new BasicStroke(2.5f, BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND, 3.0f);
+       protected Stroke  _solidStroke = new BasicStroke(1.5f, BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND, 3.0f);
+       private float[] dash = { 5.0f, 5.0f };
+       protected Stroke  _dashedStroke = new BasicStroke(1.5f, BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND, 3.0f, dash, 0);
+       
+       public abstract RelativePosition getConnectedEdge(RelativePosition edge);
+       public abstract Point2D.Double getEdgePosition(RelativePosition edge);
+       public abstract void setEdgePosition(RelativePosition edge, Point2D.Double pos);
+       public abstract RelativePosition relativePositionFromEdgeEndPointPosition(EdgeEndPointPosition endPointPosition);
+       
+       public static boolean canConnect(GraphicalTemplateElement el1, RelativePosition e1,GraphicalTemplateElement el2, RelativePosition e2)
+       {
+               return (!el1.hasAttachedElement(e1))&&(!el2.hasAttachedElement(e2))&&(el1.isIn(e1)!=el2.isIn(e2));
+       }
+
+       
+       protected void drawMove(Graphics2D g2d, Point2D.Double center)
+       {
+               g2d.setStroke(_solidStroke);
+               g2d.setColor(CONTROL_COLOR);
+               g2d.fillOval((int)((center.x-Helix.MOVE_RADIUS)), (int)((center.y-Helix.MOVE_RADIUS)), (int)(2.0*Helix.MOVE_RADIUS), (int)(2.0*Helix.MOVE_RADIUS));
+               g2d.setColor(BACKBONE_COLOR);
+               g2d.drawOval((int)((center.x-Helix.MOVE_RADIUS)), (int)((center.y-Helix.MOVE_RADIUS)), (int)(2.0*Helix.MOVE_RADIUS), (int)(2.0*Helix.MOVE_RADIUS));
+               double arrowLength = Helix.MOVE_RADIUS-2.0;
+               double width = 3.0;
+               drawArrow(g2d,center,new Point2D.Double(center.x+arrowLength,center.y),width);
+               drawArrow(g2d,center,new Point2D.Double(center.x-arrowLength,center.y),width);
+               drawArrow(g2d,center,new Point2D.Double(center.x,center.y+arrowLength),width);
+               drawArrow(g2d,center,new Point2D.Double(center.x,center.y-arrowLength),width);
+       }
+       
+       protected void drawEditStart(Graphics2D g2d, Helix h, double dx,double dy,double nx,double ny)
+       {
+               Point2D.Double center = h.getCenterEditStart();
+               drawEdit(g2d, center, dx,dy,nx,ny);
+       }
+       protected void drawEditEnd(Graphics2D g2d, Helix h, double dx,double dy,double nx,double ny)
+       {
+               Point2D.Double center = h.getCenterEditEnd();
+               drawEdit(g2d, center, dx,dy,nx,ny);
+       }
+
+       protected void drawEdit(Graphics2D g2d, Point2D.Double center, double dx,double dy,double nx,double ny)
+       {
+               g2d.setColor(CONTROL_COLOR);
+               g2d.fillOval((int)((center.x-Helix.EDIT_RADIUS)), (int)((center.y-Helix.EDIT_RADIUS)), (int)(2.0*Helix.EDIT_RADIUS), (int)(2.0*Helix.EDIT_RADIUS));
+               g2d.setColor(BACKBONE_COLOR);
+               g2d.drawOval((int)((center.x-Helix.EDIT_RADIUS)), (int)((center.y-Helix.EDIT_RADIUS)), (int)(2.0*Helix.EDIT_RADIUS), (int)(2.0*Helix.EDIT_RADIUS));
+               double arrowLength = Helix.EDIT_RADIUS-2.0;
+               double width = 3.0;
+               drawArrow(g2d,center,new Point2D.Double(center.x+nx*arrowLength,center.y+ny*arrowLength),width);
+               drawArrow(g2d,center,new Point2D.Double(center.x-nx*arrowLength,center.y-ny*arrowLength),width);
+               drawArrow(g2d,center,new Point2D.Double(center.x+dx*arrowLength,center.y+dy*arrowLength),width);
+               drawArrow(g2d,center,new Point2D.Double(center.x-dx*arrowLength,center.y-dy*arrowLength),width);
+       }
+       
+       protected void drawArrow(Graphics2D g2d, Point2D.Double orig, Point2D.Double dest, double width)
+       {
+               g2d.setStroke(_solidStroke);
+               g2d.drawLine((int)orig.x,(int)orig.y,(int)dest.x,(int)dest.y);
+               double dx = (orig.x-dest.x)/(orig.distance(dest));
+               double dy = (orig.y-dest.y)/(orig.distance(dest));
+               double nx = dy;
+               double ny = -dx;
+               g2d.drawLine((int)dest.x,(int)dest.y,(int)(dest.x-width*(-dx+nx)),(int)(dest.y-width*(-dy+ny)));
+               g2d.drawLine((int)dest.x,(int)dest.y,(int)(dest.x-width*(-dx-nx)),(int)(dest.y-width*(-dy-ny)));
+       }
+
+       
+       
+       protected void drawAnchor(Graphics2D g2d, Point2D.Double p)
+       { drawAnchor(g2d,p,CONTROL_COLOR); }
+
+       protected void drawAnchor5(Graphics2D g2d, Point2D.Double p)
+       { drawAnchor(g2d,p,BASE_FILL_5_COLOR); }
+
+       protected void drawAnchor3(Graphics2D g2d, Point2D.Double p)
+       { drawAnchor(g2d,p,BASE_FILL_3_COLOR); }
+       
+       protected void drawAnchor(Graphics2D g2d, Point2D.Double p, Color c)
+       {
+               g2d.setColor(c);                                
+               g2d.fillOval((int)(p.x-Helix.EDGE_BASE_RADIUS),(int)(p.y-Helix.EDGE_BASE_RADIUS),(int)(2.0*Helix.EDGE_BASE_RADIUS),(int)(2.0*Helix.EDGE_BASE_RADIUS));
+               g2d.setColor(BASE_COLOR);                               
+               g2d.drawOval((int)(p.x-Helix.EDGE_BASE_RADIUS),(int)(p.y-Helix.EDGE_BASE_RADIUS),(int)(2.0*Helix.EDGE_BASE_RADIUS),(int)(2.0*Helix.EDGE_BASE_RADIUS));
+
+       }
+
+       protected void drawMagnet(Graphics2D g2d, Point2D.Double p)
+       {
+               drawAnchor(g2d, p, MAGNET_COLOR);                               
+               g2d.setColor(BASE_COLOR);                               
+               g2d.drawOval((int)(p.x-Helix.EDGE_BASE_RADIUS),(int)(p.y-Helix.EDGE_BASE_RADIUS),(int)(2.0*Helix.EDGE_BASE_RADIUS),(int)(2.0*Helix.EDGE_BASE_RADIUS));
+               g2d.drawOval((int)(p.x-2),(int)(p.y-2),(int)(2.0*2),(int)(2.0*2));
+
+       }
+       
+       
+       
+       protected void drawBase(Graphics2D g2d, Point2D.Double p)
+       {
+               g2d.setColor(BASE_FILL_COLOR);
+               g2d.fillOval((int)(p.x-Helix.BASE_RADIUS),(int)(p.y-Helix.BASE_RADIUS),(int)(2.0*Helix.BASE_RADIUS),(int)(2.0*Helix.BASE_RADIUS));
+               g2d.setColor(BASE_COLOR);
+               g2d.drawOval((int)(p.x-Helix.BASE_RADIUS),(int)(p.y-Helix.BASE_RADIUS),(int)(2.0*Helix.BASE_RADIUS),(int)(2.0*Helix.BASE_RADIUS));
+       }
+
+       public boolean equals(Object b)
+       {
+         if (b instanceof GraphicalTemplateElement)
+         {
+               return b==this;  
+         }
+         else
+                 return false;
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/Helix.java b/src2/fr/orsay/lri/varna/applications/templateEditor/Helix.java
new file mode 100644 (file)
index 0000000..4c81bed
--- /dev/null
@@ -0,0 +1,687 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+
+import java.awt.Graphics2D;
+import java.awt.Polygon;
+import java.awt.Shape;
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import fr.orsay.lri.varna.exceptions.ExceptionInvalidRNATemplate;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.models.templates.RNATemplate;
+import fr.orsay.lri.varna.models.templates.RNATemplate.EdgeEndPointPosition;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateHelix;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement.EdgeEndPoint;
+
+
+public class Helix extends GraphicalTemplateElement{
+       
+  RNATemplateHelix _h;
+  
+  public Helix(double x, double y, RNATemplate tmp, List<GraphicalTemplateElement> existingRNAElements)
+  {
+         this(x,y,getNextAutomaticCaption(existingRNAElements),tmp);
+  }
+  
+  public Helix(double x, double y, String cap, RNATemplate tmp)
+  {
+         _h = tmp.new RNATemplateHelix(cap);
+         _h.setStartPosition(new Point2D.Double(x,y));
+         _h.setEndPosition(new Point2D.Double(x,y));
+         _h.setLength(1);
+         _h.setCaption(cap);
+  }
+  
+  public Helix(RNATemplateHelix templateHelix) {
+         _h = templateHelix;
+  }
+  
+  
+  private static String getNextAutomaticCaption(List<GraphicalTemplateElement> existingRNAElements) {
+         // Find which captions are already used
+         Set<String> captions = new HashSet<String>();
+         for (GraphicalTemplateElement element: existingRNAElements) {
+                 if (element instanceof Helix) {
+                         Helix helix = (Helix) element;
+                         if (helix.getCaption() != null) {
+                                 captions.add(helix.getCaption());
+                         }
+                 }
+         }
+         // Find a non-conflicting name for this helix
+         for (int i=1;;i++) {
+                 String candidateCaption = "H" + i;
+                 if (! captions.contains(candidateCaption)) {
+                         return candidateCaption;
+                 }
+         }
+  }
+  
+  public void toggleFlipped()
+  {
+         _h.setFlipped(!_h.isFlipped());
+         updateAttachedUnpairedRegions();
+  }
+  
+
+  /**
+   * When an helix is moved/resized/etc... it is necessary to update
+   * the positions of endpoints from unpaired regions that are attached
+   * to the helix. This function updates the endpoints positions of
+   * attached unpaired regions.
+   */
+  public void updateAttachedUnpairedRegions() {
+         for (RelativePosition rpos: getConnectedEdges()) {
+                 Couple<RelativePosition,GraphicalTemplateElement> c = getAttachedElement(rpos);
+                 if (c != null && c.second instanceof UnpairedRegion) {
+                         UnpairedRegion unpairedRegion = (UnpairedRegion) c.second;
+                         Point2D.Double pos = getEdgePosition(rpos);
+                         if (c.first == RelativePosition.RP_CONNECT_START5) {
+                                 unpairedRegion.setEdge5(pos);
+                         } else if (c.first == RelativePosition.RP_CONNECT_END3) {
+                                 unpairedRegion.setEdge3(pos);
+                         }
+                 }
+         }
+  }
+
+  public double getPosX()
+  {
+         return _h.getStartPosition().x;
+  }
+
+  public String getCaption()
+  {
+         return _h.getCaption();
+  }
+  
+  public double getPosY()
+  {
+         return _h.getStartPosition().y;
+  }
+  
+  public RNATemplateHelix getTemplateElement()
+  {
+         return _h;
+  }
+
+  public void setX(double x)
+  {
+         _h.getStartPosition().x = x;
+  }
+  
+  public void setY(double y)
+  {
+         _h.getStartPosition().y = y;
+  }
+
+  public void setPos(Point2D.Double p)
+  {
+        _h.setStartPosition(p);
+         updateLength();
+  }
+
+  public void setPos(double x, double y)
+  {
+         setPos(new Point2D.Double(x,y));
+  }
+
+  public Point2D.Double getPos()
+  {
+         return _h.getStartPosition();
+  }
+
+  public void moveCenter(double x, double y)
+  {
+         Point2D.Double center = new Point2D.Double((_h.getStartPosition().x+_h.getEndPosition().x)/2.0,(_h.getStartPosition().y+_h.getEndPosition().y)/2.0);
+         double dx = x-center.x;
+         double dy = y-center.y;
+         _h.setStartPosition(new Point2D.Double(_h.getStartPosition().x+dx,_h.getStartPosition().y+dy));
+         _h.setEndPosition(new Point2D.Double(_h.getEndPosition().x+dx,_h.getEndPosition().y+dy));
+  }
+
+  
+  public void setExtent(double x, double y)
+  {
+        setExtent(new Point2D.Double(x,y));
+  }
+
+  private void updateLength()
+  {
+         _h.setLength(getNbBP());
+  }
+  
+  public void setExtent(Point2D.Double p)
+  {
+        _h.setEndPosition(p);
+         updateLength();
+  }
+
+  public double getExtentX()
+  {
+         return _h.getEndPosition().x;
+  }
+
+  public Point2D.Double getExtent()
+  {
+         return _h.getEndPosition();
+  }
+
+  public double getExtentY()
+  {
+         return _h.getEndPosition().y;
+  }
+  
+       public static final double BASE_PAIR_DISTANCE = RNA.BASE_PAIR_DISTANCE;
+       public static final double LOOP_DISTANCE = RNA.LOOP_DISTANCE;
+       public static final double SELECTION_RADIUS = 15.0;
+       
+       
+       
+
+       public Point2D.Double getAbsStart5()
+       {
+               double dx = (_h.getStartPosition().x-_h.getEndPosition().x)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double dy = (_h.getStartPosition().y-_h.getEndPosition().y)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double nx = dy;
+               double ny = -dx;
+               Point2D.Double start5 = new Point2D.Double((getPosX()-Helix.BASE_PAIR_DISTANCE*nx/2.0),(getPosY()-Helix.BASE_PAIR_DISTANCE*ny/2.0)); 
+               return start5;
+       }
+
+       public Point2D.Double getAbsStart3()
+       {
+               double dx = (_h.getStartPosition().x-_h.getEndPosition().x)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double dy = (_h.getStartPosition().y-_h.getEndPosition().y)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double nx = dy;
+               double ny = -dx;
+               Point2D.Double start3 = new Point2D.Double((getPosX()+Helix.BASE_PAIR_DISTANCE*nx/2.0),(getPosY()+Helix.BASE_PAIR_DISTANCE*ny/2.0)); 
+               return start3;
+       }
+
+       public Point2D.Double getAbsEnd5()
+       {
+               double dx = (_h.getStartPosition().x-_h.getEndPosition().x)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double dy = (_h.getStartPosition().y-_h.getEndPosition().y)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double nx = dy;
+               double ny = -dx;
+               Point2D.Double end5 = new Point2D.Double((getExtentX()-Helix.BASE_PAIR_DISTANCE*nx/2.0),(getExtentY()-Helix.BASE_PAIR_DISTANCE*ny/2.0)); 
+               return end5;
+       }
+
+       public Point2D.Double getAbsEnd3()
+       {
+               double dx = (_h.getStartPosition().x-_h.getEndPosition().x)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double dy = (_h.getStartPosition().y-_h.getEndPosition().y)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double nx = dy;
+               double ny = -dx;
+               Point2D.Double end3 = new Point2D.Double((getExtentX()+Helix.BASE_PAIR_DISTANCE*nx/2.0),(getExtentY()+Helix.BASE_PAIR_DISTANCE*ny/2.0));
+               return end3;
+       }
+       
+       public Point2D.Double getStart5()
+       {
+               if (_h.isFlipped())
+                       return getAbsStart3();
+               else
+                       return getAbsStart5();
+               
+       }
+
+       public Point2D.Double getStart3()
+       {
+               if (_h.isFlipped())
+                       return getAbsStart5();
+               else
+                       return getAbsStart3();
+       }
+
+       public Point2D.Double getEnd5()
+       {
+               if (_h.isFlipped())
+                       return getAbsEnd3();
+               else
+                       return getAbsEnd5();
+       }
+
+       public Point2D.Double getEnd3()
+       {
+               if (_h.isFlipped())
+                       return getAbsEnd5();
+               else
+                       return getAbsEnd3();
+       }
+
+       public Polygon getBoundingPolygon()
+       {
+               double dx = (_h.getStartPosition().x-_h.getEndPosition().x)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double dy = (_h.getStartPosition().y-_h.getEndPosition().y)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double nx = dy;
+               double ny = -dx;
+               Point2D.Double start5 = new Point2D.Double((getPosX()+Helix.BASE_PAIR_DISTANCE*nx/2.0),(getPosY()+Helix.BASE_PAIR_DISTANCE*ny/2.0)); 
+               Point2D.Double end5 = new Point2D.Double((getExtentX()+Helix.BASE_PAIR_DISTANCE*nx/2.0),(getExtentY()+Helix.BASE_PAIR_DISTANCE*ny/2.0)); 
+               Point2D.Double start3 = new Point2D.Double((getPosX()-Helix.BASE_PAIR_DISTANCE*nx/2.0),(getPosY()-Helix.BASE_PAIR_DISTANCE*ny/2.0)); 
+               Point2D.Double end3 = new Point2D.Double((getExtentX()-Helix.BASE_PAIR_DISTANCE*nx/2.0),(getExtentY()-Helix.BASE_PAIR_DISTANCE*ny/2.0));
+               Polygon p = new Polygon();
+               p.addPoint((int)start5.x, (int)start5.y);
+               p.addPoint((int)end5.x, (int)end5.y);
+               p.addPoint((int)end3.x, (int)end3.y);
+               p.addPoint((int)start3.x, (int)start3.y);
+               return p;
+       }
+
+       
+       public Point2D.Double getCenter()
+       {
+               return new Point2D.Double((int)((_h.getStartPosition().x+_h.getEndPosition().x)/2.0),
+                               (int)((_h.getStartPosition().y+_h.getEndPosition().y)/2.0));
+       }
+
+
+       public Point2D.Double getCenterEditStart()
+       {
+               double dist = _h.getStartPosition().distance(_h.getEndPosition());
+               double dx = (_h.getEndPosition().x-_h.getStartPosition().x)/(dist);
+               double dy = (_h.getEndPosition().y-_h.getStartPosition().y)/(dist);
+               return new Point2D.Double((int)(_h.getStartPosition().x+(dist-10.0)*dx),
+                               (int)(_h.getStartPosition().y+(dist-10.0)*dy));
+       }       
+
+       public Point2D.Double getCenterEditEnd()
+       {
+               double dist = _h.getStartPosition().distance(_h.getEndPosition());
+               double dx = (_h.getEndPosition().x-_h.getStartPosition().x)/(dist);
+               double dy = (_h.getEndPosition().y-_h.getStartPosition().y)/(dist);
+               return new Point2D.Double((int)(_h.getStartPosition().x+(10.0)*dx),
+                               (int)(_h.getStartPosition().y+(10.0)*dy));
+       }       
+
+       
+       public Shape getSelectionBox()
+       {
+               double dx = (_h.getStartPosition().x-_h.getEndPosition().x)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double dy = (_h.getStartPosition().y-_h.getEndPosition().y)/(_h.getStartPosition().distance(_h.getEndPosition()));
+               double nx = dy;
+               double ny = -dx;
+               Polygon hbox = getBoundingPolygon();
+               Polygon p = new Polygon();
+               Point2D.Double start5 = new Point2D.Double(hbox.xpoints[0]+SELECTION_RADIUS*(dx+nx),hbox.ypoints[0]+SELECTION_RADIUS*(dy+ny)); 
+               Point2D.Double end5 = new Point2D.Double(hbox.xpoints[1]+SELECTION_RADIUS*(-dx+nx),hbox.ypoints[1]+SELECTION_RADIUS*(-dy+ny)); 
+               Point2D.Double end3  = new Point2D.Double(hbox.xpoints[2]+SELECTION_RADIUS*(-dx-nx),hbox.ypoints[2]+SELECTION_RADIUS*(-dy-ny));;
+               Point2D.Double start3 = new Point2D.Double(hbox.xpoints[3]+SELECTION_RADIUS*(dx-nx),hbox.ypoints[3]+SELECTION_RADIUS*(dy-ny));; 
+               p.addPoint((int)start5.x, (int)start5.y);
+               p.addPoint((int)end5.x, (int)end5.y);
+               p.addPoint((int)end3.x, (int)end3.y);
+               p.addPoint((int)start3.x, (int)start3.y);
+               return p;
+       }
+
+       public Shape getArea()
+       {
+               return getSelectionBox();
+       }
+
+       
+       public static final double EDIT_RADIUS = 10.0;
+       public static final double MOVE_RADIUS = 13.0;
+       public static final double BASE_RADIUS = 8.0;
+       public static final double EDGE_BASE_RADIUS = 7.0;
+       
+       
+       public RelativePosition getRelativePosition(double x, double y)
+       {
+               Point2D.Double current = new Point2D.Double(x,y);
+               Shape p = getSelectionBox();
+               if (p.contains(current))
+               {
+                       if (getCenterEditStart().distance(current)<EDIT_RADIUS)
+                       {
+                               return RelativePosition.RP_EDIT_START;
+                       }
+                       else if (getCenterEditEnd().distance(current)<EDIT_RADIUS)
+                       {
+                               return RelativePosition.RP_EDIT_END;
+                       }
+                       else if (getCenter().distance(current)<MOVE_RADIUS)
+                       {
+                               return RelativePosition.RP_INNER_MOVE;
+                       }
+                       else if (getEnd3().distance(current)<EDGE_BASE_RADIUS)
+                       {
+                               return RelativePosition.RP_CONNECT_END3;
+                       }
+                       else if (getEnd5().distance(current)<EDGE_BASE_RADIUS)
+                       {
+                               return RelativePosition.RP_CONNECT_END5;
+                       }
+                       else if (getStart3().distance(current)<EDGE_BASE_RADIUS)
+                       {
+                               return RelativePosition.RP_CONNECT_START3;
+                       }
+                       else if (getStart5().distance(current)<EDGE_BASE_RADIUS)
+                       {
+                               return RelativePosition.RP_CONNECT_START5;
+                       }
+                               
+                       return RelativePosition.RP_INNER_GENERAL;
+               }
+               else 
+                       return RelativePosition.RP_OUTER;  
+       }
+
+       public RelativePosition getClosestEdge(double x, double y)
+       {
+               RelativePosition result = RelativePosition.RP_OUTER;
+               double dist = Double.MAX_VALUE;
+               Point2D.Double current = new Point2D.Double(x,y);
+               double dcand = getStart5().distance(current);
+           if (dcand<dist)
+           {
+               dist = dcand;
+               result = RelativePosition.RP_CONNECT_START5;
+           }
+               dcand = getStart3().distance(current);
+           if (dcand<dist)
+           {
+               dist = dcand;
+               result = RelativePosition.RP_CONNECT_START3;
+           }
+               dcand = getEnd5().distance(current);
+           if (dcand<dist)
+           {
+               dist = dcand;
+               result = RelativePosition.RP_CONNECT_END5;
+           }
+               dcand = getEnd3().distance(current);
+           if (dcand<dist)
+           {
+               dist = dcand;
+               result = RelativePosition.RP_CONNECT_END3;
+           }
+               return result;
+       }
+       
+       public Point2D.Double getEdgePosition(Helix.RelativePosition edge)
+       {
+               switch (edge)
+               {
+                       case RP_CONNECT_END3:
+                               return getEnd3();
+                       case RP_CONNECT_END5:
+                               return getEnd5();
+                       case RP_CONNECT_START5:
+                               return getStart5();
+                       case RP_CONNECT_START3:
+                               return getStart3();
+                       case RP_EDIT_START:
+                               return getPos();
+                       case RP_EDIT_END:
+                               return  getExtent();
+                       case RP_INNER_MOVE:
+                               return  getCenter();
+               }
+               return getCenter();
+       }
+
+       public RelativePosition getConnectedEdge(RelativePosition edge)
+       {
+               switch (edge)
+               {
+                       case RP_CONNECT_END3:
+                               return RelativePosition.RP_CONNECT_START3;
+                       case RP_CONNECT_END5:
+                               return RelativePosition.RP_CONNECT_START5;
+                       case RP_CONNECT_START5:
+                               return RelativePosition.RP_CONNECT_END5;
+                       case RP_CONNECT_START3:
+                               return RelativePosition.RP_CONNECT_END3;
+               }
+               return RelativePosition.RP_OUTER;
+       }
+       
+       public boolean isAnchored5Start()
+       {
+               return (_h.getIn1().getOtherElement()!=null);
+       }
+
+       public boolean isAnchored5End()
+       {
+               return (_h.getOut1().getOtherElement()!=null);
+       }
+       
+       public boolean isAnchored3Start()
+       {
+               return (_h.getOut2().getOtherElement()!=null);
+       }
+
+       public boolean isAnchored3End()
+       {
+               return (_h.getIn2().getOtherElement()!=null);
+       }
+       
+       public int getNbBP()
+       {
+               Point2D.Double pos = getPos();
+               Point2D.Double extent = getExtent();
+               double helLength =  pos.distance(extent);
+               return Math.max((int)Math.round(helLength/Helix.LOOP_DISTANCE) + 1, 2);
+       }
+       
+       public void draw(Graphics2D g2d,boolean isSelected)
+       {
+               g2d.setStroke(_solidStroke);
+               Point2D.Double pos = getPos();
+               Point2D.Double extent = getExtent();
+               double dx = (pos.x-extent.x)/pos.distance(extent);
+               double dy = (pos.y-extent.y)/pos.distance(extent);
+               double nx = Helix.BASE_PAIR_DISTANCE*dy/2.0;
+               double ny = -Helix.BASE_PAIR_DISTANCE*dx/2.0;
+               Point2D.Double start5 = getStart5(); 
+               Point2D.Double end5 = getEnd5(); 
+               Point2D.Double start3 = getStart3(); 
+               Point2D.Double end3 = getEnd3();
+               
+               for (RelativePosition e:this.getConnectedEdges())
+               {
+                       g2d.setStroke(_solidStroke);
+                       g2d.setColor(BACKBONE_COLOR);
+                       Point2D.Double p1 = this.getEdgePosition(e);
+                       Point2D.Double p2 = this.getEdgePosition(getConnectedEdge(e));
+                       if (_mainColors.containsKey(e))
+                       { 
+                               g2d.setColor(_mainColors.get(e));
+                               g2d.setStroke(this._boldStroke);
+                       }
+                       g2d.drawLine((int)p1.x,(int)p1.y,(int)(p1.x+p2.x)/2,(int)(p1.y+p2.y)/2);
+               }
+
+               g2d.setColor(NUMBER_COLOR);
+               double captionx = (_h.isFlipped()?-1.0:1.0)*1.5*nx+(start3.x+end3.x)/2.0;
+               double captiony = (_h.isFlipped()?-1.0:1.0)*1.5*ny+(start3.y+end3.y)/2.0;
+               drawStringCentered(g2d, getCaption(),captionx,captiony);
+
+               int nbBasePairs = _h.getLength();
+
+               g2d.setStroke(_solidStroke);
+
+               for (int i=0;i<nbBasePairs;i++)
+               {
+                       g2d.setColor(BASE_PAIR_COLOR);
+                       Point2D.Double p5 = new Point2D.Double(
+                                       (i*start5.x+(nbBasePairs-1-i)*end5.x)/(nbBasePairs-1),
+                                       (i*start5.y+(nbBasePairs-1-i)*end5.y)/(nbBasePairs-1));
+                       Point2D.Double p3 = new Point2D.Double(
+                                       (i*start3.x+(nbBasePairs-1-i)*end3.x)/(nbBasePairs-1),
+                                       (i*start3.y+(nbBasePairs-1-i)*end3.y)/(nbBasePairs-1));
+                       g2d.drawLine((int)p3.x,(int)p3.y,(int)p5.x,(int)p5.y);
+                       if (i==0)
+                       {
+                               if (isAnchored5End())
+                               { drawMagnet(g2d, p5); }
+                               else
+                               { drawAnchor3(g2d, p5); }
+                               
+                               if (isAnchored3End())
+                               { drawMagnet(g2d, p3); }
+                               else
+                               { drawAnchor5(g2d, p3); }
+                       }
+                       else if (i==nbBasePairs-1)
+                       {
+                               if (isAnchored5Start())
+                               { drawMagnet(g2d, p5); }
+                               else
+                               { drawAnchor5(g2d, p5); }
+                               
+                               if (isAnchored3Start())
+                               { drawMagnet(g2d, p3); }
+                               else
+                               { drawAnchor3(g2d, p3); }
+                       }
+                       else
+                       {
+                               drawBase(g2d, p3);
+                               drawBase(g2d, p5);
+                       }
+               }
+
+               if (isSelected)
+               {
+                       nx = dy;
+                       ny = -dx;
+                       Shape p = getSelectionBox();
+                       g2d.setColor(BACKBONE_COLOR);
+                       g2d.setStroke(_dashedStroke);
+                       g2d.draw(p);
+                       Point2D.Double center = getCenter();
+                       g2d.setStroke(_solidStroke);
+                       drawMove(g2d,center);
+                       drawEditStart(g2d,this,-dx,-dy,nx,ny);                  
+                       drawEditEnd(g2d,this,-dx,-dy,nx,ny);                    
+               }
+       }
+
+
+       public void translate(double x, double y) {
+                 Point2D.Double pos = getPos();
+                 Point2D.Double extent = getExtent();
+                 setPos(pos.x+x,pos.y+y);
+                 setExtent(extent.x+x,extent.y+y);
+       }
+
+       public RNATemplateHelix getHelix() {
+               return _h;
+       }
+       
+
+       public EdgeEndPoint getEndPoint(RelativePosition r) {
+               switch(r)
+               {
+                       case RP_CONNECT_START5:
+                       return _h.getIn1();                             
+                       case RP_CONNECT_START3:
+                       return _h.getOut2();                            
+                       case RP_CONNECT_END3:
+                               return _h.getIn2();
+                       case RP_CONNECT_END5:
+                               return _h.getOut1();
+               }
+               return null;
+       }
+
+       public boolean isIn(RelativePosition r) {
+               switch(r)
+               {
+               case RP_CONNECT_START5:
+                       return true;                            
+               case RP_CONNECT_START3:
+                       return false;                           
+               case RP_CONNECT_END3:
+                       return true;
+               case RP_CONNECT_END5:
+                       return false;
+               }
+               return true;
+       }
+       
+       
+       public void attach(GraphicalTemplateElement e, RelativePosition edgeOrig, RelativePosition edgeDest) throws ExceptionInvalidRNATemplate
+       {
+               super.attach(e,edgeOrig,edgeDest);
+               EdgeEndPoint e1 = this.getEndPoint(edgeOrig);
+               EdgeEndPoint e2 = e.getEndPoint(edgeDest);
+               boolean parity1 = this.isIn(edgeOrig);
+               boolean parity2 = e.isIn(edgeDest);
+               if ((e1!=null)&&(e2!=null)&&(parity1!=parity2))
+               {
+                  e1.disconnect();
+                  e2.disconnect();
+                  e1.connectTo(e2);
+               }
+       }
+       
+
+
+       public void detach(RelativePosition edge)
+       {
+               // If the underlying template element is still connected, disconnect it
+               if (getEndPoint(edge).isConnected())
+               {
+                       getEndPoint(edge).disconnect();
+               }
+               
+               // Call the parent class detach function, which will also take care to disconnect this other endpoint of this edge
+               super.detach(edge);
+       }
+
+       public void setEdgePosition(RelativePosition edge, java.awt.geom.Point2D.Double pos) {
+               switch (edge)
+               {
+                       case RP_EDIT_START:
+                               setPos(pos);
+                               break;
+                       case RP_EDIT_END:
+                               setExtent(pos);
+                               break;
+                       case RP_INNER_MOVE:
+                               moveCenter(pos.x,pos.y);
+                               break;
+               }
+               updateAttachedUnpairedRegions();
+       }
+
+       public ArrayList<RelativePosition> getConnectedEdges() {
+               ArrayList<RelativePosition> result = new ArrayList<RelativePosition>();
+               result.add(RelativePosition.RP_CONNECT_START5);
+               result.add(RelativePosition.RP_CONNECT_START3);
+               result.add(RelativePosition.RP_CONNECT_END5);
+               result.add(RelativePosition.RP_CONNECT_END3);
+               return result;
+       }
+       
+       public String toString()
+       {
+               return "Helix " + getCaption();
+       }
+
+       public RelativePosition relativePositionFromEdgeEndPointPosition(
+                       EdgeEndPointPosition pos) {
+               switch (pos) {
+               case IN1:
+                       return RelativePosition.RP_CONNECT_START5;
+               case OUT1:
+                       return RelativePosition.RP_CONNECT_END5;
+               case IN2:
+                       return RelativePosition.RP_CONNECT_END3;
+               case OUT2:
+                       return RelativePosition.RP_CONNECT_START3;
+               default:
+                       return null;
+               }
+       }
+
+}
+
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/MouseControler.java b/src2/fr/orsay/lri/varna/applications/templateEditor/MouseControler.java
new file mode 100644 (file)
index 0000000..5eb3e5d
--- /dev/null
@@ -0,0 +1,345 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+
+import java.awt.Point;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.awt.event.MouseWheelEvent;
+import java.awt.event.MouseWheelListener;
+import java.awt.geom.Point2D;
+
+
+
+public class MouseControler implements MouseListener, MouseMotionListener, MouseWheelListener {
+
+       private int _granularity = 8;
+       private final int HYSTERESIS_DISTANCE = 10;
+       TemplatePanel _sp;
+       GraphicalTemplateElement _elem;
+       TemplateEditorPanelUI _ui;
+       private GraphicalTemplateElement.RelativePosition _currentMode = Helix.RelativePosition.RP_OUTER;
+       private boolean movingView = false;
+       private Point2D.Double _clickedPos = new Point2D.Double();
+       private Point _clickedPosScreen = new Point();
+
+       public MouseControler(TemplatePanel sp, TemplateEditorPanelUI ui)
+       {
+               _sp = sp;
+               _elem = null;
+               _ui = ui;
+       }
+
+       public void mouseWheelMoved(MouseWheelEvent e) {
+               if (e.getWheelRotation() == -1) {
+                       _sp.zoomIn();
+               }
+               else {
+                       _sp.zoomOut();
+               }
+               e.consume();
+       }
+
+
+       public void mouseClicked(MouseEvent arg0) {
+       }
+
+       public void mouseEntered(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+
+       }
+
+       public void mouseExited(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+
+       }
+
+
+       
+       /**
+        * Get mouse position in logical coordinates, ie. those used in the template XML file.
+        * It differs from the screen coordinates relative to panel because of the scaling factor.
+        */
+       public Point2D.Double getLogicalMouseCoords(MouseEvent event) {
+               return new Point2D.Double(event.getX()/_sp.getScaleFactor(), event.getY()/_sp.getScaleFactor());
+       }
+
+       public void mousePressed(MouseEvent arg0) {
+               movingView = false;
+               _clickedPos = new Point2D.Double(arg0.getX(), arg0.getY());
+               _clickedPosScreen.x = arg0.getXOnScreen();
+               _clickedPosScreen.y = arg0.getYOnScreen();
+               
+               // middle-click
+               if (arg0.getButton() == MouseEvent.BUTTON2) {
+                       movingView = true;
+                       
+               } else {
+                       
+                       Point2D.Double logicalMousePos = getLogicalMouseCoords(arg0);
+                       GraphicalTemplateElement elem = _sp.getElementAt(logicalMousePos.getX(), logicalMousePos.getY());
+                       _sp.Unselect();
+                       
+                       if (elem==null)
+                       {
+                               if (arg0.getButton()==MouseEvent.BUTTON1
+                                               && _ui.getSelectedTool() == TemplateEditorPanelUI.Tool.CREATE_HELIX)
+                               {
+                                       _currentMode = Helix.RelativePosition.RP_EDIT_START;
+                               }
+                               else if ((arg0.getButton()==MouseEvent.BUTTON1
+                                               && _ui.getSelectedTool() == TemplateEditorPanelUI.Tool.CREATE_UNPAIRED))
+                               {
+                                       // Create a new unpaired region
+                                       UnpairedRegion n = new UnpairedRegion(logicalMousePos.getX(),logicalMousePos.getY(),_sp.getTemplate());
+                                       n.setDominantColor(_sp.nextBackgroundColor());
+                                       _ui.addElementUI(n);
+                                       _sp.setSelected(n);
+                                       _sp.repaint();
+                                       _elem = n;
+                                       _currentMode = GraphicalTemplateElement.RelativePosition.RP_EDIT_START;
+                               }
+                       }
+                       else if (arg0.getButton()==MouseEvent.BUTTON1) 
+                       {
+                               _currentMode = elem.getRelativePosition(logicalMousePos.getX(), logicalMousePos.getY());
+                               _sp.setSelected(elem);
+                               _elem = elem;
+                               switch (_currentMode)
+                               {
+                               case RP_EDIT_START:
+                               case RP_EDIT_END:
+                               case RP_EDIT_TANGENT_5:
+                               case RP_EDIT_TANGENT_3:
+                                       break;
+                               case RP_INNER_MOVE:
+                                       break;
+                               case RP_INNER_GENERAL:
+                                       _currentMode = Helix.RelativePosition.RP_INNER_MOVE; 
+                                       break;
+                               case RP_CONNECT_END3:
+                               case RP_CONNECT_END5:
+                               case RP_CONNECT_START5:
+                               case RP_CONNECT_START3:
+                               {
+                                       Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> al = _sp.getPartner(elem, _currentMode);
+                                       boolean isConnected = (al!=null); 
+                                       if (isConnected)
+                                       {
+                                               Connection c = _sp.getConnection(elem, _currentMode);
+                                               _ui.removeConnectionUI(c);
+                                               GraphicalTemplateElement p1 = c._h1;
+                                               GraphicalTemplateElement p2 = c._h2;
+                                               boolean p1IsHelix = (p1 instanceof Helix);
+                                               boolean p1IsUnpaired = (p1 instanceof UnpairedRegion);
+                                               boolean p2IsHelix = (p2 instanceof Helix);
+                                               boolean p2IsUnpaired = (p2 instanceof UnpairedRegion);
+                                               boolean p1StillAttached = (p1 == elem);
+       
+                                               if ((p1IsUnpaired && p2IsHelix))
+                                               {
+                                                       p1StillAttached = false;
+                                               }
+                                               if (p1StillAttached)
+                                               { 
+                                                       _elem = p2;
+                                                       _currentMode = c._edge2;
+                                               }
+                                               else if (!p1StillAttached)
+                                               { 
+                                                       _elem=p1;
+                                                       _currentMode = c._edge1;
+                                               }
+       
+                                       }
+                                       if (_elem instanceof Helix)
+                                       { 
+                                               _sp.setPointerPos(new Point2D.Double(logicalMousePos.getX(),logicalMousePos.getY()));
+                                               _sp.setSelectedEdge(_currentMode);
+                                       }
+                                       _sp.setSelected(_elem);
+                               }
+                               break;
+                               case RP_OUTER:
+                                       _sp.Unselect();
+                                       _elem = null;
+                               }
+                               _sp.repaint();
+                       }
+               }
+       }
+
+       public void mouseReleased(MouseEvent arg0) {
+               movingView = false;
+               Point2D.Double logicalMousePos = getLogicalMouseCoords(arg0);
+               if (_elem!=null)
+               {
+                       switch (_currentMode)
+                       {
+                       case RP_EDIT_START:
+                       case RP_EDIT_END:
+                       {
+                               if (_elem instanceof Helix)
+                               {
+                                       Helix h = (Helix) _elem;
+                                       if (h.getPos().distance(h.getExtent())<10.0)
+                                       {
+                                               _ui.removeElementUI(_elem);
+                                               _sp.Unselect();
+                                       }
+                               }
+                       }
+                       break;
+                       case RP_INNER_MOVE:
+                               break;
+                       case RP_CONNECT_END3:
+                       case RP_CONNECT_END5:
+                       case RP_CONNECT_START5:
+                       case RP_CONNECT_START3:
+                       {
+                               GraphicalTemplateElement t = _sp.getElementAt(logicalMousePos.getX(), logicalMousePos.getY(),_elem);
+                               if (t!=null)
+                               {
+                                       GraphicalTemplateElement.RelativePosition edge = t.getClosestEdge(logicalMousePos.getX(), logicalMousePos.getY());
+                                       _ui.addConnectionUI(_elem,_currentMode,t,edge);
+                               }
+                               _sp.setSelectedEdge(Helix.RelativePosition.RP_OUTER);
+                       }
+                       break;
+                       }
+                       _elem = null;           
+                       _sp.rescale();
+               }
+               _sp.setSelectedEdge(Helix.RelativePosition.RP_OUTER);
+               _currentMode = Helix.RelativePosition.RP_OUTER;
+               _sp.repaint();
+       }
+
+
+       private Point2D.Double projectPoint(double x, double y, Point2D.Double ref)
+       {
+               Point2D.Double result = new Point2D.Double();
+               double nx = x-ref.x;
+               double ny = y-ref.y;
+               double tmp = Double.MIN_VALUE;
+               for (int i=0;i<this._granularity;i++)
+               {
+                       double angle = 2.0*Math.PI*((double)i/(double)_granularity);
+                       double dx = Math.cos(angle);
+                       double dy = Math.sin(angle);
+                       double norm  = nx*dx+ny*dy;
+                       //System.out.println(""+angle+" "+norm);
+                       if (norm > tmp)
+                       {
+                               tmp = norm;
+                               result.x = ref.x+dx*norm;
+                               result.y = ref.y+dy*norm;
+                       }
+               }
+               return result;
+       }
+
+       public void mouseDragged(MouseEvent arg0) 
+       {
+               if (movingView) {
+                       Point trans = new Point(
+                                       arg0.getXOnScreen() - _clickedPosScreen.x,
+                                       arg0.getYOnScreen() - _clickedPosScreen.y);
+                       _sp.translateView(trans);
+                       _clickedPosScreen.x = arg0.getXOnScreen();
+                       _clickedPosScreen.y = arg0.getYOnScreen();
+               } else {
+                       Point2D.Double logicalMousePos = getLogicalMouseCoords(arg0);
+                       if (_elem == null)
+                       {
+                               switch (_currentMode)
+                               {
+                               case RP_EDIT_START:
+                               {
+                                       if (_clickedPos.distance(arg0.getX(),arg0.getY())>HYSTERESIS_DISTANCE)
+                                       {
+                                               System.out.println("Creating Helix...");
+                                               Helix h1 = new Helix(logicalMousePos.getX(),logicalMousePos.getY(),_sp.getTemplate(),_sp.getRNAComponents());
+                                               h1.setDominantColor(_sp.nextBackgroundColor());
+                                               _ui.addElementUI(h1);
+                                               _sp.setSelected(h1);
+                                               _sp.repaint();
+                                               _elem = h1;
+                                       }
+                               }
+                               break;
+       
+                               }
+                       }
+                       else
+                       {
+                               if (_elem instanceof Helix)
+                               {
+                                       Helix h = (Helix) _elem;
+                                       switch (_currentMode)
+                                       {
+                                       case RP_EDIT_START:
+                                       {
+                                               Point2D.Double d = projectPoint(logicalMousePos.getX(),logicalMousePos.getY(),h.getPos());
+                                               _ui.setHelixExtentUI(h, d.x,d.y);
+                                       }
+                                       break;
+                                       case RP_EDIT_END:
+                                       {
+                                               Point2D.Double d = projectPoint( logicalMousePos.getX(),logicalMousePos.getY(),h.getExtent());
+                                               _ui.setHelixPosUI(h, d.x,d.y);
+                                       }
+                                       break;
+                                       case RP_INNER_MOVE:
+                                               _ui.moveHelixUI(h, logicalMousePos.getX(),logicalMousePos.getY());
+                                               break;
+                                       case RP_CONNECT_END3:
+                                       case RP_CONNECT_END5:
+                                       case RP_CONNECT_START5:
+                                       case RP_CONNECT_START3:
+                                               _sp.setPointerPos(new Point2D.Double(logicalMousePos.getX(),logicalMousePos.getY()));
+                                               _sp.repaint();                          
+                                               break;
+                                       }
+                               }
+                               else if (_elem instanceof UnpairedRegion)
+                               {
+                                       UnpairedRegion ur = (UnpairedRegion) _elem;
+                                       Point2D.Double p = new Point2D.Double(logicalMousePos.getX(),logicalMousePos.getY());
+                                       switch (_currentMode)
+                                       {
+                                       case RP_EDIT_TANGENT_5:
+                                       {
+                                               _ui.setEdge5TangentUI(ur,logicalMousePos.getX(),logicalMousePos.getY());
+                                               _sp.repaint();
+                                               break;
+                                       }
+                                       case RP_EDIT_TANGENT_3:
+                                       {
+                                               _ui.setEdge3TangentUI(ur,logicalMousePos.getX(),logicalMousePos.getY());
+                                               _sp.repaint();
+                                               break;
+                                       }
+                                       case RP_INNER_MOVE:
+                                       {
+                                               _ui.moveUnpairedUI(ur,logicalMousePos.getX(),logicalMousePos.getY());
+                                               _sp.repaint();
+                                               break;
+                                       }
+                                       case RP_CONNECT_START5:
+                                               _ui.setEdge5UI(ur,logicalMousePos.getX(),logicalMousePos.getY());
+                                               break;
+                                       case RP_CONNECT_END3:
+                                               _ui.setEdge3UI(ur,logicalMousePos.getX(),logicalMousePos.getY());
+                                               break;
+                                       }
+                                       _sp.repaint();                          
+                               }
+                       }
+               }
+       }
+
+       public void mouseMoved(MouseEvent arg0) {
+               // TODO Auto-generated method stub
+
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEditor.java b/src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEditor.java
new file mode 100644 (file)
index 0000000..fe60aae
--- /dev/null
@@ -0,0 +1,577 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.ComponentOrientation;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.BoxLayout;
+import javax.swing.ButtonGroup;
+import javax.swing.Icon;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.JScrollPane;
+import javax.swing.JToggleButton;
+import javax.swing.JToolBar;
+import javax.swing.UIManager;
+import javax.swing.UIManager.LookAndFeelInfo;
+import javax.swing.filechooser.FileFilter;
+import javax.swing.undo.UndoManager;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.applications.FileNameExtensionFilter;
+import fr.orsay.lri.varna.exceptions.ExceptionInvalidRNATemplate;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionXMLGeneration;
+import fr.orsay.lri.varna.models.templates.Benchmark;
+import fr.orsay.lri.varna.models.templates.DrawRNATemplateCurveMethod;
+import fr.orsay.lri.varna.models.templates.DrawRNATemplateMethod;
+import fr.orsay.lri.varna.models.templates.RNATemplate;
+import fr.orsay.lri.varna.models.templates.RNATemplateDrawingAlgorithmException;
+import fr.orsay.lri.varna.models.templates.RNATemplateMapping;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement;
+
+
+
+
+public class TemplateEditor extends JFrame implements KeyListener, ActionListener,DropTargetListener {
+
+       private TemplatePanel _sk;
+       private VARNAPanel _vp;
+       private File currentFilePath = null;
+       private JButton saveButton;
+       private JScrollPane jp;
+       private UndoManager manager;
+       private JButton flipButton;
+       private JComboBox ellipseMethodList;
+       private JComboBox applyMethodList;
+       /*private JRadioButton ellipseButtons[];
+       private JRadioButton methodButtons[];
+       */
+
+
+       public TemplateEditor()
+       {
+               init();
+               clearCurrentFilePath();
+       }       
+
+       public JScrollPane getJp() {
+               return jp;
+       }
+       
+       private void init()
+       {
+               try {
+                       _vp = new VARNAPanel(" ",".");
+               } catch (ExceptionNonEqualLength e) {
+                       e.printStackTrace();
+               }
+               _vp.setNumPeriod(0);
+               JPanel p = new JPanel();
+               p.setLayout(new GridLayout(1,2));
+               
+               JToolBar systemBar = new JToolBar();
+               JToolBar optionsBar = new JToolBar();
+               JButton newButton = new JButton("New",UIManager.getIcon("FileView.fileIcon")); 
+               newButton.setActionCommand("new");
+               newButton.addActionListener(this);
+               newButton.addKeyListener(this);
+               JButton loadButton = new JButton("Open...",UIManager.getIcon("FileView.directoryIcon")); 
+               loadButton.setActionCommand("open");
+               loadButton.addActionListener(this);
+               loadButton.addKeyListener(this);
+               saveButton = new JButton("Save",UIManager.getIcon("FileView.floppyDriveIcon")); 
+               saveButton.setActionCommand("save");
+               saveButton.addActionListener(this);
+               saveButton.addKeyListener(this);
+               saveButton.setEnabled(false);
+               JButton saveAsButton = new JButton("Save As...",UIManager.getIcon("FileView.floppyDriveIcon")); 
+               saveAsButton.setActionCommand("save as");
+               saveAsButton.addActionListener(this);
+               saveAsButton.addKeyListener(this);
+               JButton undoButton = new JButton("Undo"); 
+               undoButton.setActionCommand("undo");
+               undoButton.addActionListener(this);
+               undoButton.addKeyListener(this);
+               JButton redoButton = new JButton("Redo"); 
+               redoButton.setActionCommand("redo");
+               redoButton.addActionListener(this);
+               redoButton.addKeyListener(this);
+               
+               JButton benchmarkButton = new JButton("Benchmark"); 
+               benchmarkButton.setActionCommand("benchmark");
+               benchmarkButton.addActionListener(this);
+               benchmarkButton.addKeyListener(this);
+               
+               DrawRNATemplateMethod applyMethods[] = DrawRNATemplateMethod.values();
+               applyMethodList = new JComboBox(applyMethods); 
+               applyMethodList.setSelectedItem(DrawRNATemplateMethod.getDefault());
+               
+               DrawRNATemplateCurveMethod ellipseMethods[] = DrawRNATemplateCurveMethod.values();
+               ellipseMethodList = new JComboBox(ellipseMethods); 
+               ellipseMethodList.setSelectedItem(DrawRNATemplateCurveMethod.getDefault());
+
+               JButton applyButton = new JButton("Apply"); 
+               applyButton.setActionCommand("apply");
+               applyButton.addActionListener(this);
+               applyButton.addKeyListener(this);
+
+               JButton retrieveButton = new JButton("Retrieve Templates"); 
+               retrieveButton.setActionCommand("retrieve");
+               retrieveButton.addActionListener(this);
+               
+               
+               flipButton = new JButton("Flip helix"); 
+               flipButton.setActionCommand("flip");
+               flipButton.addActionListener(this);
+               flipButton.addKeyListener(this);
+               flipButton.setEnabled(false);
+
+               
+               systemBar.add(newButton);
+               systemBar.add(loadButton);
+               systemBar.add(saveButton);
+               systemBar.add(saveAsButton);
+               systemBar.addSeparator();
+               
+               systemBar.addSeparator();
+               systemBar.addSeparator();
+               systemBar.add(benchmarkButton);
+               systemBar.addKeyListener(this);
+               
+               optionsBar.setLayout(new FlowLayout(FlowLayout.LEFT));
+               optionsBar.add(new JLabel("Single-Stranded "));
+               optionsBar.add(this.ellipseMethodList);
+               optionsBar.addSeparator();
+               optionsBar.add(new JLabel("Layout "));
+               optionsBar.add(this.applyMethodList);
+               optionsBar.addSeparator();
+               optionsBar.add(applyButton);
+               optionsBar.addSeparator();
+               optionsBar.add(retrieveButton);
+               optionsBar.doLayout();
+               
+               /*optionsBar.add(new JLabel("Curves:"));
+               for (int i=0; i<ellipseButtons.length; i++)
+                       optionsBar.add(ellipseButtons[i]);
+               optionsBar.addSeparator();
+               optionsBar.add(new JLabel("Helix positions:"));
+               for (int i=0; i<methodButtons.length; i++)
+                       optionsBar.add(methodButtons[i]);
+               optionsBar.addKeyListener(this);
+               */
+
+               JToolBar toolBar = new JToolBar();
+               ButtonGroup bg = new ButtonGroup(); 
+               toolBar.setOrientation(JToolBar.VERTICAL);
+               //toolBar.setLayout(new BoxLayout(toolBar, BoxLayout.PAGE_AXIS));
+               JToggleButton selectButton = new JToggleButton("Select"); 
+               selectButton.setActionCommand("select");
+               selectButton.addActionListener(this);
+               selectButton.addKeyListener(this);
+               JToggleButton helixButton = new JToggleButton("Helix"); 
+               helixButton.setActionCommand("helix");
+               helixButton.addActionListener(this);
+               helixButton.addKeyListener(this);
+               helixButton.setSelected(true);
+               JToggleButton unpairedButton = new JToggleButton("Unpaired"); 
+               unpairedButton.setActionCommand("unpaired");
+               unpairedButton.addActionListener(this);
+               unpairedButton.addKeyListener(this);
+
+               bg.add(selectButton);
+               bg.add(helixButton);
+               bg.add(unpairedButton);
+               
+               toolBar.add(undoButton);
+               toolBar.add(redoButton);
+               toolBar.addSeparator();
+               toolBar.add(new JLabel("Tools:"));
+               toolBar.add(selectButton);
+               toolBar.add(helixButton);
+               toolBar.add(unpairedButton);
+               toolBar.addSeparator();
+               toolBar.add(flipButton);
+               systemBar.addKeyListener(this);
+
+               
+               this.setLayout(new BorderLayout());
+               _sk = new TemplatePanel(this);
+               _sk.setPreferredSize(new Dimension(800,600));
+               manager = new UndoManager();
+               manager.setLimit(2000);
+          _sk.addUndoableEditListener(manager);
+          _sk.addKeyListener(this);
+               
+               jp = new JScrollPane(_sk,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
+               p.add(jp);
+               p.add(_vp);
+               JPanel bars = new JPanel();
+               BoxLayout barsLayout = new BoxLayout(bars, BoxLayout.Y_AXIS);
+               bars.setLayout(barsLayout);
+               systemBar.setAlignmentX(0);
+               bars.add(systemBar);
+               optionsBar.setAlignmentX(0);
+               bars.add(optionsBar);
+               getContentPane().add(bars,BorderLayout.PAGE_START);
+               getContentPane().add(toolBar,BorderLayout.WEST);
+               getContentPane().add(p,BorderLayout.CENTER);
+               this.addKeyListener(this);
+               
+           new DropTarget(_vp, this);
+           new DropTarget(_sk, this);
+           this.pack();
+
+               _sk.requestFocusInWindow();
+       }
+       
+       
+       private File getCurrentFilePath() {
+               return currentFilePath;
+       }
+
+       private void setCurrentFilePath(File currentFilePath) {
+               this.currentFilePath = currentFilePath;
+               saveButton.setEnabled(true);
+               setTitle("VARNA Template Editor: " + currentFilePath);
+       }
+       
+       private void clearCurrentFilePath() {
+               currentFilePath = null;
+               saveButton.setEnabled(false);
+               setTitle("VARNA Template Editor: New file");
+       }
+       
+       
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -5942729520783690050L;
+
+       public static void main(String[] argv)
+       {
+               try {
+                       LookAndFeelInfo[] lfs = UIManager.getInstalledLookAndFeels();
+                       int i = 1;
+                   LookAndFeelInfo info = lfs[i % lfs.length];
+            UIManager.setLookAndFeel(info.getClassName());
+               } catch (Exception e) {
+                   // If Nimbus is not available, you can set the GUI to another look and feel.
+               }
+               TemplateEditor frame = new TemplateEditor();
+               frame.pack();
+               frame.setVisible(true);
+               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+       }
+
+       public void keyPressed(KeyEvent e) {
+               System.out.println(e);
+               switch (e.getKeyCode())
+               {
+                 case (KeyEvent.VK_DELETE):
+                 {
+                         GraphicalTemplateElement h = _sk.getSelected();
+                         _sk.Unselect();
+                         _sk.getTemplateUI().removeElementUI(h);
+                         _sk.repaint();
+                 }
+                 break;
+                 case (KeyEvent.VK_Z):
+                 {
+                         if (e.isControlDown())
+                         {
+                                 undo();
+                         }
+                 }
+                 break;
+                 case (KeyEvent.VK_Y):
+                 {
+                         if (e.isControlDown())
+                         {
+                                 redo();
+                         }
+                 }
+                 break;
+               }
+       }
+       
+       public void undo()
+       {
+               if (manager.canUndo())
+               {
+                       //System.out.println("Undo: "+manager.getUndoPresentationName());
+                       manager.undo();
+               }
+       }
+
+       public void redo()
+       {
+                 if (manager.canRedo())
+                 {
+                         //System.out.println("Redo: "+manager.getRedoPresentationName());
+                     manager.redo();
+                 }
+       }
+       
+       public void clearTemplate() {
+               _sk.clearTemplate();
+               clearCurrentFilePath();
+               
+               // Empty the cancel history
+               manager.discardAllEdits();
+       }
+       
+       public void loadTemplate(File templatePath) {
+               _sk.loadFromXmlFile(templatePath);
+               setCurrentFilePath(templatePath);
+               
+               // Empty the cancel history
+               manager.discardAllEdits();
+       }
+       
+       public void keyReleased(KeyEvent e) {
+               System.out.println(e);
+       }
+
+       public void keyTyped(KeyEvent e) {
+               System.out.println(e);
+       }
+
+       public void actionPerformed(ActionEvent e) {
+               if (e.getActionCommand().equals("undo"))
+               {
+                       undo();
+               }
+               else if (e.getActionCommand().equals("redo"))
+               {
+                       redo();
+               }
+               else if (e.getActionCommand().equals("flip"))
+               {
+                       GraphicalTemplateElement gr = _sk.getSelected();
+                       if (gr != null)
+                       {
+                               if (gr instanceof Helix)
+                               {
+                                       _sk.getTemplateUI().flipHelixUI((Helix)gr);
+                               }
+                       }
+               }
+               else if (e.getActionCommand().equals("select")) {
+                       _sk.getTemplateUI().setSelectedTool(TemplateEditorPanelUI.Tool.SELECT);
+               }
+               else if (e.getActionCommand().equals("helix")) {
+                       _sk.getTemplateUI().setSelectedTool(TemplateEditorPanelUI.Tool.CREATE_HELIX);
+               }
+               else if (e.getActionCommand().equals("retrieve")) {
+                       retrieveTemplates();
+               }               
+               else if (e.getActionCommand().equals("unpaired")) {
+                       _sk.getTemplateUI().setSelectedTool(TemplateEditorPanelUI.Tool.CREATE_UNPAIRED);
+               }
+               else if (e.getActionCommand().equals("apply"))
+               {
+                       try {
+                               DrawRNATemplateMethod method = (DrawRNATemplateMethod)applyMethodList.getSelectedItem();
+                               DrawRNATemplateCurveMethod curveMethod = (DrawRNATemplateCurveMethod)ellipseMethodList.getSelectedItem();
+                               RNATemplateMapping map =  _vp.getRNA().drawRNATemplate(_sk.getTemplate(),_vp.getConfig(), method, curveMethod, getStraightBulges());
+                               for(int i: map.getSourceElemsAsSet())
+                               {
+                                       RNATemplateElement t = map.getPartner(i);
+                                       Color c = _sk.getElement(t).getDominantColor();
+                                       _vp.getRNA().getBaseAt(i).getStyleBase().setBaseInnerColor(c);
+                               }
+                               _vp.repaint();
+                       } catch (RNATemplateDrawingAlgorithmException e1) {
+                               e1.printStackTrace();
+                               JOptionPane.showMessageDialog(this, e1.getMessage(), "Template-based RNA drawing error", JOptionPane.ERROR_MESSAGE);
+                       }
+               }
+               else if (e.getActionCommand().equals("save"))
+               {
+                       try {
+                               _sk.getTemplate().toXMLFile(getCurrentFilePath());
+                               System.out.println("Template saved in " + getCurrentFilePath().toString());
+                       } catch (ExceptionXMLGeneration e1) {
+                               e1.printStackTrace();
+                       } catch (ExceptionInvalidRNATemplate e1) {
+                               e1.printStackTrace();
+                       }
+               }
+               else if (e.getActionCommand().equals("save as"))
+               {
+                       JFileChooser chooser = new JFileChooser();
+                       FileFilter filter = new FileNameExtensionFilter("VARNA RNA template (.xml)", "xml");
+                   chooser.setFileFilter(filter);
+                       if (chooser.showSaveDialog(_sk) == JFileChooser.APPROVE_OPTION) {
+                               String path = chooser.getSelectedFile().getAbsolutePath();
+                               if (!path.toLowerCase().endsWith(".xml")) {
+                                       path = path + ".xml";
+                               }
+                               try {
+                                       _sk.getTemplate().toXMLFile(new File(path));
+                                       System.out.println("Template saved in " + path);
+                                       setCurrentFilePath(new File(path));
+                               } catch (ExceptionXMLGeneration e1) {
+                                       e1.printStackTrace();
+                               } catch (ExceptionInvalidRNATemplate e1) {
+                                       e1.printStackTrace();
+                               }
+                       }
+               }
+               else if (e.getActionCommand().equals("new"))
+               {
+                       clearTemplate();
+               }
+               else if (e.getActionCommand().equals("open"))
+               {
+                       JFileChooser chooser = new JFileChooser();
+                   FileFilter filter = new FileNameExtensionFilter("VARNA RNA template (.xml)", "xml");
+                   chooser.setFileFilter(filter);
+                       if (chooser.showOpenDialog(_sk) == JFileChooser.APPROVE_OPTION) {
+                               File templatePath = chooser.getSelectedFile();
+                               loadTemplate(templatePath);
+                       }
+               }
+               else if (e.getActionCommand().equals("benchmark")) {
+                       new Benchmark(_vp.getRNA()).printAll();
+               }
+
+       }
+       
+       
+       private boolean getStraightBulges() {
+               return false;
+       }
+
+       public void dragEnter(DropTargetDragEvent arg0) {
+       }
+
+       public void dragExit(DropTargetEvent arg0) {
+       }
+
+       public void dragOver(DropTargetDragEvent arg0) {
+       }
+
+       public void drop(DropTargetDropEvent dtde) 
+       {
+         try 
+         {
+           Transferable tr = dtde.getTransferable();
+           DataFlavor[] flavors = tr.getTransferDataFlavors();
+           for (int i = 0; i < flavors.length; i++) 
+           {
+             if (flavors[i].isFlavorJavaFileListType()) 
+             {
+                 dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
+                 List list = (List) tr.getTransferData(flavors[i]);
+                 for (int j = 0; j < list.size(); j++) 
+                 {
+                         Object o = list.get(j);
+                         if (dtde.getSource() instanceof DropTarget)
+                         {
+                                 DropTarget dt = (DropTarget) dtde.getSource();
+                                 Component c = dt.getComponent();
+                                 if (c instanceof VARNAPanel)
+                                 {
+                                         VARNAPanel vp = (VARNAPanel) c;
+                                         //String path = o.toString();
+                                         vp.loadFile((File) o, true); // BH SwingJS 
+                                         vp.repaint();
+                                 }
+                                 else if (c instanceof TemplatePanel)
+                                 {
+                                         TemplatePanel sk = (TemplatePanel) c;
+                                         //String path = o.toString();
+                                         sk.loadFromXmlFile((File) o); // BH SwingJS
+                                         sk.repaint();
+                                 }
+                         }
+                 }
+                 dtde.dropComplete(true);
+                 return;
+             }
+           }
+        dtde.rejectDrop();
+        } 
+        catch (Exception e) 
+        {
+                e.printStackTrace();
+            dtde.rejectDrop();
+         }
+       }
+
+       public void dropActionChanged(DropTargetDragEvent arg0) {
+       }
+
+       public VARNAPanel getVarnaPanel() {
+               return _vp;
+       }
+       
+       public void flipButtonEnable() {
+               flipButton.setEnabled(true);
+       }
+       
+       public void flipButtonDisable() {
+               flipButton.setEnabled(false);
+       }
+       
+       public void retrieveTemplates()
+       {
+               URL u;
+               
+               try {
+                       u = new URL("http://127.0.0.1/VARNA/templateShare/actions.php?action=retrieve&nbHelices=3&nbMultiLoops=1&length=50");
+               URLConnection uc = u.openConnection();
+               InputStreamReader  isr = new InputStreamReader(uc.getInputStream());
+               BufferedReader b = new BufferedReader(isr);
+               ArrayList<String> res = new ArrayList<String>();
+               String s = b.readLine();
+               while(s!=null)
+               {
+                       res.add(s);
+                       s = b.readLine();
+               }
+               } catch (MalformedURLException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               } catch (IOException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEditorPanelUI.java b/src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEditorPanelUI.java
new file mode 100644 (file)
index 0000000..9a7725e
--- /dev/null
@@ -0,0 +1,112 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+
+import java.awt.geom.Point2D;
+
+import javax.swing.undo.UndoManager;
+import javax.swing.undo.UndoableEditSupport;
+
+import fr.orsay.lri.varna.applications.templateEditor.GraphicalTemplateElement.RelativePosition;
+import fr.orsay.lri.varna.models.templates.RNATemplate;
+
+public class TemplateEditorPanelUI {
+
+       private UndoableEditSupport _undoableEditSupport;
+       private TemplatePanel _tp;
+       private Tool selectedTool = Tool.CREATE_HELIX;
+       
+
+
+       public enum Tool {
+               SELECT, CREATE_HELIX, CREATE_UNPAIRED
+       }
+
+       public TemplateEditorPanelUI(TemplatePanel tp)
+       {
+               _tp = tp;
+                _undoableEditSupport = new UndoableEditSupport(tp);
+       }
+       
+       public Tool getSelectedTool() {
+               return selectedTool;
+       }
+
+       public void setSelectedTool(Tool selectedTool) {
+               this.selectedTool = selectedTool;
+       }
+       
+       /* Generic undoable event firing for edge movement */
+       public void undoableEdgeMove(GraphicalTemplateElement h, GraphicalTemplateElement.RelativePosition edge,double nx, double ny)
+       {
+               _undoableEditSupport.postEdit(new TemplateEdits.ElementEdgeMoveTemplateEdit( h,edge,nx,ny,_tp));
+               h.setEdgePosition(edge, new Point2D.Double(nx,ny));
+               _tp.repaint();          
+       }
+       
+       public void setEdge5UI(GraphicalTemplateElement h, double nx, double ny)
+       { undoableEdgeMove(h,GraphicalTemplateElement.RelativePosition.RP_CONNECT_START5, nx,ny); }     
+       public void setEdge3UI(UnpairedRegion h, double nx, double ny)
+       { undoableEdgeMove(h,GraphicalTemplateElement.RelativePosition.RP_CONNECT_END3, nx,ny); }       
+       public void setEdge5TangentUI(UnpairedRegion h, double nx, double ny)
+       { undoableEdgeMove(h,GraphicalTemplateElement.RelativePosition.RP_EDIT_TANGENT_5, nx,ny); }
+       public void setEdge3TangentUI(UnpairedRegion h, double nx, double ny)
+       { undoableEdgeMove(h,GraphicalTemplateElement.RelativePosition.RP_EDIT_TANGENT_3, nx,ny); }     
+       public void moveUnpairedUI(UnpairedRegion u, double nx, double ny)
+       { undoableEdgeMove(u,GraphicalTemplateElement.RelativePosition.RP_INNER_MOVE, nx,ny); } 
+       public void moveHelixUI(Helix h, double nx, double ny)
+       { undoableEdgeMove(h,GraphicalTemplateElement.RelativePosition.RP_INNER_MOVE, nx,ny); } 
+       public void setHelixPosUI(Helix h, double nx, double ny)
+       { undoableEdgeMove(h,GraphicalTemplateElement.RelativePosition.RP_EDIT_START, nx,ny); } 
+       public void setHelixExtentUI(Helix h, double nx, double ny)
+       { undoableEdgeMove(h,GraphicalTemplateElement.RelativePosition.RP_EDIT_END, nx,ny); }   
+       
+
+       public void addElementUI(GraphicalTemplateElement h)
+       {
+               _undoableEditSupport.postEdit(new TemplateEdits.ElementAddTemplateEdit( h,_tp));
+               _tp.addElement(h);
+       }
+
+       public void removeElementUI(GraphicalTemplateElement h)
+       {
+               _undoableEditSupport.postEdit(new TemplateEdits.ElementRemoveTemplateEdit( h,_tp));
+               _tp.removeElement(h);
+       }
+       
+
+       public void addUndoableEditListener(UndoManager manager)
+       {
+               _undoableEditSupport.addUndoableEditListener(manager);
+       }
+       
+       public void addConnectionUI(GraphicalTemplateElement h1,
+                       GraphicalTemplateElement.RelativePosition e1,  
+                       GraphicalTemplateElement h2,
+                       GraphicalTemplateElement.RelativePosition e2)
+       {
+               if (GraphicalTemplateElement.canConnect(h1, e1,h2, e2))
+               {
+               Connection c = _tp.addConnection(h1,e1,h2,e2);
+               _undoableEditSupport.postEdit(new TemplateEdits.ElementAttachTemplateEdit(c,_tp));
+               }
+       }
+
+       public void removeConnectionUI(Connection c)
+       {
+               _undoableEditSupport.postEdit(new TemplateEdits.ElementDetachTemplateEdit(c,_tp));
+               _tp.removeConnection(c);
+       }
+
+       public void flipHelixUI(Helix h)
+       {
+                         _undoableEditSupport.postEdit(new TemplateEdits.HelixFlipTemplateEdit(h,_tp));
+                         _tp.flip(h);
+                         _tp.repaint();
+       }
+       
+       public RNATemplate getTemplate()
+       {
+               return _tp.getTemplate();
+       }
+       
+       
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEdits.java b/src2/fr/orsay/lri/varna/applications/templateEditor/TemplateEdits.java
new file mode 100644 (file)
index 0000000..d086989
--- /dev/null
@@ -0,0 +1,174 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+
+import java.awt.geom.Point2D;
+
+import javax.swing.undo.AbstractUndoableEdit;
+import javax.swing.undo.CannotRedoException;
+import javax.swing.undo.CannotUndoException;
+import javax.swing.undo.UndoableEdit;
+
+public class TemplateEdits {
+       public static final double MAX_DISTANCE= 15.0;
+               
+       public static  class ElementAddTemplateEdit extends AbstractUndoableEdit
+       {
+               private GraphicalTemplateElement _h;
+               private TemplatePanel _p;
+               public ElementAddTemplateEdit(GraphicalTemplateElement h,TemplatePanel p)
+               {
+                       _h = h;
+                       _p = p;
+               }
+               public void undo() throws CannotUndoException {
+                       _p.removeElement(_h);
+                       _p.repaint();                   
+               }
+               public void redo() throws CannotRedoException {
+                       _p.addElement(_h);
+                       _p.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Graphical element added"; }
+       };
+       public static  class ElementRemoveTemplateEdit extends AbstractUndoableEdit
+       {
+               private GraphicalTemplateElement _h;
+               private TemplatePanel _p;
+               public ElementRemoveTemplateEdit(GraphicalTemplateElement h,TemplatePanel p)
+               {
+                       _h = h;
+                       _p = p;
+               }
+               public void undo() throws CannotUndoException {
+                       _p.addElement(_h);
+                       _p.repaint();                   
+               }
+               public void redo() throws CannotRedoException {
+                       _p.removeElement(_h);
+                       _p.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Graphical element removed"; }
+       };
+       public static  class ElementAttachTemplateEdit extends AbstractUndoableEdit
+       {
+               Connection _c;
+               private TemplatePanel _p;
+               public ElementAttachTemplateEdit(Connection c,
+                               TemplatePanel p)
+               {
+                       _c = c;
+                       _p = p;
+               }
+               public void undo() throws CannotUndoException {
+                       _p.removeConnection(_c);
+                       _p.repaint();                   
+               }
+               public void redo() throws CannotRedoException {
+                       _c = _p.addConnection(_c._h1,_c._edge1,_c._h2,_c._edge2);
+                       _p.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Graphical elements attached"; }
+       };
+       public static  class ElementDetachTemplateEdit extends AbstractUndoableEdit
+       {
+               Connection _c;
+               private TemplatePanel _p;
+               public ElementDetachTemplateEdit(Connection c,
+                               TemplatePanel p)
+               {
+                       _c = c;
+                       _p = p;
+               }
+               public void undo() throws CannotUndoException {
+                       _c = _p.addConnection(_c._h1,_c._edge1,_c._h2,_c._edge2);
+                       _p.repaint();                   
+               }
+               public void redo() throws CannotRedoException {
+                       _p.removeConnection(_c);
+                       _p.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Graphical elements detached"; }
+       };
+       
+       public static  class ElementEdgeMoveTemplateEdit extends AbstractUndoableEdit
+       {
+               private GraphicalTemplateElement _ur;
+               GraphicalTemplateElement.RelativePosition _edge;
+               private double _ox; 
+               private double _oy;
+               private double _nx; 
+               private double _ny;
+               private TemplatePanel _p;
+               public ElementEdgeMoveTemplateEdit(GraphicalTemplateElement ur, GraphicalTemplateElement.RelativePosition edge, double nx, double ny, TemplatePanel p)
+               {
+                       _ur = ur;
+                       _edge = edge;
+                       _ox = ur.getEdgePosition(edge).x;
+                       _oy = ur.getEdgePosition(edge).y;
+                       _nx = nx;
+                       _ny = ny;
+                       _p = p;
+               }
+               public void undo() throws CannotUndoException {
+                       _ur.setEdgePosition(_edge,new Point2D.Double(_ox,_oy));
+                       _p.repaint();                   
+               }
+               public void redo() throws CannotRedoException {
+                       _ur.setEdgePosition(_edge,new Point2D.Double(_nx,_ny));
+                       _p.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Edge moved "+_edge; }
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       if (anEdit instanceof ElementEdgeMoveTemplateEdit)
+                       {
+                               ElementEdgeMoveTemplateEdit e = (ElementEdgeMoveTemplateEdit) anEdit;
+                               if (e._edge==_edge)
+                               {
+                                       Point2D.Double po1 = new Point2D.Double(_ox,_oy);
+                                       Point2D.Double pn1 = new Point2D.Double(_nx,_ny);
+                                       Point2D.Double po2 = new Point2D.Double(e._ox,e._oy);
+                                       Point2D.Double pn2 = new Point2D.Double(e._nx,e._ny);
+                                       if ((_ur==e._ur)&&(pn1.equals(po2))&&(po1.distance(pn2)<MAX_DISTANCE))
+                                       {
+                                               _nx = e._nx;
+                                               _ny = e._ny;
+                                               return true;
+                                       }
+                               }
+                       }
+                       return false;
+               }
+       };
+       public static  class HelixFlipTemplateEdit extends AbstractUndoableEdit
+       {
+               private Helix _h;
+               private TemplatePanel _p;
+               public HelixFlipTemplateEdit(Helix h, TemplatePanel p)
+               {
+                       _h = h;
+                       _p = p;
+               }
+               public void undo() throws CannotUndoException {
+                       _h.toggleFlipped();
+                       _p.repaint();                   
+               }
+               public void redo() throws CannotRedoException {
+                       _h.toggleFlipped();
+                       _p.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Helix flipped "; }
+       };
+       
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/TemplatePanel.java b/src2/fr/orsay/lri/varna/applications/templateEditor/TemplatePanel.java
new file mode 100644 (file)
index 0000000..ce47716
--- /dev/null
@@ -0,0 +1,662 @@
+/**
+ * 
+ */
+package fr.orsay.lri.varna.applications.templateEditor;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Point;
+import java.awt.Polygon;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.Stroke;
+import java.awt.geom.Point2D;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.undo.UndoManager;
+
+import fr.orsay.lri.varna.applications.templateEditor.GraphicalTemplateElement.RelativePosition;
+import fr.orsay.lri.varna.controlers.ControleurMolette;
+import fr.orsay.lri.varna.exceptions.ExceptionInvalidRNATemplate;
+import fr.orsay.lri.varna.exceptions.ExceptionXmlLoading;
+import fr.orsay.lri.varna.models.templates.RNATemplate;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateHelix;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateUnpairedSequence;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement.EdgeEndPoint;
+
+
+
+
+/**
+ * @author ponty
+ *
+ */
+public class TemplatePanel extends JPanel {
+  /**
+        * 
+        */
+       private static final long serialVersionUID = 3162771335587335679L;
+       
+       
+       private ArrayList<GraphicalTemplateElement> _RNAComponents;
+       private ArrayList<Connection> _RNAConnections;
+       private Hashtable<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>,Connection> _helixToConnection;
+       private TemplateEditorPanelUI _ui;
+       
+       private RNATemplate _template;
+
+       
+       private static Color[] BackgroundColors = {Color.blue,Color.red,Color.cyan,Color.green,Color.lightGray,Color.magenta,Color.PINK};
+
+       private int _nextBackgroundColor = 0;
+       
+       private static double scaleFactorDefault = 0.7;
+       private double scaleFactor = scaleFactorDefault;
+       
+       
+       private TemplateEditor _editor;
+       
+       
+       public double getScaleFactor() {
+               return scaleFactor;
+       }
+
+       public void setScaleFactor(double scaleFactor) {
+               this.scaleFactor = scaleFactor;
+       }
+
+       public Color nextBackgroundColor()
+       {
+               Color c = BackgroundColors[_nextBackgroundColor++];
+               _nextBackgroundColor = _nextBackgroundColor % BackgroundColors.length;
+               return new Color(c.getRed(),c.getBlue(),c.getGreen(),50);
+       }
+       
+       public TemplatePanel(TemplateEditor parent)
+       {
+               _editor = parent;
+               init();
+       }
+
+       public RNATemplate getTemplate()
+       {
+               return _template;
+       }
+       
+       List<GraphicalTemplateElement> getRNAComponents() {
+               return _RNAComponents;
+       }
+       
+       private void init()
+       {
+               _ui = new TemplateEditorPanelUI(this); 
+               
+               _RNAComponents = new ArrayList<GraphicalTemplateElement>();
+               _RNAConnections = new ArrayList<Connection>();
+               _helixToConnection = new Hashtable<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>,Connection>();
+               
+               _template = new RNATemplate();
+               
+               setBackground(Color.WHITE);
+               MouseControler mc = new MouseControler(this,_ui); 
+               addMouseListener(mc);
+               addMouseMotionListener(mc);
+               addMouseWheelListener(mc);
+               _solidStroke = new BasicStroke(1.5f, BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND, 3.0f);
+               float[] dash = { 5.0f, 5.0f };
+               _dashedStroke = new BasicStroke(1.5f, BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND, 3.0f, dash, 0);
+       }
+       
+       public void addUndoableEditListener(UndoManager manager)
+       {
+               _ui.addUndoableEditListener(manager);
+       }
+       
+       public TemplateEditorPanelUI getTemplateUI()
+       {
+               return _ui;
+       }
+
+       
+       public void flip(Helix h)
+       { 
+               h.toggleFlipped(); 
+       }
+       
+       public void addElement(GraphicalTemplateElement h)
+       { 
+               _RNAComponents.add(h); 
+       }
+
+       public void removeElement(GraphicalTemplateElement h)
+       { 
+               _RNAComponents.remove(h);
+               try {
+                       _template.removeElement(h.getTemplateElement());
+               } catch (ExceptionInvalidRNATemplate e) {
+                       //e.printStackTrace();
+               }
+       }
+
+       private GraphicalTemplateElement _selected = null;
+       
+       public GraphicalTemplateElement getSelected()
+       {
+               return _selected;
+       }
+
+       public void setSelected(GraphicalTemplateElement sel)
+       {
+               _selected = sel;
+               if (_selected instanceof Helix) {
+                       _editor.flipButtonEnable();
+               } else {
+                       _editor.flipButtonDisable();
+               }
+       }
+
+       Helix.RelativePosition _relpos = Helix.RelativePosition.RP_OUTER;
+       
+       public void setSelectedEdge(Helix.RelativePosition rel)
+       {
+               _relpos = rel;
+       }
+
+       public void unselectEdge(Helix.RelativePosition rel)
+       {
+               _relpos = rel;
+       }
+       
+       Point2D.Double _mousePos = new Point2D.Double();
+
+       public void setPointerPos(Point2D.Double p)
+       {
+               _mousePos = p;
+       }       
+       
+       public void Unselect()
+       {
+               _editor.flipButtonDisable();
+               _selected = null;
+       }
+
+       public GraphicalTemplateElement getElement(RNATemplateElement t)
+       {
+               for(GraphicalTemplateElement t2: _RNAComponents)
+                       if (t==t2.getTemplateElement())
+                               return t2;
+               return null;
+       }
+
+       
+       public GraphicalTemplateElement getElementAt(double x, double y)
+       {
+               return getElementAt(x, y, null);
+       }
+       public GraphicalTemplateElement getElementAt(double x, double y, GraphicalTemplateElement excluded)
+       {
+               GraphicalTemplateElement h = null;
+               for (int i=0; i<_RNAComponents.size();i++)
+               {
+                       GraphicalTemplateElement h2 = _RNAComponents.get(i);
+                       if ((
+                                          (h2.getRelativePosition(x, y)== Helix.RelativePosition.RP_CONNECT_END3)
+                                       || (h2.getRelativePosition(x, y)== Helix.RelativePosition.RP_CONNECT_END5)
+                                       || (h2.getRelativePosition(x, y)== Helix.RelativePosition.RP_CONNECT_START3)
+                                       || (h2.getRelativePosition(x, y)== Helix.RelativePosition.RP_CONNECT_START5))
+                               && (excluded!=h2))
+                       {
+                               h = h2;
+                       }
+               }
+               if (h==null)
+               { h = getElementCloseTo(x, y, excluded);};
+               return h;
+       }
+
+       public GraphicalTemplateElement getElementCloseTo(double x, double y)
+       {
+               return getElementCloseTo(x, y, null);
+       }
+       public GraphicalTemplateElement getElementCloseTo(double x, double y, GraphicalTemplateElement excluded)
+       {
+               GraphicalTemplateElement h = null;
+               for (int i=0; i<_RNAComponents.size();i++)
+               {
+                       GraphicalTemplateElement h2 = _RNAComponents.get(i);
+                       if ((h2.getRelativePosition(x, y) != Helix.RelativePosition.RP_OUTER)
+                               && (excluded!=h2))
+                       {
+                               h = h2;
+                       }
+               }
+               return h;
+       }
+       
+       public void addConnection(Connection c)
+       {
+               _RNAConnections.add(c);
+               _helixToConnection.put(new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c._h1,c._edge1), c);
+               _helixToConnection.put(new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c._h2,c._edge2), c);
+                       try {
+                               c._h1.attach(c._h2, c._edge1, c._edge2);
+                               c._h2.attach(c._h1, c._edge2, c._edge1);
+                       } catch (ExceptionInvalidRNATemplate e) {
+                               System.out.println(e.toString());// TODO Auto-generated catch block
+               }
+
+       }
+
+       public Connection addConnection(GraphicalTemplateElement h1, GraphicalTemplateElement.RelativePosition edge1,GraphicalTemplateElement h2, GraphicalTemplateElement.RelativePosition edge2)
+       {
+               if ((h1!=h2)&&(getPartner(h1,edge1)==null)&&(getPartner(h2,edge2)==null))
+               {
+                       Connection c = new Connection(h1,edge1,h2,edge2);
+                       addConnection(c);
+                       return c;
+               }
+               return null;
+       }
+       
+       /**
+        * When there is already a connection in the underlying RNATemplate
+        * and we want to create one at the graphical level.
+        */
+       public void addGraphicalConnection(GraphicalTemplateElement h1, GraphicalTemplateElement.RelativePosition edge1,GraphicalTemplateElement h2, GraphicalTemplateElement.RelativePosition edge2) {
+               //System.out.println("Connecting " + h1 + " " + edge1 + " to " + h2 + " " + edge2);
+               Connection c = new Connection(h1,edge1,h2,edge2);
+               _RNAConnections.add(c);
+               _helixToConnection.put(new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c._h1,c._edge1), c);
+               _helixToConnection.put(new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c._h2,c._edge2), c);
+               c._h1.graphicalAttach(c._h2, c._edge1, c._edge2);
+               c._h2.graphicalAttach(c._h1, c._edge2, c._edge1);
+       }
+       
+
+       public void removeConnection(Connection c)
+       {
+               _RNAConnections.remove(c);
+               _helixToConnection.remove(new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c._h1,c._edge1));
+               _helixToConnection.remove(new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c._h2,c._edge2));
+               System.out.println("[A]"+c);
+               c._h1.detach(c._edge1);
+       }
+       
+       public boolean isInCycle(GraphicalTemplateElement el, GraphicalTemplateElement.RelativePosition edge)
+       {
+               Stack<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> > p = new Stack<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>>();
+               Hashtable<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>,Integer> alreadySeen = new Hashtable<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>,Integer>(); 
+               p.add(new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(el,edge));
+               while(!p.empty())
+               {
+                       Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> c2 = p.pop();
+                       if (alreadySeen.containsKey(c2))
+                       {
+                               return true;
+                       }
+                       else
+                       {
+                               alreadySeen.put(c2, new Integer(1));
+                       }
+                       GraphicalTemplateElement.RelativePosition next = c2.first.getConnectedEdge(c2.second);
+                       Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> otherEnd = new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c2.first,next);
+                       if (!alreadySeen.containsKey(otherEnd))
+                       {
+                               p.push(otherEnd);
+                       }
+                       else
+                       {
+                               Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> child =  getPartner(c2.first,c2.second);
+                               if (child!=null)
+                               {
+                                       p.push(child);
+                               }
+                       }
+                       
+               }
+               
+               return false;   
+       }
+       
+       private static Color[] _colors = {Color.gray,Color.pink,Color.cyan,Color.RED,Color.green,Color.orange};
+       
+       public static Color getIndexedColor(int n)
+       {
+               return _colors[n%_colors.length];
+       }
+       
+       public HashMap<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>,Integer> buildConnectedComponents()
+       {
+               HashMap<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>,Integer> alreadySeen = new HashMap<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>,Integer>();
+               int numConnectedComponents = 0;
+               for (GraphicalTemplateElement el : this._RNAComponents)
+               {
+                       for (GraphicalTemplateElement.RelativePosition edge : el.getConnectedEdges())
+                       {
+                               Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> c = new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(el,edge);
+                               if (!alreadySeen.containsKey(c))
+                               {
+                                       Stack<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> > p = new Stack<Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>>();
+                                       p.add(c);
+                                       p.add(new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(el,el.getConnectedEdge(edge)));
+                                       while(!p.empty())
+                                       {
+                                               Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> c2 = p.pop();
+                                               if (!alreadySeen.containsKey(c2))
+                                               {
+                                                       //System.out.println("  "+numConnectedComponents+"  "+c2);
+                                                       c2.first.setMainColor(c2.second, getIndexedColor(numConnectedComponents));
+                                                       alreadySeen.put(c2, new Integer(numConnectedComponents));
+                                                       GraphicalTemplateElement.RelativePosition next = c2.first.getConnectedEdge(c2.second);
+                                                       Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> otherEnd = new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c2.first,next);
+                                                       p.push(otherEnd);
+                                                       Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> child =  getPartner(c2.first,c2.second);
+                                                       if (child!=null)
+                                                       { p.push(child); }
+                                               }       
+                                       }
+                                       numConnectedComponents += 1;
+                               }
+                       }
+               }
+               return alreadySeen;
+       }
+       
+       public boolean isInCycle(Connection c)
+       {
+               return isInCycle(c._h1,c._edge1); 
+       }
+       
+       public Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> getPartner(GraphicalTemplateElement h, GraphicalTemplateElement.RelativePosition edge)
+       {
+               Connection c = getConnection(h, edge);
+               if (c != null)
+               {
+                         if ((c._h1==h)&&(c._edge1==edge))
+                         {  return new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c._h2,c._edge2);  }
+                         else 
+                         {  return new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(c._h1,c._edge1); }
+               }
+               else
+               {
+                       return null;
+               }
+       }
+
+       public Connection getConnection(GraphicalTemplateElement h, Helix.RelativePosition edge)
+       {
+               Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> target = new Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition>(h,edge);
+               if (_helixToConnection.containsKey(target))
+               {
+                       return _helixToConnection.get(target);
+               }
+               else
+               { return null; }
+       }
+       
+       private boolean isConnected(Helix h, GraphicalTemplateElement.RelativePosition edge)
+       {
+               Couple<GraphicalTemplateElement,GraphicalTemplateElement.RelativePosition> partner = getPartner(h,edge);
+               return partner!=null;
+       }
+       
+
+       // Aspects graphiques
+       
+       private static final Color  CYCLE_COLOR = Color.red;
+       private static final Color  NON_EXISTANT_COLOR = Color.gray.brighter();
+       private static final Color  CONTROL_COLOR = Color.gray.darker();
+       private static final Color  BACKGROUND_COLOR = Color.white;
+       
+       private Stroke  _solidStroke;
+       private Stroke  _dashedStroke;
+       
+
+       
+       
+       private void drawConnections(Graphics2D g2d, Connection c)
+       {
+               GraphicalTemplateElement h1 = c._h1;
+               GraphicalTemplateElement.RelativePosition edge1 = c._edge1;
+               Point2D.Double p1 = h1.getEdgePosition(edge1);
+               GraphicalTemplateElement h2 = c._h2;
+               GraphicalTemplateElement.RelativePosition edge2 = c._edge2;
+               Point2D.Double p2 = h2.getEdgePosition(edge2);
+               if (isInCycle(c))
+               {
+                       g2d.setColor(CYCLE_COLOR);
+               }
+               else
+               {
+                       g2d.setColor(GraphicalTemplateElement.BACKBONE_COLOR);
+               }
+               g2d.drawLine((int)p1.x,(int)p1.y,(int)p2.x,(int)p2.y);
+       }
+       
+
+       public void paintComponent(Graphics g)
+       {
+               //rescale();
+               
+               // Debug code to show drawing area
+//             g.setColor(Color.red);
+//             g.fillRect(0,0,getWidth(),getHeight());
+//             g.setColor(Color.white);
+//             g.fillRect(10,10,getWidth()-20,getHeight()-20);
+               
+               g.setColor(Color.white);
+               g.fillRect(0,0,getWidth(),getHeight());
+               
+               Graphics2D g2d = (Graphics2D) g;
+               g2d.scale(scaleFactor, scaleFactor);
+               g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+                               RenderingHints.VALUE_ANTIALIAS_ON);
+               removeAll();
+               //super.paintComponent(g2d);
+
+               buildConnectedComponents();
+               
+               if (_selected!=null)
+               {
+                       if (_relpos != GraphicalTemplateElement.RelativePosition.RP_OUTER)
+                       {       
+                       Point2D.Double p = _selected.getEdgePosition(_relpos);
+                       g2d.setStroke(_solidStroke);
+                       g2d.drawLine((int)_mousePos.x, (int)_mousePos.y, (int)p.x, (int)p.y);
+                       }
+               }
+               for (int i=0;i<_RNAConnections.size();i++)
+               {
+                       Connection c = _RNAConnections.get(i);
+                       drawConnections(g2d,c);
+               }
+               for (int i=0;i<_RNAComponents.size();i++)
+               {
+                       GraphicalTemplateElement elem = _RNAComponents.get(i);
+                       //g2d.setColor(elem.getDominantColor());
+                       //g2d.fill(elem.getArea());
+                       if (_selected == elem)
+                       {  
+                               elem.draw(g2d,true); 
+                       }
+                       else
+                       {  elem.draw(g2d,false);  }
+               }
+       }
+       
+       /**
+        * Get the bounding rectangle of the RNA components, always including the origin (0,0).
+        */
+       public Rectangle getBoundingRectange() {
+               int minX = 0;
+               int maxX = 0;
+               int minY = 0;
+               int maxY = 0;
+               for(int i=0;i<this._RNAComponents.size();i++)
+               {
+                       GraphicalTemplateElement h = _RNAComponents.get(i);
+                       Polygon p = h.getBoundingPolygon();
+                       Rectangle r = p.getBounds();
+                       minX = Math.min(minX,r.x);
+                       maxX = Math.max(maxX,r.x+r.width);
+                       minY = Math.min(minY,r.y);
+                       maxY = Math.max(maxY,r.y+r.height);
+               }
+               Rectangle res = new Rectangle();
+               res.x = minX;
+               res.y = minY;
+               res.width = maxX - minX;
+               res.height = maxY - minY;
+               return res;
+       }
+
+       public void rescale()
+       {
+               Rectangle rect = getBoundingRectange();
+               
+               if (rect.x < 0 || rect.y < 0) {
+            for(int i=0;i<this._RNAComponents.size();i++)
+            {
+                    GraphicalTemplateElement h = _RNAComponents.get(i);
+                    h.translate(rect.x<0 ? -rect.x : 0, rect.y<0 ? -rect.y : 0);
+            }
+            rect = getBoundingRectange();
+               }
+               
+               // areaW and H are width and height, in pixels, of the drawing area
+               // including the "outside" parts available with scrolling
+               int areaW = (int) ((rect.width + 100) * scaleFactor);
+               int areaH = (int) ((rect.height + 100) * scaleFactor);
+               // make it cover at least the space visible in the window
+               //areaW = Math.max(areaW, (int) (_editor.getJp().getViewport().getViewSize().width));
+               //areaH = Math.max(areaH, (int) (_editor.getJp().getViewport().getViewSize().height));
+               //System.out.println(areaW + " x " + areaH);
+               setPreferredSize(new Dimension(areaW, areaH));
+               revalidate();
+       }
+
+       public void clearTemplate() {
+               loadTemplate(new RNATemplate());
+       }
+
+       /**
+        * Load an existing RNATemplate object in this panel.
+        */
+       public void loadTemplate(RNATemplate template) {
+               _template = template;
+               _RNAComponents.clear();
+               _RNAConnections.clear();
+               _helixToConnection.clear();
+               
+               // We need a template element -> graphical template element mapping
+               Map<RNATemplateElement, GraphicalTemplateElement> map = new HashMap<RNATemplateElement, GraphicalTemplateElement>();
+               
+               // First, we load elements
+               {
+                       Iterator<RNATemplateElement> iter = template.classicIterator();
+                       while (iter.hasNext()) {
+                               RNATemplateElement templateElement = iter.next();
+                               if (templateElement instanceof RNATemplateHelix) {
+                                       RNATemplateHelix templateHelix = (RNATemplateHelix) templateElement;
+                                       Helix graphicalHelix = new Helix(templateHelix);
+                                       graphicalHelix.setDominantColor(nextBackgroundColor());
+                                       _RNAComponents.add(graphicalHelix);
+                                       map.put(templateHelix, graphicalHelix);
+                               } else if (templateElement instanceof RNATemplateUnpairedSequence) {
+                                       RNATemplateUnpairedSequence templateSequence = (RNATemplateUnpairedSequence) templateElement;
+                                       UnpairedRegion graphicalSequence = new UnpairedRegion(templateSequence);
+                                       graphicalSequence.setDominantColor(nextBackgroundColor());
+                                       _RNAComponents.add(graphicalSequence);
+                                       map.put(templateSequence, graphicalSequence);
+                               }
+                       }
+               }
+               
+               // Now, we load edges
+               {
+                       Iterator<EdgeEndPoint> iter = template.makeEdgeList().iterator();
+                       while (iter.hasNext()) {
+                               EdgeEndPoint v1 = iter.next();
+                               EdgeEndPoint v2 = v1.getOtherEndPoint();
+                               GraphicalTemplateElement gte1 = map.get(v1.getElement());
+                               GraphicalTemplateElement gte2 = map.get(v2.getElement());
+                               RelativePosition rp1 = gte1.relativePositionFromEdgeEndPointPosition(v1.getPosition());
+                               RelativePosition rp2 = gte2.relativePositionFromEdgeEndPointPosition(v2.getPosition());
+                               addGraphicalConnection(gte1, rp1, gte2, rp2);
+                       }
+               }
+               
+               zoomFit();
+               //repaint();
+       }
+
+       /**
+        * Load a template from an XML file.
+        */
+       public void loadFromXmlFile(File filename) {
+               try {
+                       RNATemplate newTemplate = RNATemplate.fromXMLFile(filename);
+                       loadTemplate(newTemplate);
+               } catch (ExceptionXmlLoading e) {
+                       e.printStackTrace();
+                       JOptionPane.showMessageDialog(this, e.getMessage(), "Template loading error", JOptionPane.ERROR_MESSAGE);
+               }
+       }
+       
+       private void zoomFinish() {
+               rescale();
+               repaint();
+       }
+       
+       public void zoomIn() {
+               scaleFactor *= 1.2;
+               zoomFinish();
+       }
+       
+       public void zoomOut() {
+               scaleFactor /= 1.2;
+               zoomFinish();
+       }
+       
+       public void zoomReset() {
+               scaleFactor = scaleFactorDefault;
+               zoomFinish();
+       }
+       
+       public void zoomFit() {
+               if (_RNAComponents.isEmpty()) {
+                       zoomReset();
+               } else {
+                       Rectangle rect = getBoundingRectange();
+                       double areaW = (rect.width + 100);
+                       double areaH = (rect.height + 100);
+                       // make it cover at least the space visible in the window
+                       scaleFactor = 1;
+                       scaleFactor = Math.min(scaleFactor, _editor.getJp().getViewport().getSize().width / areaW);
+                       scaleFactor = Math.min(scaleFactor, _editor.getJp().getViewport().getSize().height / areaH);
+                       zoomFinish();
+               }
+       }
+       
+       public void translateView(Point trans) {
+               int newX = _editor.getJp().getHorizontalScrollBar().getValue() - trans.x;
+               int newY = _editor.getJp().getVerticalScrollBar().getValue() - trans.y;
+               newX = Math.max(0, Math.min(newX, _editor.getJp().getHorizontalScrollBar().getMaximum()));
+               newY = Math.max(0, Math.min(newY, _editor.getJp().getVerticalScrollBar().getMaximum()));
+               _editor.getJp().getHorizontalScrollBar().setValue(newX);
+               _editor.getJp().getVerticalScrollBar().setValue(newY);
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/applications/templateEditor/UnpairedRegion.java b/src2/fr/orsay/lri/varna/applications/templateEditor/UnpairedRegion.java
new file mode 100644 (file)
index 0000000..363fe85
--- /dev/null
@@ -0,0 +1,488 @@
+package fr.orsay.lri.varna.applications.templateEditor;
+import java.awt.Graphics2D;
+import java.awt.Polygon;
+import java.awt.Shape;
+import java.awt.geom.CubicCurve2D;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Point2D;
+import java.awt.geom.Point2D.Double;
+import java.util.ArrayList;
+
+import fr.orsay.lri.varna.applications.templateEditor.GraphicalTemplateElement.RelativePosition;
+import fr.orsay.lri.varna.exceptions.ExceptionEdgeEndpointAlreadyConnected;
+import fr.orsay.lri.varna.exceptions.ExceptionInvalidRNATemplate;
+import fr.orsay.lri.varna.models.geom.CubicBezierCurve;
+import fr.orsay.lri.varna.models.templates.RNATemplate;
+import fr.orsay.lri.varna.models.templates.RNATemplate.EdgeEndPointPosition;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateHelix;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateUnpairedSequence;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement.EdgeEndPoint;
+
+public class UnpairedRegion extends GraphicalTemplateElement{
+       private RNATemplateUnpairedSequence _e;
+       public static final double DEFAULT_VECTOR_LENGTH = 35;
+       public static final double DEFAULT_VECTOR_DISTANCE = 35;
+
+       private Point2D.Double[] sequenceBasesCoords = null;
+
+       public UnpairedRegion(double x, double y, RNATemplate tmp)
+       {
+               _e = tmp.new RNATemplateUnpairedSequence("");
+               _e.setVertex5(new Point2D.Double(x,y));
+               _e.setVertex3(new Point2D.Double(x+DEFAULT_VECTOR_DISTANCE,y));
+               _e.setInTangentVectorLength(DEFAULT_VECTOR_LENGTH);
+               _e.setInTangentVectorAngle(-Math.PI/2.0);
+               _e.setOutTangentVectorLength(DEFAULT_VECTOR_LENGTH);
+               _e.setOutTangentVectorAngle(-Math.PI/2.0);
+               updateLength();
+
+       }
+
+       /**
+        * Build an UnpairedRegion object from a RNATemplateUnpairedSequence
+        * object. The RNATemplateUnpairedSequence must be connected to
+        * an helix on both sides.
+        */
+       public UnpairedRegion(RNATemplateUnpairedSequence templateSequence)
+       {
+               _e = templateSequence;
+       }
+
+       public Point2D.Double getEdge5()
+       { 
+               RelativePosition r = RelativePosition.RP_CONNECT_START5;
+               Couple<RelativePosition,GraphicalTemplateElement> c = getAttachedElement(r);
+               return (isAnchored5()? c.second.getEdgePosition(c.first): _e.getVertex5()); 
+       }
+
+       public Point2D.Double getEdge3()
+       { 
+               RelativePosition r = RelativePosition.RP_CONNECT_END3;
+               Couple<RelativePosition,GraphicalTemplateElement> c = getAttachedElement(r);
+               return (isAnchored3()? c.second.getEdgePosition(c.first): _e.getVertex3()); 
+       }
+
+       public Point2D.Double getCenter()
+       { 
+               Point2D.Double p1 = getEdge5();
+               Point2D.Double p2 = getEdge3();
+               return new Point2D.Double((p1.x+p2.x)/2.,(p1.y+p2.y)/2.); 
+       }
+       
+       
+       public void setEdge5(Point2D.Double d)
+       {
+               _e.setVertex5(d);
+               updateLength();
+       }
+
+       public void setEdge3(Point2D.Double d)
+       {
+               _e.setVertex3(d);
+               updateLength();
+       }
+
+       public void setCenter(Point2D.Double d)
+       {
+               Point2D.Double p1 = getEdge5();
+               Point2D.Double p2 = getEdge3();
+               double dx = p1.x-p2.x;
+               double dy = p1.y-p2.y;
+               _e.setVertex3(new Point2D.Double(d.x-dx/2.,d.y-dy/2.));
+               _e.setVertex5(new Point2D.Double(d.x+dx/2.,d.y+dy/2.));
+               invalidateCoords();
+       }
+       
+       
+       public boolean isAnchored5()
+       {
+               return (_e.getIn().getOtherElement()!=null);
+       }
+
+       public boolean isAnchored3()
+       {
+               return (_e.getOut().getOtherElement()!=null);
+       }
+
+
+       public static Shape bezToShape(CubicBezierCurve c)
+       {
+               GeneralPath p = new GeneralPath();
+               int nb = 9;
+               double[] tab = new double[nb];
+               for (int i=0;i<nb;i++)
+               {
+                       tab[i] = (c.getApproxCurveLength()*(double)i)/(double)nb;
+               }
+               Point2D.Double[] points = c.uniformParam(tab);
+               System.out.println(points.length);
+               p.moveTo((float)points[0].x,(float)points[0].y);
+               for (int i=1;i<nb;i++)
+               { 
+                       Point2D.Double a = points[i];
+                       System.out.println(a);
+                       p.lineTo((float)a.x,(float)a.y);
+               }
+               p.lineTo((float)c.getP3().x,(float)c.getP3().y);
+               return p;
+       }
+
+
+
+       public Shape getCurve()
+       {
+               Point2D.Double p5 = getEdge5(); 
+               Point2D.Double p3 = getEdge3(); 
+               Point2D.Double t5 = getControl5(); 
+               Point2D.Double t3 = getControl3();
+               return new CubicCurve2D.Double(p5.x,p5.y,t5.x,t5.y,t3.x,t3.y,p3.x,p3.y);
+               //CubicBezierCurve c = new CubicBezierCurve( p5, t5, t3, p3, 30);
+               //return bezToShape(c);
+
+       }
+
+       private int estimateNumberOfBases()
+       {
+               Point2D.Double p5 = getEdge5(); 
+               Point2D.Double p3 = getEdge3(); 
+               Point2D.Double t5 = getControl5(); 
+               Point2D.Double t3 = getControl3();
+               CubicBezierCurve c = new CubicBezierCurve( p5, t5, t3, p3, 30);
+               // Extremities don't count as unpaired bases because they are part of the connected helix.
+               return Math.max((int)Math.round(c.getApproxCurveLength()/Helix.LOOP_DISTANCE)-1, 1);
+       }
+
+       private void updateLength()
+       {
+               this._e.setLength(estimateNumberOfBases());
+               invalidateCoords();
+       }
+
+       
+       /**
+        * Mark the coordinates as invalid, ie. need to be calculated again if we want to draw them.
+        */
+       private void invalidateCoords() {
+               sequenceBasesCoords = null;
+       }
+
+       /**
+        * Calculate the positions of the unpaired bases.
+        */
+       private void calculeCoords() {
+               //System.out.println("calculate coords");
+               
+               Point2D.Double p5 = getEdge5(); 
+               Point2D.Double p3 = getEdge3(); 
+               Point2D.Double t5 = getControl5(); 
+               Point2D.Double t3 = getControl3();
+               
+               // Draw bases on curve:
+               int n = _e.getLength();
+               // We choose to approximate the Bezier curve by 10*n straight lines.
+               CubicBezierCurve bezier = new CubicBezierCurve(p5, t5, t3, p3, 10*n);
+               double curveLength = bezier.getApproxCurveLength();
+               double delta_t = curveLength / (n+1);
+               double[] t = new double[n];
+               for (int k=0; k<n; k++) {
+                       t[k] = (k+1) * delta_t;
+               }
+               sequenceBasesCoords = bezier.uniformParam(t);
+       }
+
+       public void draw(Graphics2D g2d, boolean selected) {
+               Point2D.Double p5 = getEdge5(); 
+               Point2D.Double p3 = getEdge3(); 
+               Point2D.Double t5 = getControl5(); 
+               Point2D.Double t3 = getControl3();
+               if (selected)
+               {
+                       g2d.setStroke(_dashedStroke);
+                       g2d.setColor(BACKBONE_COLOR);
+                       g2d.draw(getBoundingPolygon());
+                       g2d.setStroke(_solidStroke);
+                       drawAnchor(g2d,t5);
+                       drawAnchor(g2d,t3);
+                       double d5x = (t5.x-p5.x)/(t5.distance(p5));
+                       double d5y = (t5.y-p5.y)/(t5.distance(p5));
+                       double d3x = (t3.x-p3.x)/(t3.distance(p3));
+                       double d3y = (t3.y-p3.y)/(t3.distance(p3));
+                       double shift = -3.5;
+                       Point2D.Double tp5 = new Point2D.Double(t5.x-shift*d5x,t5.y-shift*d5y); 
+                       Point2D.Double tp3 = new Point2D.Double(t3.x-shift*d3x,t3.y-shift*d3y);
+
+                       drawArrow(g2d, p5, tp5, UNPAIRED_ARROW_WIDTH);
+                       drawArrow(g2d, p3, tp3, UNPAIRED_ARROW_WIDTH);
+               }
+               g2d.setColor(BACKBONE_COLOR);
+               g2d.setStroke(_solidStroke);
+               g2d.draw(getCurve());
+
+               if (sequenceBasesCoords == null) {
+                       calculeCoords();
+               }
+               for (int k=0; k<sequenceBasesCoords.length; k++) {
+                       drawBase(g2d, sequenceBasesCoords[k]);
+               }
+
+               if (!isAnchored5())
+               {drawAnchor5(g2d,p5); }
+               else
+               { drawMagnet(g2d,p5);}
+               if (!isAnchored3())
+               {drawAnchor3(g2d,p3); }
+               else
+               { drawMagnet(g2d,p3);}
+               
+               if (!isAnchored5() && !isAnchored3())
+               drawMove(g2d, getCenter());
+       }
+
+
+       public Point2D.Double getControl5()
+       {
+               Point2D.Double p5 = getEdge5();
+               double angle = _e.getInTangentVectorAngle();
+               return new Point2D.Double(p5.x+Math.cos(angle)*_e.getInTangentVectorLength(),
+                               p5.y+Math.sin(angle)*_e.getInTangentVectorLength());
+       }
+
+       public Point2D.Double getControl3()
+       {
+               Point2D.Double p3 = getEdge3(); 
+               double angle = _e.getOutTangentVectorAngle();
+               return new Point2D.Double(p3.x+Math.cos(angle)*_e.getOutTangentVectorLength(),
+                               p3.y+Math.sin(angle)*_e.getOutTangentVectorLength());
+       }
+
+       public static final double MAX_UNPAIRED_CONTROL_DISTANCE = 10.0;
+       public static final double UNPAIRED_ARROW_WIDTH = 6.0;
+
+
+
+       public Polygon getBoundingPolygon() {
+               Point2D.Double p5 = getEdge5(); 
+               Point2D.Double p3 = getEdge3(); 
+               Point2D.Double t5 = getControl5(); 
+               Point2D.Double t3 = getControl3();
+
+               double minx = Math.min(p5.x,Math.min(p3.x,Math.min(t5.x,t3.x)));
+               double maxx = Math.max(p5.x,Math.max(p3.x,Math.max(t5.x,t3.x)));
+               double miny = Math.min(p5.y,Math.min(p3.y,Math.min(t5.y,t3.y)));
+               double maxy = Math.max(p5.y,Math.max(p3.y,Math.max(t5.y,t3.y)));
+               minx -= 10;
+               maxx += 10;
+               miny -= 10;
+               maxy += 10;
+               int[] x = {(int)minx,(int)maxx,(int)maxx,(int)minx};
+               int[] y = {(int)miny,(int)miny,(int)maxy,(int)maxy};
+               return new Polygon(x,y,4);
+       }
+
+       public RelativePosition getClosestEdge(double x, double y) {
+               Point2D.Double p = new Point2D.Double(x,y);
+               Point2D.Double p5 = getEdge5(); 
+               Point2D.Double p3 = getEdge3(); 
+               Point2D.Double t5 = getControl5(); 
+               Point2D.Double t3 = getControl3();
+               Point2D.Double ct = getCenter();
+               ArrayList<Couple<java.lang.Double,RelativePosition>> v = new ArrayList<Couple<java.lang.Double,RelativePosition>>(); 
+               v.add(new Couple<java.lang.Double,RelativePosition>(p.distance(p5),RelativePosition.RP_CONNECT_START5));
+               v.add(new Couple<java.lang.Double,RelativePosition>(p.distance(p3),RelativePosition.RP_CONNECT_END3));
+               v.add(new Couple<java.lang.Double,RelativePosition>(p.distance(t5),RelativePosition.RP_EDIT_TANGENT_5));
+               v.add(new Couple<java.lang.Double,RelativePosition>(p.distance(t3),RelativePosition.RP_EDIT_TANGENT_3));
+               v.add(new Couple<java.lang.Double,RelativePosition>(p.distance(ct),RelativePosition.RP_INNER_MOVE));
+               double dist = java.lang.Double.MAX_VALUE;
+               RelativePosition r = RelativePosition.RP_OUTER;
+               
+               for (Couple<java.lang.Double,RelativePosition> c : v)
+               {
+                       if (c.first<dist)
+                       {
+                               dist = c.first;
+                               r = c.second;
+                       }
+               }
+               return r;
+       }
+
+       public RelativePosition getConnectedEdge(RelativePosition edge) {
+               switch(edge)
+               {
+               case RP_CONNECT_START5:
+                       return RelativePosition.RP_CONNECT_END3;
+               case RP_CONNECT_END3:
+                       return RelativePosition.RP_CONNECT_START5;
+               default:
+                       return RelativePosition.RP_OUTER;
+               }
+       }
+
+       public Point2D.Double getEdgePosition(RelativePosition edge)
+       {
+               switch(edge)
+               {
+               case RP_INNER_MOVE:
+                       return getCenter();
+               case RP_CONNECT_START5:
+                       return getEdge5();
+               case RP_CONNECT_END3:
+                       return getEdge3();
+               case RP_EDIT_TANGENT_5:
+                       return getControl5();
+               case RP_EDIT_TANGENT_3:
+                       return getControl3();
+               default:
+                       return getEdge5();
+               }
+       }
+
+       double v2a(Point2D.Double p)
+       {
+               return (double)Math.atan2(p.y, p.x);
+       }
+
+       public void updateControl5(Point2D.Double p)
+       {
+               Point2D.Double p5 = getEdge5();
+               _e.setInTangentVectorLength(p5.distance(p));
+               Point2D.Double x = new Point2D.Double(p.x-p5.x,p.y-p5.y); 
+               _e.setInTangentVectorAngle(v2a(x));
+               updateLength();
+       }
+
+       public void updateControl3(Point2D.Double p)
+       {
+               Point2D.Double p3 = getEdge3();
+               _e.setOutTangentVectorLength(p3.distance(p));
+               Point2D.Double x = new Point2D.Double(p.x-p3.x,p.y-p3.y); 
+               _e.setOutTangentVectorAngle(v2a(x));
+               updateLength();
+       }
+
+       public void translate(double x, double y) {
+               _e.getVertex5().x += x;
+               _e.getVertex5().y += y;
+               _e.getVertex3().x += x;
+               _e.getVertex3().y += y;
+               invalidateCoords();
+       }
+
+       public RelativePosition getRelativePosition(double x, double y) {
+               RelativePosition rp = getClosestEdge(x, y);
+               double d = getEdgePosition(rp).distance(new Point2D.Double(x,y));
+               if (d<MAX_UNPAIRED_CONTROL_DISTANCE)
+                       return rp;
+               if (getCurve().contains(new Point2D.Double(x,y)))
+                       return RelativePosition.RP_INNER_GENERAL;
+               return RelativePosition.RP_OUTER;
+       }
+
+       public Shape getArea()
+       {
+               return getCurve();
+       }
+
+
+       public void attach(GraphicalTemplateElement e, RelativePosition edgeOrig, RelativePosition edgeDest) throws ExceptionInvalidRNATemplate
+       {
+               super.attach(e,edgeOrig,edgeDest);
+               if (e instanceof Helix)
+               {
+                       EdgeEndPoint e1 = this.getEndPoint(edgeOrig);
+                       EdgeEndPoint e2 = e.getEndPoint(edgeDest);
+                       boolean parity1 = this.isIn(edgeOrig);
+                       boolean parity2 = e.isIn(edgeDest);
+                       if ((e1!=null)&&(e2!=null)&&(parity1!=parity2))
+                       {
+                               e1.disconnect();
+                               e2.disconnect();
+                               e1.connectTo(e2);   
+                       }
+               }
+       }
+
+
+       public EdgeEndPoint getEndPoint(RelativePosition r) {
+               switch(r)
+               {
+               case RP_CONNECT_START5:
+                       return _e.getIn();                              
+               case RP_CONNECT_END3:
+                       return _e.getOut();
+               }
+               return null;
+       }
+
+       public boolean isIn(RelativePosition r) {
+               switch(r)
+               {
+               case RP_CONNECT_START5:
+                       return true;                            
+               case RP_CONNECT_END3:
+                       return false;
+               }
+               return true;
+       }
+
+       public void detach(RelativePosition edge)
+       {
+               // If the underlying template element is still connected, disconnect it
+               if (getEndPoint(edge).isConnected())
+               {
+                       Couple<GraphicalTemplateElement.RelativePosition, GraphicalTemplateElement> c = getAttachedElement(edge);
+                       getEndPoint(edge).disconnect();
+               }
+
+               // Call the parent class detach function, which will also take care to disconnect this other endpoint of this edge
+               super.detach(edge);
+       }
+
+       public void setEdgePosition(RelativePosition edge, Point2D.Double pos) {
+               switch(edge)
+               {
+               case RP_CONNECT_START5:
+                       setEdge5(pos);
+                       break;
+               case RP_INNER_MOVE:
+                       setCenter(pos);
+                       break;
+               case RP_CONNECT_END3:
+                       setEdge3(pos);
+                       break;
+               case RP_EDIT_TANGENT_5:
+                       updateControl5(pos);
+                       break;
+               case RP_EDIT_TANGENT_3:
+                       updateControl3(pos);
+                       break;
+               }
+       }
+
+       public ArrayList<RelativePosition> getConnectedEdges() {
+               ArrayList<RelativePosition> result = new ArrayList<RelativePosition>();
+               result.add(RelativePosition.RP_CONNECT_START5);
+               result.add(RelativePosition.RP_CONNECT_END3);
+               return result;
+       }
+
+       public RNATemplateElement getTemplateElement() {
+               return _e;
+       }
+
+
+       public RelativePosition relativePositionFromEdgeEndPointPosition(
+                       EdgeEndPointPosition pos) {
+               switch (pos) {
+               case IN1:
+                       return RelativePosition.RP_CONNECT_START5;
+               case OUT1:
+                       return RelativePosition.RP_CONNECT_END3;
+               default:
+                       return null;
+               }
+       }
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/components/ActionEditor.java b/src2/fr/orsay/lri/varna/components/ActionEditor.java
new file mode 100644 (file)
index 0000000..204024f
--- /dev/null
@@ -0,0 +1,54 @@
+package fr.orsay.lri.varna.components;
+
+import java.awt.Component;
+import java.awt.Event;
+import java.awt.event.ActionListener;
+import java.util.EventObject;
+
+import javax.swing.AbstractCellEditor;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JPanel;
+import javax.swing.JTable;
+import javax.swing.table.TableCellEditor;
+
+public class ActionEditor extends AbstractCellEditor implements TableCellEditor { 
+
+       JButton _btn = new JButton();
+
+       public ActionEditor (ActionListener a) {
+         // add all elments you need to your panel
+         _btn.addActionListener(a);
+       }
+
+       public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) { 
+          _btn.setText(value.toString());
+          _btn.setActionCommand(value.toString()+"-"+rowIndex);
+          // set all elemnts of you panel to the according values
+          // or add dynamically an action listener
+          
+          return _btn;
+       }
+       public Object getCellEditorValue() 
+       { 
+               return ""; 
+       } 
+       
+       public boolean shouldSelectCell(EventObject anEvent)
+       {
+               return super.shouldSelectCell(anEvent);
+               
+       }
+
+       public boolean isCellEditable(EventObject anEvent)
+       {
+               return super.isCellEditable(anEvent);           
+       }
+       
+       public boolean stopCellEditing()
+       {
+               return super.stopCellEditing();
+       }
+
+       
+} 
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/components/ActionRenderer.java b/src2/fr/orsay/lri/varna/components/ActionRenderer.java
new file mode 100644 (file)
index 0000000..ee88270
--- /dev/null
@@ -0,0 +1,30 @@
+
+package fr.orsay.lri.varna.components;
+
+
+import java.awt.Color;
+import java.awt.Component;
+
+import javax.swing.BorderFactory;
+import javax.swing.JButton;
+import javax.swing.JLabel;
+import javax.swing.JTable;
+import javax.swing.border.Border;
+import javax.swing.table.TableCellRenderer;
+
+public class ActionRenderer extends JButton implements TableCellRenderer {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       public ActionRenderer() {
+       }
+
+       public Component getTableCellRendererComponent(JTable table, Object button,
+                       boolean isSelected, boolean hasFocus, int row, int column) {
+               this.setText(button.toString());
+               return this;
+       }
+}
+
diff --git a/src2/fr/orsay/lri/varna/components/AnnotationTableModel.java b/src2/fr/orsay/lri/varna/components/AnnotationTableModel.java
new file mode 100644 (file)
index 0000000..c84f72e
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.components;
+
+import java.util.ArrayList;
+
+import javax.swing.table.AbstractTableModel;
+
+public class AnnotationTableModel extends AbstractTableModel {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String[] columnNames = { "Annotation" };
+       private ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
+
+
+       public AnnotationTableModel(ArrayList<Object> annot) {
+               ArrayList<Object> ligne;
+               for (int i = 0; i < annot.size(); i++) {
+                       ligne = new ArrayList<Object>();
+                       ligne.add(annot.get(i));
+                       data.add(ligne);
+               }
+
+       }
+
+       public int getColumnCount() {
+               return columnNames.length;
+       }
+
+       public int getRowCount() {
+               return data.size();
+       }
+
+       public String getColumnName(int col) {
+               return columnNames[col];
+       }
+
+       public Object getValueAt(int row, int col) {
+               return data.get(row).get(col);
+       }
+
+       /*
+        * JTable uses this method to determine the default renderer/ editor for
+        * each cell. If we didn't implement this method, then the last column would
+        * contain text ("true"/"false"), rather than a check box.
+        */
+       @SuppressWarnings("unchecked")
+       public Class getColumnClass(int c) {
+               return getValueAt(0, c).getClass();
+       }
+
+       public boolean isCellEditable(int row, int col) {
+               // Note that the data/cell address is constant,
+               // no matter where the cell appears onscreen.
+               if (col < 1) {
+                       return false;
+               } else {
+                       return true;
+               }
+       }
+
+       public void setValueAt(Object value, int row, int col) {
+               data.get(row).set(col, value);
+               fireTableCellUpdated(row, col);
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/components/BaseSpecialColorEditor.java b/src2/fr/orsay/lri/varna/components/BaseSpecialColorEditor.java
new file mode 100644 (file)
index 0000000..d39d74e
--- /dev/null
@@ -0,0 +1,104 @@
+
+package fr.orsay.lri.varna.components;
+
+
+import java.awt.Color;
+import java.awt.Component;
+
+import javax.swing.AbstractCellEditor;
+import javax.swing.JButton;
+import javax.swing.JColorChooser;
+import javax.swing.JDialog;
+import javax.swing.JTable;
+import javax.swing.table.TableCellEditor;
+
+import fr.orsay.lri.varna.controlers.ControleurBaseSpecialColorEditor;
+import fr.orsay.lri.varna.views.VueBases;
+
+public class BaseSpecialColorEditor extends AbstractCellEditor implements
+               TableCellEditor {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+       private Color currentColor;
+       private JButton button;
+       private JColorChooser colorChooser;
+       private JDialog dialog;
+       protected static final String EDIT = "edit";
+       private VueBases _vueBases;
+       private ControleurBaseSpecialColorEditor _controleurSpecialColorEditor;
+
+       public BaseSpecialColorEditor(VueBases vueBases) {
+               // Set up the editor (from the table's point of view),
+               // which is a button.
+               // This button brings up the color chooser dialog,
+               // which is the editor from the user's point of view.
+               button = new JButton();
+               button.setActionCommand(EDIT);
+               _controleurSpecialColorEditor = new ControleurBaseSpecialColorEditor(this);
+               button.addActionListener(_controleurSpecialColorEditor);
+               button.setBorderPainted(false);
+               fireEditingStopped();
+               _vueBases = vueBases;
+
+               // Set up the dialog that the button brings up.
+               colorChooser = new JColorChooser();
+               dialog = JColorChooser.createDialog(button, "Pick a Color", true, // modal
+                               colorChooser, _controleurSpecialColorEditor, // OK button
+                               // handler
+                               null); // no CANCEL button handler
+       }
+
+       // Implement the one CellEditor method that AbstractCellEditor doesn't.
+       public Object getCellEditorValue() {
+               return currentColor;
+       }
+
+       // Implement the one method defined by TableCellEditor.
+       public Component getTableCellEditorComponent(JTable table, Object value,
+                       boolean isSelected, int row, int column) {
+               currentColor = (Color) value;
+               return button;
+       }
+
+       public static long getSerialVersionUID() {
+               return serialVersionUID;
+       }
+
+       public Color getCurrentColor() {
+               return currentColor;
+       }
+
+       public JButton getButton() {
+               return button;
+       }
+
+       public JColorChooser getColorChooser() {
+               return colorChooser;
+       }
+
+       public JDialog getDialog() {
+               return dialog;
+       }
+
+       public static String getEDIT() {
+               return EDIT;
+       }
+
+       public VueBases get_vueBases() {
+               return _vueBases;
+       }
+
+       public ControleurBaseSpecialColorEditor get_controleurSpecialColorEditor() {
+               return _controleurSpecialColorEditor;
+       }
+
+       public void setCurrentColor(Color currentColor) {
+               this.currentColor = currentColor;
+       }
+
+       public void callFireEditingStopped() {
+               fireEditingStopped();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/components/BaseTableModel.java b/src2/fr/orsay/lri/varna/components/BaseTableModel.java
new file mode 100644 (file)
index 0000000..cf04d61
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.components;
+
+import java.awt.Color;
+import java.util.ArrayList;
+
+import javax.swing.table.AbstractTableModel;
+
+import fr.orsay.lri.varna.models.BaseList;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModelBaseStyle;
+
+
+public class BaseTableModel extends AbstractTableModel {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String[] columnNames = { "Numbers", "Base", "Outline Color", "Inner Color",
+                       "Name Color", "Number Color" };
+       private ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
+       private ArrayList<BaseList> _bases;
+       private boolean _singleBases = true;
+
+       public BaseTableModel(ArrayList<BaseList> bases) {
+               _bases = bases;
+               ArrayList<Object> ligne;
+               for (int i = 0; i < bases.size(); i++) {
+                       ligne = new ArrayList<Object>();
+                       BaseList bl  = bases.get(i);
+                       if (bl.size()!=1)
+                       {
+                               _singleBases = false;
+                       }
+                       ligne.add(bl.getNumbers());
+                       ligne.add(bl.getContents());
+                       ligne.add(bl.getAverageOutlineColor());
+                       ligne.add(bl.getAverageInnerColor());
+                       ligne.add(bl.getAverageNameColor());
+                       ligne.add(bl.getAverageNumberColor());
+                       this.data.add(ligne);   
+               }
+
+       }
+
+       public int getColumnCount() {
+               return columnNames.length;
+       }
+
+       public int getRowCount() {
+               return data.size();
+       }
+
+       public String getColumnName(int col) {
+               return columnNames[col];
+       }
+
+       public Object getValueAt(int row, int col) {
+               return data.get(row).get(col);
+       }
+
+       /*
+        * JTable uses this method to determine the default renderer/ editor for
+        * each cell. If we didn't implement this method, then the last column would
+        * contain text ("true"/"false"), rather than a check box.
+        */
+       @SuppressWarnings("unchecked")
+       public Class getColumnClass(int c) {
+               return getValueAt(0, c).getClass();
+       }
+
+       public boolean isCellEditable(int row, int col) {
+               // Note that the data/cell address is constant,
+               // no matter where the cell appears onscreen.
+               if (col < 1) {
+                       return false;
+               } else {
+                       return true;
+               }
+       }
+
+       public void setValueAt(Object value, int row, int col) {
+               data.get(row).set(col, value);
+               if (col == 1 && _singleBases)
+               {
+                       ModeleBase mb = _bases.get(row).getBases().get(0);
+                       mb.setContent(value.toString());
+               }
+               fireTableCellUpdated(row, col);
+
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/components/ColorRenderer.java b/src2/fr/orsay/lri/varna/components/ColorRenderer.java
new file mode 100644 (file)
index 0000000..fa0c285
--- /dev/null
@@ -0,0 +1,52 @@
+
+package fr.orsay.lri.varna.components;
+
+
+import java.awt.Color;
+import java.awt.Component;
+
+import javax.swing.BorderFactory;
+import javax.swing.JLabel;
+import javax.swing.JTable;
+import javax.swing.border.Border;
+import javax.swing.table.TableCellRenderer;
+
+public class ColorRenderer extends JLabel implements TableCellRenderer {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+       Border unselectedBorder = null;
+       Border selectedBorder = null;
+       boolean isBordered = true;
+
+       public ColorRenderer(boolean isBordered) {
+               this.isBordered = isBordered;
+               setOpaque(true); // MUST do this for background to show up.
+       }
+
+       public Component getTableCellRendererComponent(JTable table, Object color,
+                       boolean isSelected, boolean hasFocus, int row, int column) {
+               Color newColor = (Color) color;
+               setBackground(newColor);
+               if (isBordered) {
+                       if (isSelected) {
+                               if (selectedBorder == null) {
+                                       selectedBorder = BorderFactory.createMatteBorder(2, 5, 2,
+                                                       5, table.getSelectionBackground());
+                               }
+                               setBorder(selectedBorder);
+                       } else {
+                               if (unselectedBorder == null) {
+                                       unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2,
+                                                       5, table.getBackground());
+                               }
+                               setBorder(unselectedBorder);
+                       }
+               }
+
+               setToolTipText("RGB value: " + newColor.getRed() + ", "
+                               + newColor.getGreen() + ", " + newColor.getBlue());
+               return this;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/components/GradientEditorPanel.java b/src2/fr/orsay/lri/varna/components/GradientEditorPanel.java
new file mode 100644 (file)
index 0000000..f6d835a
--- /dev/null
@@ -0,0 +1,344 @@
+package fr.orsay.lri.varna.components;
+
+import java.awt.Color;
+import java.awt.Cursor;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+
+import javax.swing.JColorChooser;
+import javax.swing.JPanel;
+
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+
+public class GradientEditorPanel extends JPanel implements MouseListener, MouseMotionListener{
+               ModeleColorMap _mcm;
+               
+               public GradientEditorPanel (ModeleColorMap mcm)
+               { 
+                       _mcm = mcm;
+                       this.addMouseListener( this);
+                       this.addMouseMotionListener(this);
+               }
+               
+               public void setColorMap(ModeleColorMap mcm)
+               {
+                       _mcm = mcm;
+                       repaint();
+                       firePropertyChange("PaletteChanged","a","b");
+               }
+               
+               public ModeleColorMap getColorMap()
+               {
+                       return _mcm;
+               }
+
+               private final static int TRIGGERS_SEMI_WIDTH = 2;
+               private final static int PALETTE_HEIGHT = 11;
+               private final static int REMOVE_HEIGHT = 11;
+               private final static int TOLERANCE = 5;
+               private final static int GAP = 4;
+               private final Color EDGES = Color.gray.brighter();
+               private final Color BUTTONS = Color.LIGHT_GRAY.brighter();
+               
+               public int getStartChoose()
+               {
+                       return getHeight()-PALETTE_HEIGHT-REMOVE_HEIGHT-GAP-1;
+               }
+               
+               public int getEndChoose()
+               {
+                       return getStartChoose()+PALETTE_HEIGHT;
+               }
+               
+               public int getStartRemove()
+               {
+                       return getEndChoose()+GAP;
+               }
+
+               public int getEndRemove()
+               {
+                       return getStartRemove()+REMOVE_HEIGHT;
+               }
+               
+               private int getStripeHeight()
+               {
+                       return getHeight()-PALETTE_HEIGHT-REMOVE_HEIGHT-2*GAP-1;
+               }
+               
+               private Color alterColor(Color c, int inc)
+               {
+                       int nr = Math.min(Math.max(c.getRed()+inc, 0),255);
+                       int ng = Math.min(Math.max(c.getGreen()+inc, 0),255);
+                       int nb = Math.min(Math.max(c.getBlue()+inc, 0),255);
+                       return new Color(nr,ng,nb);
+               }
+
+               public void paintComponent(Graphics g)
+               {
+                       super.paintComponent(g);
+                       Graphics2D g2d = (Graphics2D)  g;
+                       g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+                                       RenderingHints.VALUE_ANTIALIAS_ON);
+                       int height = getStripeHeight();
+                       double v1 = _mcm.getMinValue();
+                       double v2 = _mcm.getMaxValue();
+                       for (int i=0;i<=getWidth();i++)
+                       {
+                               double ratio = (((double)i)/((double)getWidth()));
+                               double val = v1+(v2-v1)*ratio;
+                               g2d.setColor(_mcm.getColorForValue(val));
+                               g2d.drawLine(i, 0, i, height);  
+                       }
+                       for(int i=0;i<_mcm.getNumColors();i++)
+                       {
+                               double val = _mcm.getValueAt(i);
+                               Color c = _mcm.getColorAt(i);
+                               double norm = (val-_mcm.getMinValue())/(_mcm.getMaxValue()-_mcm.getMinValue());
+                               int x = (int)(norm*(getWidth()-1));
+                               // Target
+                               g2d.setColor(c);
+                               g2d.fillRect(x-TRIGGERS_SEMI_WIDTH+1, 0, 2*TRIGGERS_SEMI_WIDTH-1, getHeight()-1);                                       
+                               g2d.setColor(EDGES);
+                               g2d.drawLine(x-TRIGGERS_SEMI_WIDTH, 0, x-TRIGGERS_SEMI_WIDTH, getHeight());                                     
+                               g2d.drawLine(x+TRIGGERS_SEMI_WIDTH, 0, x+TRIGGERS_SEMI_WIDTH, getHeight());
+                               
+                               if (i==0)
+                               {
+                                       // Choose Color
+                                       g2d.setColor(EDGES);
+                                       g2d.drawRect(x,height+GAP,PALETTE_HEIGHT,2*PALETTE_HEIGHT+GAP);                                 
+                                       g2d.setColor(c);
+                                       g2d.fillRect(x+1,height+GAP+1,PALETTE_HEIGHT-1,2*PALETTE_HEIGHT+GAP-1);
+                               }
+                               else if (i==_mcm.getNumColors()-1)
+                               {
+                                       // Choose Color
+                                       g2d.setColor(EDGES);
+                                       g2d.drawRect(x-PALETTE_HEIGHT,height+GAP,PALETTE_HEIGHT,2*PALETTE_HEIGHT+GAP);                                  
+                                       g2d.setColor(c);
+                                       g2d.fillRect(x-PALETTE_HEIGHT+1,height+GAP+1,PALETTE_HEIGHT-1,2*PALETTE_HEIGHT+GAP-1);                                  
+                               }
+                               else
+                               {
+                               // Choose Color
+                               g2d.setColor(EDGES);
+                               g2d.drawRect(x-PALETTE_HEIGHT/2,height+GAP,PALETTE_HEIGHT,PALETTE_HEIGHT);                                      
+                               g2d.setColor(alterColor(c,-15));
+                               g2d.fillRect(x-PALETTE_HEIGHT/2+1,height+GAP+1,PALETTE_HEIGHT-1,PALETTE_HEIGHT-1);                                      
+                               g2d.setColor(c);
+                               g2d.fillOval(x-PALETTE_HEIGHT/2+1,height+GAP+1,PALETTE_HEIGHT-1,PALETTE_HEIGHT-1);
+                               g2d.setColor(alterColor(c,10));
+                               g2d.fillOval(x-PALETTE_HEIGHT/2+1+2,height+GAP+1+2,PALETTE_HEIGHT-1-4,PALETTE_HEIGHT-1-4);
+
+
+                               // Remove Color
+                               g2d.setColor(EDGES);
+                               g2d.drawRect(x-PALETTE_HEIGHT/2,height+2*GAP+PALETTE_HEIGHT,REMOVE_HEIGHT,REMOVE_HEIGHT);                                       
+                               g2d.setColor(BUTTONS);
+                               g2d.fillRect(x-PALETTE_HEIGHT/2+1,height+2*GAP+1+PALETTE_HEIGHT,REMOVE_HEIGHT-1,REMOVE_HEIGHT-1);                                               
+                               int xcross1 = x-PALETTE_HEIGHT/2+2;
+                               int ycross1 = height+2*GAP+PALETTE_HEIGHT +2;
+                               int xcross2 = xcross1+REMOVE_HEIGHT-4;
+                               int ycross2 = ycross1+REMOVE_HEIGHT-4;
+                               g2d.setColor(Color.red);
+                               g2d.drawLine(xcross1, ycross1, xcross2 , ycross2);                              
+                               g2d.drawLine(xcross1, ycross2, xcross2 , ycross1);
+                               }
+                       }
+
+               }
+               
+               private boolean isChooseColor(int x, int y)
+               {
+                       if (_selectedIndex != -1)
+                       {
+                               if ((_selectedIndex ==0)||(_selectedIndex == _mcm.getNumColors()-1))
+                                       return (y<=getEndRemove() && y>=getStartChoose() && Math.abs(getXPos(_selectedIndex)-x)<=PALETTE_HEIGHT);
+                               if (y<=getEndChoose() && y>=getStartChoose())
+                               {
+                                       return Math.abs(getXPos(_selectedIndex)-x)<=PALETTE_HEIGHT/2;
+                               }
+                       }
+                       return false;
+               }
+               
+               private boolean isRemove(int x, int y)
+               {
+                       if (_selectedIndex != -1)
+                       {
+                               if ((_selectedIndex ==0)||(_selectedIndex == _mcm.getNumColors()-1))
+                                       return false;
+                               if (y<=getEndRemove() && y>=getStartRemove())
+                               {
+                                       return Math.abs(getXPos(_selectedIndex)-x)<=PALETTE_HEIGHT/2;
+                               }
+                       }
+                       return false;
+               }
+               
+               private int getXPos(int i)
+               {
+                       double val = _mcm.getValueAt(i);
+                       double norm = (val-_mcm.getMinValue())/(_mcm.getMaxValue()-_mcm.getMinValue());
+                       return (int)(norm*(getWidth()-1));                      
+               }
+
+               
+               private int locateSelectedIndex(int x, int y)
+               {
+                       double dist = Double.MAX_VALUE;
+                       int index = -1;
+                       for(int i=0;i<_mcm.getNumColors();i++)
+                       {
+                               int xp = getXPos(i);
+                               double tmpDist = Math.abs(x-xp);
+                               if (tmpDist<dist)
+                               {
+                                       index = i;
+                                       dist = tmpDist; 
+                               }
+                       }       
+                       return index;
+               }
+               
+               private int _selectedIndex = -1;
+               
+               public void mouseClicked(MouseEvent arg0) {
+                       _selectedIndex = locateSelectedIndex(arg0.getX(),arg0.getY());
+                       if (_selectedIndex!=-1)
+                       {
+                               if (isRemove(arg0.getX(),arg0.getY()))
+                               {
+                                       removeEntry(_selectedIndex);
+                               }
+                               else if (Math.abs(getXPos(_selectedIndex)-arg0.getX())>TOLERANCE)
+                               {
+                                       double val = _mcm.getMinValue()+ arg0.getX()*(_mcm.getMaxValue()-_mcm.getMinValue())/(getWidth()-1);
+                                       Color nc = JColorChooser.showDialog(this, "Choose new color" ,_mcm.getColorAt(_selectedIndex));
+                                       if (nc != null)
+                                       {
+                                               _mcm.addColor(val, nc);
+                                               repaint();
+                                               firePropertyChange("PaletteChanged","a","b");
+                                       }                                       
+                               }
+                       }
+               }
+
+               public void mouseEntered(MouseEvent arg0) {
+                       // TODO Auto-generated method stub
+                       
+               }
+
+               public void mouseExited(MouseEvent arg0) {
+                       // TODO Auto-generated method stub
+                       
+               }
+
+               public void mousePressed(MouseEvent arg0) {
+                       requestFocus();
+                       _selectedIndex = locateSelectedIndex(arg0.getX(),arg0.getY());
+                       if (_selectedIndex!=-1)
+                       {
+                               if (isChooseColor(arg0.getX(),arg0.getY()))
+                               {
+                                       Color nc = JColorChooser.showDialog(this, "Choose new color" ,_mcm.getColorAt(_selectedIndex));
+                                       if (nc != null)
+                                       {
+                                               double nv = _mcm.getValueAt(_selectedIndex);
+                                               replaceEntry(_selectedIndex, nc, nv);
+                                               _selectedIndex = -1;
+                                       }
+                               }
+                       }
+               }
+
+               public void mouseReleased(MouseEvent arg0) {
+                       _selectedIndex = -1;
+               }
+
+               private void replaceEntry(int index, Color nc, double nv)
+               {
+                       ModeleColorMap cm = new ModeleColorMap();
+                       for(int i=0;i<_mcm.getNumColors();i++)
+                       {
+                               if (i!=index)
+                               {
+                                       double val = _mcm.getValueAt(i);
+                                       Color c = _mcm.getColorAt(i);
+                                       cm.addColor(val, c);
+                               }
+                               else
+                               {
+                                       cm.addColor(nv, nc);
+                               }
+                       }
+                       _mcm = cm;
+                       repaint();
+                       firePropertyChange("PaletteChanged","a","b");
+               }
+
+               private void removeEntry(int index)
+               {
+                       ModeleColorMap cm = new ModeleColorMap();
+                       for(int i=0;i<_mcm.getNumColors();i++)
+                       {
+                               if (i!=index)
+                               {
+                                       double val = _mcm.getValueAt(i);
+                                       Color c = _mcm.getColorAt(i);
+                                       cm.addColor(val, c);
+                               }
+                       }
+                       _mcm = cm;
+                       repaint();
+                       firePropertyChange("PaletteChanged","a","b");
+               }
+               
+               
+               public void mouseDragged(MouseEvent arg0) {
+                       if ((_selectedIndex!=-1)&&(_selectedIndex!=0)&&(_selectedIndex!=_mcm.getNumColors()-1))
+                       {
+                               Color c = _mcm.getColorAt(_selectedIndex);
+                               double val = _mcm.getMinValue()+ arg0.getX()*(_mcm.getMaxValue()-_mcm.getMinValue())/(getWidth()-1);
+                               replaceEntry(_selectedIndex, c, val);
+                       }
+               }
+
+               public void mouseMoved(MouseEvent arg0) {
+                       Cursor c = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
+                       _selectedIndex = locateSelectedIndex(arg0.getX(),arg0.getY());
+                       if (_selectedIndex!=-1)
+                       {
+                               if (isChooseColor(arg0.getX(),arg0.getY()))
+                               {
+                                       c = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
+                               }
+                               else if ((_selectedIndex != 0)&&(_selectedIndex != _mcm.getNumColors()-1))
+                               {
+                                       if (isRemove(arg0.getX(),arg0.getY()))
+                                       {
+                                               c = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);                                     
+                                       }
+                                       else if (Math.abs(getXPos(_selectedIndex)-arg0.getX())<=TOLERANCE)
+                                       {
+                                               c = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
+                                       }
+                                       else if (arg0.getY()<getHeight()-this.getStripeHeight())
+                                       {
+                                               c = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);                                                                             
+                                       }
+                                       else
+                                       {
+                                               Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
+                                       }
+                               }
+                       }
+                       setCursor(c);
+               }
+       }
+
diff --git a/src2/fr/orsay/lri/varna/components/ReorderableJList.java b/src2/fr/orsay/lri/varna/components/ReorderableJList.java
new file mode 100644 (file)
index 0000000..791c451
--- /dev/null
@@ -0,0 +1,219 @@
+package fr.orsay.lri.varna.components;
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Cursor;
+import java.awt.Graphics;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DragGestureEvent;
+import java.awt.dnd.DragGestureListener;
+import java.awt.dnd.DragGestureRecognizer;
+import java.awt.dnd.DragSource;
+import java.awt.dnd.DragSourceDragEvent;
+import java.awt.dnd.DragSourceDropEvent;
+import java.awt.dnd.DragSourceEvent;
+import java.awt.dnd.DragSourceListener;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.DropTargetDragEvent;
+import java.awt.dnd.DropTargetDropEvent;
+import java.awt.dnd.DropTargetEvent;
+import java.awt.dnd.DropTargetListener;
+import java.io.IOException;
+
+import javax.swing.DefaultListCellRenderer;
+import javax.swing.DefaultListModel;
+import javax.swing.JList;
+
+public class ReorderableJList extends JList 
+implements DragSourceListener, DropTargetListener, DragGestureListener {
+
+static DataFlavor localObjectFlavor;
+static {
+    try {
+        localObjectFlavor =
+            new DataFlavor (DataFlavor.javaJVMLocalObjectMimeType);
+    } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } 
+} 
+static DataFlavor[] supportedFlavors = { localObjectFlavor }; 
+DragSource dragSource; 
+DropTarget dropTarget; 
+int dropTargetIndex; 
+int draggedIndex = -1;
+
+public ReorderableJList () {
+    super();
+    setCellRenderer (new ReorderableListCellRenderer());
+    setModel (new DefaultListModel());
+    dragSource = new DragSource();
+    DragGestureRecognizer dgr =
+        dragSource.createDefaultDragGestureRecognizer (this,
+                                   DnDConstants.ACTION_MOVE,
+                                                       this);
+    dropTarget = new DropTarget (this, this);
+}
+
+// DragGestureListener
+public void dragGestureRecognized (DragGestureEvent dge) {
+    //System.out.println ("dragGestureRecognized");
+    // find object at this x,y
+    Point clickPoint = dge.getDragOrigin();
+    int index = locationToIndex(clickPoint);
+    if (index == -1)
+        return;
+    Object target = getModel().getElementAt(index);
+    Transferable trans = new RJLTransferable (target);
+    draggedIndex = index;
+    dragSource.startDrag (dge,Cursor.getDefaultCursor(),
+                          trans, this);
+}
+// DragSourceListener events
+public void dragDropEnd (DragSourceDropEvent dsde) {
+   //System.out.println ("dragDropEnd()");
+   dropTargetIndex = -1;
+   draggedIndex = -1;
+   repaint();
+}
+public void dragEnter (DragSourceDragEvent dsde) {}
+public void dragExit (DragSourceEvent dse) {}
+public void dragOver (DragSourceDragEvent dsde) {}
+public void dropActionChanged (DragSourceDragEvent dsde) {}
+// DropTargetListener events
+public void dragEnter (DropTargetDragEvent dtde) {
+    //System.out.println ("dragEnter");
+    if (dtde.getSource() != dropTarget)
+        dtde.rejectDrag();
+    else {
+        dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
+        //System.out.println ("accepted dragEnter");
+    }
+}
+public void dragExit (DropTargetEvent dte) {}
+
+public void dropActionChanged (DropTargetDragEvent dtde) {}
+
+public void dragOver (DropTargetDragEvent dtde) { 
+    // figure out which cell it's over, no drag to self    
+    if (dtde.getSource() != dropTarget)
+        dtde.rejectDrag();
+    Point dragPoint = dtde.getLocation();
+    int index = locationToIndex (dragPoint);
+    dropTargetIndex = index;
+    if (dropTargetIndex != -1)
+    {
+       Rectangle r = getCellBounds(dropTargetIndex,dropTargetIndex);
+        if (dragPoint.y > r.y+r.height/2)
+        {
+               dropTargetIndex += 1;           
+        }
+    }
+    //System.out.println(dropTargetIndex);
+    repaint(); 
+}
+
+public void drop (DropTargetDropEvent dtde) {    
+    //System.out.println ("drop()!");    
+    if (dtde.getSource() != dropTarget) {
+        //System.out.println ("rejecting for bad source (" +
+        //                    dtde.getSource().getClass().getName() + ")");        
+        dtde.rejectDrop(); 
+        return;
+    }
+    Point dropPoint = dtde.getLocation();
+    int index = locationToIndex (dropPoint);
+    if (index != -1)
+    {
+       Rectangle r = getCellBounds(index,index);
+        if (dropPoint.y > r.y+r.height/2)
+        {
+               index += 1;             
+        }
+    }
+    
+    //System.out.println ("drop index is " + index);
+    boolean dropped = false;
+    try {
+        if ((index == -1) || (index == draggedIndex)|| (index == draggedIndex+1)) {
+            //System.out.println ("dropped onto self");
+            dtde.rejectDrop();
+            return;
+        }
+        dtde.acceptDrop (DnDConstants.ACTION_MOVE);
+        //System.out.println ("accepted");
+        Object dragged =
+           dtde.getTransferable().getTransferData(localObjectFlavor);
+        // move items - note that indicies for insert will 
+        // change if [removed] source was before target 
+        //System.out.println ("drop " + draggedIndex + " to " + index);
+        boolean sourceBeforeTarget = (draggedIndex < index); 
+        //System.out.println ("source is" +
+        //                    (sourceBeforeTarget ? "" : " not") +
+        //                    " before target");
+        //System.out.println ("insert at " +
+        //                    (sourceBeforeTarget ? index-1 : index));
+         DefaultListModel mod = (DefaultListModel) getModel(); 
+        mod.remove (draggedIndex); 
+        mod.add ((sourceBeforeTarget ? index-1 : index), dragged); 
+        dropped = true;
+    } catch (Exception e) {
+        e.printStackTrace();
+    }
+    dtde.dropComplete (dropped);
+}
+
+private class ReorderableListCellRenderer 
+extends DefaultListCellRenderer { 
+boolean isTargetCell; 
+boolean isLastItem;    
+public ReorderableListCellRenderer() {
+    super();
+}
+public Component getListCellRendererComponent (JList list,
+                                               Object value, 
+                                               int index, 
+                                               boolean isSelected,                                                  boolean hasFocus) {
+    isTargetCell = (index == dropTargetIndex);
+    isLastItem = (index == list.getModel().getSize()-1) && (dropTargetIndex == list.getModel().getSize());
+    boolean showSelected = isSelected;
+    return super.getListCellRendererComponent (list, value, 
+                                               index, showSelected,                                                 
+                                               hasFocus);
+}
+public void paintComponent (Graphics g) {
+    super.paintComponent(g);
+    if (isTargetCell) {
+        g.setColor(Color.black);            
+        g.drawLine (0, 0, getSize().width, 0); 
+    } 
+    if (isLastItem) {
+        g.setColor(Color.black);            
+        g.drawLine (0, getSize().height-1, getSize().width, getSize().height-1); 
+    } 
+ } 
+}
+
+private class RJLTransferable implements Transferable { 
+    Object object; 
+    public RJLTransferable (Object o) {
+        object = o;
+    }
+    public Object getTransferData(DataFlavor df)
+        throws UnsupportedFlavorException, IOException {
+        if (isDataFlavorSupported (df))
+            return object;
+        else
+           throw new UnsupportedFlavorException(df);
+    }
+    public boolean isDataFlavorSupported (DataFlavor df) {
+        return (df.equals (localObjectFlavor));
+    }
+    public DataFlavor[] getTransferDataFlavors () {
+        return supportedFlavors; } 
+}
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/components/VARNAConsole.java b/src2/fr/orsay/lri/varna/components/VARNAConsole.java
new file mode 100644 (file)
index 0000000..2b8b8a9
--- /dev/null
@@ -0,0 +1,119 @@
+package fr.orsay.lri.varna.components;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.io.IOException;
+
+import javax.swing.JButton;
+import javax.swing.JEditorPane;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurScriptParser;
+import fr.orsay.lri.varna.models.VARNAConfig;
+
+public class VARNAConsole extends JFrame implements ActionListener, FocusListener, KeyListener {
+
+  private VARNAPanel _vp;
+       
+  private JButton _quitButton; 
+  private JPanel _contentPanel; 
+  private JPanel _quitPanel; 
+  private JTextField _input; 
+  private JEditorPane _output; 
+  private JScrollPane _scrolls; 
+       
+  public VARNAConsole(VARNAPanel vp)
+  {
+         _vp = vp;
+         init();
+  }
+  
+  private void init()
+  {
+         _quitButton = new JButton("Exit");
+         _quitPanel = new JPanel();
+         _contentPanel = new JPanel();
+         _input = new JTextField("Your command here...");
+         _output = new JEditorPane();
+         _scrolls = new JScrollPane(_output);
+
+         _input.addFocusListener(this);
+         _input.addKeyListener(this);
+         
+         _output.setText(VARNAConfig.getFullName()+" console\n");
+         _output.setPreferredSize(new Dimension(500,300));
+         _output.setEditable(false);
+         
+         _quitPanel.add(_quitButton);
+         
+         _quitButton.addActionListener(this);
+         
+         _contentPanel.setLayout(new BorderLayout());
+         _contentPanel.add(_scrolls,BorderLayout.CENTER);
+         _contentPanel.add(_input,BorderLayout.SOUTH);
+
+         getContentPane().setLayout(new BorderLayout());
+         getContentPane().add(_contentPanel,BorderLayout.CENTER);
+         getContentPane().add(_quitPanel,BorderLayout.SOUTH);
+         
+         pack();
+  }
+
+public void actionPerformed(ActionEvent arg0) {
+       setVisible(false);
+}
+
+private boolean _firstFocus = true;
+
+public void focusGained(FocusEvent arg0) {
+       if (_firstFocus)
+       {
+               _input.setSelectionStart(0);
+               _input.setSelectionEnd(_input.getText().length());
+               _firstFocus = false;
+       }
+}
+
+public void focusLost(FocusEvent arg0) {
+       // TODO Auto-generated method stub
+       
+}
+
+public void keyPressed(KeyEvent arg0) {
+       // TODO Auto-generated method stub
+       
+}
+
+public void keyReleased(KeyEvent arg0) {
+       // TODO Auto-generated method stub
+       
+}
+
+public void keyTyped(KeyEvent arg0) {
+       // TODO Auto-generated method stub
+       char c = arg0.getKeyChar();
+       if (c=='\n')
+       {
+               try {
+                       ControleurScriptParser.executeScript(_vp,_input.getText());
+               } catch (Exception e) {
+                       _output.setText(_output.getText()+e.getMessage()+'\n');
+                       e.printStackTrace();
+               }
+       }
+}
+  
+  
+  
+}
diff --git a/src2/fr/orsay/lri/varna/components/ZoomWindow.java b/src2/fr/orsay/lri/varna/components/ZoomWindow.java
new file mode 100644 (file)
index 0000000..4003e69
--- /dev/null
@@ -0,0 +1,185 @@
+package fr.orsay.lri.varna.components;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Point;
+import java.awt.Polygon;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.geom.Point2D.Double;
+import java.awt.image.BufferedImage;
+import java.awt.image.ImageObserver;
+
+import javax.swing.JPanel;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.export.SwingGraphics;
+import fr.orsay.lri.varna.models.export.VueVARNAGraphics;
+
+public class ZoomWindow extends JPanel implements ImageObserver, Runnable, MouseMotionListener, MouseListener {
+
+       VARNAPanel _vp = null;
+       BufferedImage _bi = null;
+       Rectangle2D.Double rnaRect = null;
+       
+       public ZoomWindow(VARNAPanel vp)
+       {
+               _vp = vp;
+               addMouseMotionListener(this);
+               addMouseListener(this);
+       }
+       
+       
+       public synchronized void setPanel(VARNAPanel vp)
+       {
+               _vp = vp; 
+       }
+       
+       
+       
+       public synchronized void drawPanel()
+       {
+               if (getWidth()>0 && getHeight()>0)
+               {
+                       _bi= new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
+                       Graphics2D g2 = _bi.createGraphics();
+                       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+                               RenderingHints.VALUE_ANTIALIAS_ON);
+                       VueVARNAGraphics g2D = new SwingGraphics(g2);
+                       rnaRect =_vp.renderRNA(g2D,new Rectangle2D.Double(0,0,getWidth(),getHeight()),false,true);
+                       
+                       Point2D.Double p1 = _vp.panelToLogicPoint(new Point2D.Double(0.,0.));
+                       Point2D.Double p2 = _vp.panelToLogicPoint(new Point2D.Double(_vp.getWidth(),_vp.getHeight()));
+                       
+                       double w = p2.x-p1.x; 
+                       double h = p2.y-p1.y;
+                                               
+                       Rectangle2D.Double rnaBox = _vp.getRNA().getBBox();
+                       
+                       double ratiox = w/rnaBox.width;
+                       double ratioy = h/rnaBox.height;
+                       
+                       Rectangle2D.Double rvisible = new Rectangle2D.Double(rnaRect.x+rnaRect.width*(double)(p1.x-rnaBox.x)/(double)rnaBox.width,
+                                       rnaRect.y+rnaRect.height*(double)(p1.y-rnaBox.y)/(double)rnaBox.height,
+                                       ratiox*rnaRect.width,
+                                       ratioy*rnaRect.height);
+                       
+                       //g2D.drawRect(rleft.x,rleft.y,rleft.width,rleft.height);
+                       
+                       Color shade = new Color(.9f,.9f,.9f,.4f);
+                       
+                       g2.setStroke(new BasicStroke(1.0f));
+
+                       g2.setColor(shade);
+                       
+                       /*Polygon north = new Polygon(new int[]{0,getWidth(),(int)rvisible.x,
+                                       (int)(rvisible.x+rvisible.width+1),},new int[]{},1);*/
+                       g2.fillRect(0,0,getWidth(),(int)rvisible.y);
+                       g2.fillRect(0,(int)rvisible.y,(int)rvisible.x,(int)rvisible.height+1);
+                       g2.fillRect((int)(rvisible.x+rvisible.width),(int)rvisible.y,(int)(getHeight()-(rvisible.x+rvisible.width)),(int)(rvisible.height+1));
+                       g2.fillRect(0,(int)(rvisible.y+rvisible.height),getWidth(),(int)(getHeight()-(rvisible.y+rvisible.height)));
+
+                       g2.setColor(new Color(.7f,.7f,.7f,.3f));
+                       g2.draw(rvisible);
+                       g2.drawLine(0,
+                                       0,
+                                       (int)rvisible.x,
+                                       (int)rvisible.y);
+                       g2D.drawLine(getWidth(),
+                                       0,
+                                       rvisible.x+rvisible.width,
+                                       rvisible.y);
+                       g2D.drawLine(getWidth(),
+                                       getHeight(),
+                                       rvisible.x+rvisible.width,
+                                       rvisible.y+rvisible.height);
+                       g2D.drawLine(0,
+                                       getHeight(),
+                                       rvisible.x,
+                                       rvisible.y+rvisible.height);
+
+                       g2.dispose();
+               }
+       }
+       
+       public void paintComponent(Graphics g)
+       {
+               setBackground(_vp.getBackground());
+               super.paintComponent(g);
+               drawPanel();
+               if (_bi!=null)
+               {
+                       g.drawImage(_bi,0,0,this);
+               }
+       }
+
+       public void run() {
+               while(true)
+               {
+                       repaint();
+                       try {
+                               Thread.sleep(500);
+                       } catch (InterruptedException e) {
+                               e.printStackTrace();
+                       }
+                       
+               }
+       }
+
+
+       public void mouseDragged(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void mouseMoved(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void mouseClicked(MouseEvent e) {
+               /*if (rnaRect!=null)
+               {
+                       int x= e.getX();
+                       int y= e.getY();
+                       double ratioX = ((double)(x-rnaRect.getMinX())/((double)rnaRect.width));
+                       double ratioY = ((double)(y-rnaRect.getMinY())/((double)rnaRect.height));
+                       _vp.centerViewOn(ratioX,ratioY );
+               }*/
+       }
+
+
+       public void mousePressed(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void mouseReleased(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void mouseEntered(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+       public void mouseExited(MouseEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurBPHeightIncrement.java b/src2/fr/orsay/lri/varna/controlers/ControleurBPHeightIncrement.java
new file mode 100644 (file)
index 0000000..87866e1
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.views.VueBPHeightIncrement;
+
+
+public class ControleurBPHeightIncrement implements ChangeListener {
+
+       private VueBPHeightIncrement _vsbb;
+
+       public ControleurBPHeightIncrement(VueBPHeightIncrement vsbb) {
+               _vsbb = vsbb;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               _vsbb.get_vp().setBPHeightIncrement(_vsbb.getIncrement());
+               _vsbb.get_vp().drawRNA();
+               _vsbb.get_vp().repaint();
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurBaseSpecialColorEditor.java b/src2/fr/orsay/lri/varna/controlers/ControleurBaseSpecialColorEditor.java
new file mode 100644 (file)
index 0000000..b0700cc
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Color;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ComponentEvent;
+import java.awt.event.ComponentListener;
+
+import fr.orsay.lri.varna.components.BaseSpecialColorEditor;
+import fr.orsay.lri.varna.models.BaseList;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+
+/**
+ * BH SwingJS - additions here to allow asynchronous JColorChooser  
+ */
+public class ControleurBaseSpecialColorEditor implements ActionListener, ComponentListener {  // BH SwingJS
+
+       private BaseSpecialColorEditor _specialColorEditor;
+
+       private int _selectedRow;
+       private int _selectedCol;
+       private Color _selectedColor;
+       private String _selectedColTitle;
+
+       public ControleurBaseSpecialColorEditor(BaseSpecialColorEditor specialColorEditor) {
+               _specialColorEditor = specialColorEditor;
+       }
+
+       /**
+        * Handles events from the editor button and from the dialog's OK button.
+        */
+       public void actionPerformed(ActionEvent e) {
+               if (BaseSpecialColorEditor.getEDIT().equals(e.getActionCommand())) {
+                       // The user has clicked the cell, so
+                       // bring up the dialog.
+                       _specialColorEditor.getButton().setBackground(
+                                       _specialColorEditor.getCurrentColor());
+                       _specialColorEditor.getColorChooser().setColor(
+                                       _specialColorEditor.getCurrentColor());
+                       
+                       // BH SwingJS in JavaScript, this is not modal. 
+                       // We have to set a callback to stop the editing.
+                       
+                       _specialColorEditor.getDialog().removeComponentListener(this);
+                       _specialColorEditor.getDialog().addComponentListener(this);
+                       _specialColorEditor.getDialog().setVisible(true);
+                       
+                       
+                       // Make the renderer reappear.
+                       // BH SwingJS not so fast...
+                       //_specialColorEditor.callFireEditingStopped();
+
+               } else { // User pressed dialog's "OK" button.
+                       _specialColorEditor.setCurrentColor(_specialColorEditor
+                                       .getColorChooser().getColor());
+
+                       _selectedRow = _specialColorEditor.get_vueBases().getTable()
+                                       .getSelectedRow();
+
+                       _selectedCol = _specialColorEditor.get_vueBases().getTable()
+                                       .getSelectedColumn();
+
+                       _selectedColor = _specialColorEditor.getCurrentColor();
+
+                       _selectedColTitle = _specialColorEditor.get_vueBases()
+                                       .getSpecialTableModel().getColumnName(_selectedCol);
+                       BaseList lb = _specialColorEditor.get_vueBases().getDataAt(_selectedRow);
+                       for(ModeleBase mb: lb.getBases())
+                       {
+                               applyColor(_selectedColTitle, _selectedColor,mb);
+                       }
+                       _specialColorEditor.get_vueBases().get_vp().repaint();
+               }
+       }
+
+
+       private void applyColor(String titreCol, Color couleur, ModeleBase mb) {
+               if (titreCol.equals("Inner Color")) {
+                       mb.getStyleBase()
+                                       .setBaseInnerColor(couleur);
+               } else if (titreCol.equals("Outline Color")) {
+                       mb.getStyleBase()
+                                       .setBaseOutlineColor(couleur);
+               } else if (titreCol.equals("Name Color")) {
+                       mb.getStyleBase()
+                                       .setBaseNameColor(couleur);
+               } else if (titreCol.equals("Number Color")) {
+                       mb.getStyleBase()
+                                       .setBaseNumberColor(couleur);
+               }
+
+       }
+
+
+       @Override
+       public void componentResized(ComponentEvent e) {
+       }
+
+       @Override
+       public void componentMoved(ComponentEvent e) {
+       }
+
+       @Override
+       public void componentShown(ComponentEvent e) {
+       }
+
+       @Override
+       public void componentHidden(ComponentEvent e) {
+               
+               _specialColorEditor.callFireEditingStopped(); // BH SwingJS -- need to catch this
+               
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurBlinkingThread.java b/src2/fr/orsay/lri/varna/controlers/ControleurBlinkingThread.java
new file mode 100644 (file)
index 0000000..c01619d
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.Timer;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+/**
+ * BH SwingJS converted to Timer mechanism for compatibility with JavaScript 
+ *
+ */
+public class ControleurBlinkingThread extends Thread implements ActionListener {
+       public static final long DEFAULT_FREQUENCY = 50;
+       private long _period;
+       private VARNAPanel _parent;
+       private double _minVal, _maxVal, _val, _incr;
+       private boolean _increasing = true;
+       private boolean _active = false;
+
+       public ControleurBlinkingThread(VARNAPanel vp) {
+               this(vp, DEFAULT_FREQUENCY, 0, 1.0, 0.0, 0.2);
+       }
+
+       public ControleurBlinkingThread(VARNAPanel vp, long period, double minVal,
+                       double maxVal, double val, double incr) {
+               _parent = vp;
+               _period = period;
+               _minVal = minVal;
+               _maxVal = maxVal;
+               _incr = incr;
+       }
+
+       public void setActive(boolean b) {
+               if (_active == b)
+               {}
+               else
+               {
+               _active = b;
+               if (_active) {
+                       interrupt();
+               }
+               }
+       }
+
+       public boolean getActive() {
+               return _active;
+       }
+       
+       
+       public double getVal() {
+               return _val;
+       }
+
+       protected final int START = 0;
+       protected final int LOOP = 1;
+       protected final int STOP = -1;
+       
+       protected int nextMode = START;
+       private Timer timer;
+       
+       
+       public void interrupt() {
+               super.interrupt();
+               stopTimer();
+               run();
+       }
+       
+       @Override
+       public void actionPerformed(ActionEvent e) {
+               run();
+       }
+       public void run() {
+       //   same as:
+       //                      while (true) {
+       //                      try {
+       //                              if (_active) {
+       //                                      sleep(_period);
+       //                                      if (_increasing) {
+       //                                              _val = Math.min(_val + _incr, _maxVal);
+       //                                              if (_val == _maxVal) {
+       //                                                      _increasing = false;
+       //                                              }
+       //                                      } else {
+       //                                              _val = Math.max(_val - _incr, _minVal);
+       //                                              if (_val == _minVal) {
+       //                                                      _increasing = true;
+       //                                              }
+       //                                      }
+       //                                      _parent.repaint();
+       //                              } else {
+       //                                      sleep(10000);
+       //                              }
+       //                      } catch (InterruptedException e) {
+       //                      }
+       //              }
+               long delay = 0;
+               while (true) { 
+                       try {
+                               switch (nextMode) {
+                               case START:
+                                       if (_active) {
+                                               delay = _period;
+                                               nextMode = LOOP;
+                                       } else {
+                                               delay = 10000;
+                                               nextMode = START;
+                                       }
+                                       startTimer(delay);
+                                       return;
+                               case STOP:
+                                       break;
+                               case LOOP:
+                                       if (_increasing) {
+                                               _val = Math.min(_val + _incr, _maxVal);
+                                               if (_val == _maxVal) {
+                                                       _increasing = false;
+                                               }
+                                       } else {
+                                               _val = Math.max(_val - _incr, _minVal);
+                                               if (_val == _minVal) {
+                                                       _increasing = true;
+                                               }
+                                       }
+                                       _parent.repaint();
+                                       nextMode = START;
+                                       continue;
+                               }
+                               sleep(0);
+                       } catch (InterruptedException e) {
+                               // ignore??
+                       }
+                       break;
+                       }
+       }
+
+       private void startTimer(long delay) {
+               stopTimer();
+               timer = new Timer((int) delay, this);
+               timer.setRepeats(false);
+               timer.start();
+       }
+
+       private void stopTimer() {
+               if (timer != null) {
+                       timer.stop();
+                       timer = null;
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurBorder.java b/src2/fr/orsay/lri/varna/controlers/ControleurBorder.java
new file mode 100644 (file)
index 0000000..dd54466
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Dimension;
+
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.views.VueBorder;
+
+
+public class ControleurBorder implements ChangeListener {
+
+       private VueBorder _vb;
+
+       public ControleurBorder(VueBorder vb) {
+               _vb = vb;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               if (_vb.getDimension().getHeight() < _vb.get_vp().getHeight()
+                               && _vb.getDimension().getWidth() < _vb.get_vp().getWidth()) {
+                       _vb.get_vp().setBorderSize(_vb.getDimension());
+                       _vb.get_vp().setMinimumSize(
+                                       new Dimension(_vb.get_vp().getBorderSize().width * 2, _vb
+                                                       .get_vp().getBorderSize().height * 2));
+                       _vb.get_vp().repaint();
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurClicMovement.java b/src2/fr/orsay/lri/varna/controlers/ControleurClicMovement.java
new file mode 100644 (file)
index 0000000..4212106
--- /dev/null
@@ -0,0 +1,688 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Component;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Vector;
+
+import javax.swing.JMenu;
+import javax.swing.JMenuItem;
+import javax.swing.event.PopupMenuEvent;
+import javax.swing.event.PopupMenuListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleBasesComparison;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+/**
+ * Controller of the mouse click
+ * 
+ * @author darty
+ * 
+ */
+public class ControleurClicMovement implements MouseListener,
+               MouseMotionListener, PopupMenuListener {
+       private VARNAPanel _vp;
+       private boolean _presenceMenuSelection;
+       private JMenu _submenuSelection;
+       public Point _spawnPoint;       
+       public Point _initialPoint;
+       public Point _prevPoint;
+       public Point _currentPoint;
+
+       public static final double MIN_SELECTION_DISTANCE = 40.0;
+       public static final double HYSTERESIS_DISTANCE = 10.0;
+       
+       private ModeleBase _selectedBase = null;
+       
+       
+       public enum MouseStates {
+               NONE,
+               MOVE_ELEMENT,
+               MOVE_OR_SELECT_ELEMENT,
+               SELECT_ELEMENT,
+               SELECT_REGION_OR_UNSELECT,
+               SELECT_REGION,
+               CREATE_BP,
+               POPUP_MENU,
+               MOVE_ANNOTATION,
+       };
+       private MouseStates _currentState = MouseStates.NONE;
+       
+
+
+       public ControleurClicMovement(VARNAPanel _vuep) {
+               _vp = _vuep;
+               _vp.getPopup().addPopupMenuListener(this);
+               _presenceMenuSelection = false;
+       }
+
+       public void mouseClicked(MouseEvent arg0) {
+       }
+
+       public void mouseEntered(MouseEvent arg0) {
+       }
+
+       public void mouseExited(MouseEvent arg0) {
+       }
+
+       public void mousePressed(MouseEvent arg0) 
+       {
+               _vp.requestFocus();
+               boolean button1 = (arg0.getButton() == MouseEvent.BUTTON1);
+               boolean button2 = (arg0.getButton() == MouseEvent.BUTTON2);
+               boolean button3 = (arg0.getButton() == MouseEvent.BUTTON3);
+               boolean shift = arg0.isShiftDown();
+               boolean ctrl = arg0.isControlDown();
+               boolean alt = arg0.isAltDown();
+               _vp.removeSelectedAnnotation();
+               if (button1 && !ctrl && !alt && !shift)
+               {
+                       if (_vp.isModifiable()) 
+                       {
+                               _currentState = MouseStates.MOVE_OR_SELECT_ELEMENT;
+                               if (_vp.getRealCoords() != null
+                                               && _vp.getRealCoords().length != 0
+                                               && _vp.getRNA().get_listeBases().size() != 0) 
+                               {
+                                       _selectedBase = _vp.getNearestBase(arg0.getX(),arg0.getY(),false,false);
+                                       TextAnnotation selectedAnnotation = _vp.getNearestAnnotation(arg0.getX(), arg0.getY());
+                                       _initialPoint = new Point(arg0.getX(),arg0.getY());
+                                       _currentPoint = new Point(_initialPoint);
+                                       _prevPoint = new Point(_initialPoint);
+                                       if (_selectedBase != null)
+                                       { 
+                                               if (_vp.getRNA().get_drawMode() == RNA.DRAW_MODE_RADIATE) 
+                                               {
+                                                       _vp.highlightSelectedBase(_selectedBase);
+                                               } else {
+                                                       if (!_vp.getSelectionIndices().contains(_selectedBase.getIndex()))
+                                                       {
+                                                               _vp.highlightSelectedBase(_selectedBase);
+                                                       }
+                                                       else
+                                                       {
+                                                         // Otherwise, keep current selection as it is and move it
+                                                       }
+                                               }
+                                       }
+                                       else
+                                       {
+                                               if (selectedAnnotation != null)
+                                               {
+                                                       _currentState = MouseStates.MOVE_ANNOTATION;
+                                                       _vp.set_selectedAnnotation(selectedAnnotation);
+                                                       _vp.highlightSelectedAnnotation();
+                                               }
+                                               else
+                                               {
+                                                       _vp.clearSelection();
+                                                       _selectedBase = null;
+                                                       _currentState = MouseStates.SELECT_REGION_OR_UNSELECT;
+                                                       _initialPoint = new Point(arg0.getX(),arg0.getY());
+                                                       _prevPoint = new Point(_initialPoint);
+                                                       _currentPoint = new Point(_initialPoint);
+                                               }
+                                       }
+                               }
+                       }
+               }
+               else if (button1 && ctrl && !alt && !shift)
+               {
+                       _selectedBase = _vp.getNearestBase(arg0.getX(),arg0.getY(),false,false);
+                       if (_selectedBase != null)
+                       { 
+                               _vp.clearSelection();
+                               _currentState = MouseStates.CREATE_BP;
+                               _vp.highlightSelectedBase(_selectedBase);
+                               _vp.setOriginLink(_vp.logicToPanel(_selectedBase.getCoords()));
+                               _initialPoint = new Point(arg0.getX(),arg0.getY());
+                               _currentPoint = new Point(_initialPoint);
+                       }
+               }
+               else if (button1 && !ctrl && !alt && shift)
+               {
+                       _currentState = MouseStates.SELECT_ELEMENT;
+                       _initialPoint = new Point(arg0.getX(),arg0.getY());
+                       _currentPoint = new Point(_initialPoint);
+               }
+               else if (button3) 
+               {
+                       _currentState = MouseStates.POPUP_MENU;
+                       if (_presenceMenuSelection) {
+                               _vp.getPopupMenu().removeSelectionMenu();
+                       }
+                       if ((_vp.getRealCoords() != null) && _vp.getRNA().get_listeBases().size() != 0) {
+                               updateNearestBase(arg0);
+                               // on insere dans le menu les nouvelles options
+                               addMenu(arg0);
+                               if (_vp.get_selectedAnnotation() != null)
+                                       _vp.highlightSelectedAnnotation();
+                       }
+                       // affichage du popup menu
+                       if (_vp.getRNA().get_drawMode() == RNA.DRAW_MODE_LINEAR) {
+                               _vp.getPopup().get_rotation().setEnabled(false);
+                       } else {
+                               _vp.getPopup().get_rotation().setEnabled(true);
+                       }
+                       _vp.getPopup().updateDialog();
+                       _vp.getPopup().show(_vp, arg0.getX(), arg0.getY());
+               }
+               _vp.repaint();
+       }
+
+       public void mouseDragged(MouseEvent me) {
+               if ((_currentState == MouseStates.MOVE_OR_SELECT_ELEMENT)||(_currentState == MouseStates.MOVE_ELEMENT))
+               {
+                       _vp.lockScrolling();
+
+                       _currentState = MouseStates.MOVE_ELEMENT;
+                               // si on deplace la souris et qu'une base est selectionnée
+                               if (_selectedBase != null) {
+                                       if (_vp.getRNA().get_drawMode() == RNA.DRAW_MODE_RADIATE) {
+                                               _vp.highlightSelectedStem(_selectedBase);
+                                               // dans le cas radiale on deplace une helice
+                                               _vp.getVARNAUI().UIMoveHelixAtom(_selectedBase.getIndex(), _vp.panelToLogicPoint(new Point2D.Double(me.getX(), me.getY())));
+                                       } else {
+                                               // dans le cas circulaire naview ou line on deplace une base
+                                               _currentPoint = new Point(me.getX(), me.getY());
+                                               moveSelection(_prevPoint,_currentPoint);
+                                               _prevPoint = new Point(_currentPoint);
+                                       }
+                                       _vp.repaint();
+                               }
+               }
+               else if (_currentState == MouseStates.MOVE_ANNOTATION)
+               {
+                       if (_vp.get_selectedAnnotation()!=null)
+                       {
+                               Point2D.Double p = _vp.panelToLogicPoint(new Point2D.Double(me.getX(), me.getY()));
+                               _vp.get_selectedAnnotation().setAncrage(p.x,p.y);
+                               _vp.repaint();
+                       }                       
+               }
+               else if ((_currentState == MouseStates.SELECT_ELEMENT)||(_currentState == MouseStates.SELECT_REGION_OR_UNSELECT))
+               {
+                       if (_initialPoint.distance(me.getX(),me.getY())>HYSTERESIS_DISTANCE)
+                               _currentState = MouseStates.SELECT_REGION;
+               }
+               else if (_currentState == MouseStates.SELECT_REGION)
+               {
+                       _currentPoint = new Point(me.getX(),me.getY());
+                       int minx = Math.min(_currentPoint.x, _initialPoint.x);
+                       int miny = Math.min(_currentPoint.y, _initialPoint.y);
+                       int maxx = Math.max(_currentPoint.x, _initialPoint.x);
+                       int maxy = Math.max(_currentPoint.y, _initialPoint.y);
+                       _vp.setSelectionRectangle(new Rectangle(minx,miny,maxx-minx,maxy-miny));
+               }
+               else if (_currentState == MouseStates.CREATE_BP)
+               {
+                       if (_initialPoint.distance(me.getX(),me.getY())>HYSTERESIS_DISTANCE)
+                       {
+                               ModeleBase newSelectedBase = _vp.getNearestBase(me.getX(),me.getY(),false,false);
+                               _vp.setHoverBase(newSelectedBase);
+                               if (newSelectedBase==null)
+                               {
+                                       _vp.setDestinationLink(new Point2D.Double(me.getX(),me.getY()));
+                                       _vp.clearSelection();
+                                       _vp.addToSelection(_selectedBase.getIndex());
+                               }
+                               else
+                               {
+                                       ModeleBase mborig = _selectedBase;
+                                       _vp.clearSelection();
+                                       _vp.addToSelection(newSelectedBase.getIndex());
+                                       _vp.addToSelection(mborig.getIndex());
+                                       _vp.setDestinationLink(_vp.logicToPanel(newSelectedBase.getCoords()));
+                               }
+                               _vp.repaint();
+                       }
+                       
+               }
+       }
+
+
+       public void mouseReleased(MouseEvent arg0) {
+               if (arg0.getButton() == MouseEvent.BUTTON1)
+               {
+                       _vp.fireBaseClicked(_selectedBase, arg0);       
+                       //System.out.println(""+_currentState);
+                       
+                       if (_currentState == MouseStates.MOVE_ELEMENT)
+                       {
+                               _vp.clearSelection();
+                               _selectedBase = null;
+                               _vp.unlockScrolling();
+                               _vp.removeSelectedAnnotation();
+                       }
+                       else if (_currentState == MouseStates.SELECT_REGION_OR_UNSELECT)
+                       {
+                               _vp.clearSelection();
+                               _selectedBase = null;
+                               _vp.removeSelectedAnnotation();
+                       }
+                       else if (_currentState == MouseStates.SELECT_ELEMENT)
+                       {
+                               if (_vp.getRealCoords() != null
+                                               && _vp.getRealCoords().length != 0
+                                               && _vp.getRNA().get_listeBases().size() != 0) 
+                                       {
+                                               int selectedIndex = _vp.getNearestBaseIndex(arg0.getX(),arg0.getY(),false,false);
+                                               if (selectedIndex !=-1)
+                                               { 
+                                                       _vp.toggleSelection(selectedIndex);
+                                               }
+                                       }
+                               _selectedBase = null;
+                       }
+                       else if (_currentState == MouseStates.SELECT_REGION)
+                       {
+                         _vp.removeSelectionRectangle();
+                       }
+                       else if (_currentState == MouseStates.CREATE_BP)
+                       {
+                               if (_initialPoint.distance(arg0.getX(),arg0.getY())>HYSTERESIS_DISTANCE)
+                               {
+                                       int selectedIndex = _vp.getNearestBaseIndex(arg0.getX(),arg0.getY(),false,false);
+                                       if (selectedIndex>=0)
+                                       {
+                                               ModeleBase mb = _vp.getNearestBase(arg0.getX(),arg0.getY(),false,false);
+                                               ModeleBase mborig = _selectedBase;
+                                               ModeleBP msbp = new ModeleBP(mb,mborig); 
+                                               if (mb!=mborig)
+                                               {
+                                                 _vp.getVARNAUI().UIAddBP(mb.getIndex(),mborig.getIndex(),msbp);
+                                               }
+                                       }
+                               }
+                               _vp.removeLink();
+                               _vp.clearSelection();
+                               _vp.repaint();
+                       }
+                       else
+                       {
+                               _vp.clearSelection();
+                       }
+
+               }
+               _currentState = MouseStates.NONE;
+               _vp.repaint();          
+       }
+
+
+       private void addMenu(MouseEvent arg0) {
+               // creation du menu
+               _submenuSelection = new JMenu("Selection");
+               addCurrent();
+               // ajout des option sur base
+               addMenuBase();
+               // ajout des option sur paire de base
+               if (_vp.getRNA().get_listeBases().get(_vp.getNearestBase())
+                               .getElementStructure() != -1) {
+                       addMenuBasePair();
+               }
+
+               // detection renflement
+               detectBulge();
+               // detection 3'
+               detect3Prime();
+               // detection 5'
+               detect5Prime();
+               // detection boucle
+               detectLoop();
+               // detection d'helice
+               detectHelix();
+               // detection tige
+               detectStem();
+               // Ajout de toutes bases
+               addAllBase();
+               // detection d'annotation
+               detectAnnotation(arg0);
+
+               _vp.getPopup().addSelectionMenu(_submenuSelection);
+               _presenceMenuSelection = true;
+       }
+
+       private void detectAnnotation(MouseEvent arg0) {
+               if (_vp.getListeAnnotations().size() != 0) {
+                       double dist = Double.MAX_VALUE;
+                       double d2;
+                       Point2D.Double position;
+                       for (TextAnnotation textAnnot : _vp.getListeAnnotations()) {
+                               // calcul de la distance
+                               position = textAnnot.getCenterPosition();
+                               position = _vp.transformCoord(position);
+                               d2 = Math.sqrt(Math.pow((position.x - arg0.getX()), 2)
+                                               + Math.pow((position.y - arg0.getY()), 2));
+                               // si la valeur est inferieur au minimum actuel
+                               if (dist > d2) {
+                                       _vp.set_selectedAnnotation(textAnnot);
+                                       dist = d2;
+                               }
+                       }
+                       _submenuSelection.addSeparator();
+                       _vp.getPopup().addAnnotationMenu(_submenuSelection,true);
+               }
+       }
+
+       private void detectBulge() {
+               int indiceB = _vp.getNearestBase();
+               ArrayList<Integer> indices = _vp.getRNA().findBulge(indiceB);
+               if ((indices.size() > 0)
+                               && (_vp.getRNA().getHelixCountOnLoop(_vp.getNearestBase()) == 2)) {
+                       JMenu submenuBulge = new JMenu("Bulge");
+                       submenuBulge.addChangeListener(new ControleurSelectionHighlight(
+                                       new Vector<Integer>(indices), _vp, submenuBulge));
+                       submenuBulge.setActionCommand("bulge");
+                       if (!_vp.isModifiable())
+                               submenuBulge.setEnabled(false);
+                       _vp.getPopupMenu().addColorOptions(submenuBulge);
+                       _submenuSelection.add(submenuBulge);
+               }
+       }
+
+       private void detectHelix() {
+               int indiceH = _vp.getNearestBase();
+               ArrayList<Integer> indices = _vp.getRNA().findHelix(indiceH);
+               if (indices.size() != 0) {
+                       // ajout menu helice
+                       JMenu submenuHelix = new JMenu("Helix");
+                       submenuHelix.addChangeListener(new ControleurSelectionHighlight(
+                                       new Vector<Integer>(indices), _vp, submenuHelix));
+                       submenuHelix.setActionCommand("helix");
+                       if (!_vp.isModifiable())
+                               submenuHelix.setEnabled(false);
+                       _vp.getPopupMenu().addColorOptions(submenuHelix);
+                       submenuHelix.addSeparator();
+                       _vp.getPopupMenu().addAnnotationMenu(submenuHelix);
+                       _submenuSelection.add(submenuHelix);
+               }
+       }
+
+       private void detectStem() {
+               int indiceS = _vp.getNearestBase();
+               ArrayList<Integer> indices = _vp.getRNA().findStem(indiceS);
+               if (indices.size() > 0) {
+                       JMenu submenuStem = new JMenu("Stem");
+                       submenuStem.addChangeListener(new ControleurSelectionHighlight(
+                                       new Vector<Integer>(indices), _vp, submenuStem));
+                       submenuStem.setActionCommand("stem");
+                       if (!_vp.isModifiable())
+                               submenuStem.setEnabled(false);
+                       _vp.getPopupMenu().addColorOptions(submenuStem);
+                       _submenuSelection.add(submenuStem);
+               }
+       }
+
+       private void detect3Prime() {
+               // detection 3'
+               int indice3 = _vp.getNearestBase();
+               ArrayList<Integer> indices = _vp.getRNA().find3Prime(indice3);
+               if (indices.size() != 0) {
+                       JMenu submenu3Prime = new JMenu("3'");
+                       submenu3Prime.addChangeListener(new ControleurSelectionHighlight(
+                                       new Vector<Integer>(indices), _vp, submenu3Prime));
+                       submenu3Prime.setActionCommand("3'");
+                       if (!_vp.isModifiable())
+                               submenu3Prime.setEnabled(false);
+                       _vp.getPopupMenu().addColorOptions(submenu3Prime);
+                       _submenuSelection.add(submenu3Prime);
+               }
+       }
+
+       private void detect5Prime() {
+               int indice5 = _vp.getNearestBase();
+               ArrayList<Integer> indices = _vp.getRNA().find5Prime(indice5);
+               if (indices.size() != 0) {
+                       JMenu submenu5Prime = new JMenu("5'");
+                       submenu5Prime.addChangeListener(new ControleurSelectionHighlight(
+                                       new Vector<Integer>(indices), _vp, submenu5Prime));
+                       submenu5Prime.setActionCommand("5'");
+                       if (!_vp.isModifiable())
+                               submenu5Prime.setEnabled(false);
+                       _vp.getPopupMenu().addColorOptions(submenu5Prime);
+                       _submenuSelection.add(submenu5Prime);
+               }
+       }
+
+       private void detectLoop() {
+               int indexL = _vp.getNearestBase();
+               if (_vp.getRNA().get_listeBases().get(indexL).getElementStructure() == -1) {
+                       ArrayList<Integer> listLoop = _vp.getRNA().findLoop(indexL);
+                       JMenu submenuLoop = new JMenu("Loop");
+                       submenuLoop.addChangeListener(new ControleurSelectionHighlight(
+                                       listLoop, _vp, submenuLoop));
+                       submenuLoop.setActionCommand("loop1");
+                       if (!_vp.isModifiable())
+                               submenuLoop.setEnabled(false);
+                       _vp.getPopupMenu().addColorOptions(submenuLoop);
+                       submenuLoop.addSeparator();
+                       _vp.getPopupMenu().addAnnotationMenu(submenuLoop);
+                       _submenuSelection.add(submenuLoop);
+               } else {
+                       ArrayList<Integer> listLoop1 = _vp.getRNA().findLoopForward(indexL);
+                       if (listLoop1.size() > 0) {
+                               JMenu submenuLoop1 = new JMenu("Forward loop");
+                               submenuLoop1
+                                               .addChangeListener(new ControleurSelectionHighlight(
+                                                               listLoop1, _vp, submenuLoop1));
+                               submenuLoop1.setActionCommand("loop1");
+                               if (!_vp.isModifiable())
+                                       submenuLoop1.setEnabled(false);
+                               _vp.getPopupMenu().addColorOptions(submenuLoop1);
+                               submenuLoop1.addSeparator();
+                               _vp.getPopupMenu().addAnnotationMenu(submenuLoop1);
+                               _submenuSelection.add(submenuLoop1);
+                       }
+                       ArrayList<Integer> listLoop2 = _vp.getRNA()
+                                       .findLoopBackward(indexL);
+                       if (listLoop2.size() > 0) {
+                               JMenu submenuLoop2 = new JMenu("Backward loop");
+                               submenuLoop2
+                                               .addChangeListener(new ControleurSelectionHighlight(
+                                                               listLoop2, _vp, submenuLoop2));
+                               submenuLoop2.setActionCommand("loop2");
+                               if (!_vp.isModifiable())
+                                       submenuLoop2.setEnabled(false);
+                               _vp.getPopupMenu().addColorOptions(submenuLoop2);
+                               submenuLoop2.addSeparator();
+                               _vp.getPopupMenu().addAnnotationMenu(submenuLoop2);
+                               _submenuSelection.add(submenuLoop2);
+                       }
+               }
+       }
+
+       private void addCurrent() {
+               Collection<? extends ModeleBase> mbs = _vp.getSelection().getBases();
+               if (mbs.size()>0)
+               {
+               JMenu submenuAll = new JMenu("Current");
+               submenuAll.addChangeListener(new ControleurSelectionHighlight(
+                               mbs, _vp, submenuAll));
+               submenuAll.setActionCommand("current");
+               if (!_vp.isModifiable())
+                       submenuAll.setEnabled(false);
+               _vp.getPopupMenu().addColorOptions(submenuAll);
+               _submenuSelection.add(submenuAll);
+               }
+       }
+       
+       
+       private void addMenuBase() {
+               JMenu submenuBase = new JMenu();
+               ModeleBase mb = _vp.getRNA().get_listeBases().get(_vp.getNearestBase());
+               if (mb instanceof ModeleBasesComparison) {
+                       submenuBase.setText("Base #" + (mb.getBaseNumber()) + ":"
+                                       + ((ModeleBasesComparison) mb).getBases());
+               } else {
+                       submenuBase.setText("Base #" + (mb.getBaseNumber()) + ":"
+                                       + ((ModeleBaseNucleotide) mb).getBase());
+               }
+               submenuBase.addChangeListener(new ControleurSelectionHighlight(mb
+                               .getIndex(), _vp, submenuBase));
+               submenuBase.setActionCommand("base");
+               // option disponible seulement en mode modifiable
+               if (!_vp.isModifiable())
+                       submenuBase.setEnabled(false);
+
+               JMenuItem baseChar = new JMenuItem("Edit base");
+               baseChar.setActionCommand("baseChar");
+               baseChar.addActionListener(_vp.getPopupMenu().get_controleurMenu());
+               submenuBase.add(baseChar);
+               _vp.getPopupMenu().addColorOptions(submenuBase);
+               submenuBase.addSeparator();
+               _vp.getPopupMenu().addAnnotationMenu(submenuBase);
+               _submenuSelection.add(submenuBase);
+       }
+
+       private void addAllBase() {
+               ArrayList<Integer> indices = _vp.getRNA().findAll();
+               JMenu submenuAll = new JMenu("All");
+               submenuAll.addChangeListener(new ControleurSelectionHighlight(
+                               new Vector<Integer>(indices), _vp, submenuAll));
+               submenuAll.setActionCommand("all");
+               if (!_vp.isModifiable())
+                       submenuAll.setEnabled(false);
+               _vp.getPopupMenu().addColorOptions(submenuAll);
+               _submenuSelection.add(submenuAll);
+       }
+
+       private void addMenuBasePair() {
+                       int indiceBP = _vp.getNearestBase();
+                       ArrayList<Integer> indices = _vp.getRNA().findPair(indiceBP);
+                       ModeleBase base = _vp.getRNA()
+                                       .get_listeBases().get(_vp.getNearestBase());
+                       if (base.getElementStructure() != -1) {
+                               JMenu submenuBasePair = new JMenu();
+                               ModeleBase partner = _vp
+                                               .getRNA().get_listeBases().get(
+                                                               base.getElementStructure());
+                               submenuBasePair
+                                               .addChangeListener(new ControleurSelectionHighlight(
+                                                               indices, _vp, submenuBasePair));
+                               submenuBasePair.setText("Base pair #("
+                                               + (Math.min(base.getBaseNumber(), partner
+                                                               .getBaseNumber()))
+                                               + ","
+                                               + (Math.max(base.getBaseNumber(), partner
+                                                               .getBaseNumber())) + ")");
+                               submenuBasePair.setActionCommand("bp");
+                               // option disponible seulement en mode modifiable
+                               if (!_vp.isModifiable())
+                                       submenuBasePair.setEnabled(false);
+
+                               JMenuItem basepair = new JMenuItem("Edit BP");
+                               basepair.setActionCommand("basepair");
+                               basepair.addActionListener(_vp.getPopupMenu()
+                                               .get_controleurMenu());
+
+                               _vp.getPopupMenu().addColorOptions(submenuBasePair);
+                               Component[] comps = submenuBasePair.getMenuComponents();
+                               int offset = -1;
+                               for (int i = 0; i < comps.length; i++) {
+                                       Component c = comps[i];
+                                       if (c instanceof JMenuItem) {
+                                               JMenuItem jmi = (JMenuItem) c;
+                                               if (jmi.getActionCommand().contains(",BPColor")) {
+                                                       offset = i;
+                                               }
+                                       }
+                               }
+                               if (offset != -1) {
+                                       submenuBasePair.insert(basepair, offset);
+                               } else {
+                                       submenuBasePair.add(basepair);
+                               }
+                               _submenuSelection.add(submenuBasePair);
+                       }
+               }
+
+       private void updateNearestBase(MouseEvent arg0) {
+               int i = _vp.getNearestBaseIndex(arg0.getX(),arg0.getY(),true,false);
+               if (i!=-1)
+                       _vp.setNearestBase(i);
+       }
+
+
+
+       
+       public void mouseMoved(MouseEvent arg0) {
+               _selectedBase = _vp.getNearestBase(arg0.getX(),arg0.getY());
+               TextAnnotation selectedAnnotation = _vp.getNearestAnnotation(arg0.getX(),arg0.getY());
+               _vp.setHoverBase(_selectedBase);
+               if (_selectedBase != null)
+               {
+               }
+               else if (selectedAnnotation!=null)
+               {
+                       _vp.set_selectedAnnotation(selectedAnnotation);
+                       _vp.highlightSelectedAnnotation();
+                       _vp.repaint();
+               }
+               _vp.setLastSelectedPosition(new Point2D.Double(arg0.getX(),arg0.getY()));
+       }
+
+       
+       
+       private void moveSelection(Point prev, Point cur) 
+       {
+               Point2D.Double p1 =  _vp.panelToLogicPoint(new Point2D.Double(prev.x,prev.y));
+               Point2D.Double p2 =  _vp.panelToLogicPoint(new Point2D.Double(cur.x,cur.y));
+               double dx = (p2.x - p1.x);
+               double dy = (p2.y - p1.y);
+               
+               if (_vp.isModifiable())
+               {  
+                       double ndx = dx;
+                       double ndy = dy;
+                       if (_vp.getRNA().get_drawMode() == RNA.DRAW_MODE_LINEAR) 
+                       {
+                               ndy=0.0;
+                       }
+                       _vp.getVARNAUI().UIShiftBaseCoord(_vp.getSelectionIndices(), ndx, ndy);
+                       _vp.fireLayoutChanged();
+                       
+               }
+       }
+
+
+       public void popupMenuCanceled(PopupMenuEvent arg0) {
+       }
+
+       public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
+               _vp.resetAnnotationHighlight();
+               _selectedBase = null;
+       }
+
+       public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurDemoTextField.java b/src2/fr/orsay/lri/varna/controlers/ControleurDemoTextField.java
new file mode 100644 (file)
index 0000000..fd87fc6
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.Stack;
+
+import javax.swing.event.CaretEvent;
+import javax.swing.event.CaretListener;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.DefaultHighlighter;
+import javax.swing.text.Highlighter;
+
+import fr.orsay.lri.varna.applications.VARNAOnlineDemo;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+
+/**
+ * It controls the sequence and structure text fields and changes their color if
+ * they have different lengths or unbalanced parentheses.
+ * 
+ * @author darty
+ * 
+ */
+public class ControleurDemoTextField implements CaretListener {
+       private VARNAOnlineDemo _vod;
+       private String _oldSeq, _oldStruct;
+       private Highlighter _hilit;
+       private Highlighter.HighlightPainter _painter;
+       private final Color COLORERROR = Color.RED;
+       private final Color COLORWARNING = Color.ORANGE;
+
+       public ControleurDemoTextField(VARNAOnlineDemo VOD) {
+               _vod = VOD;
+               _oldSeq = _vod.get_seq().getText();
+               _oldStruct = _vod.get_struct().getText();
+               _hilit = new DefaultHighlighter();
+               _painter = new DefaultHighlighter.DefaultHighlightPainter(Color.BLACK);
+               _vod.get_struct().setHighlighter(_hilit);
+       }
+
+       // if there is any change
+       public void caretUpdate(CaretEvent e) {
+               if (_oldStruct != _vod.get_struct().getText()
+                               || _oldSeq != _vod.get_seq().getText()) {
+                       ArrayList<String> infos = new ArrayList<String>();
+                       _vod.get_info().removeAll();
+                       _hilit.removeAllHighlights();
+                       _oldStruct = _vod.get_struct().getText();
+                       _oldSeq = _vod.get_seq().getText();
+                       int nbPO = 0, nbPF = 0;
+                       // compte les parentheses ouvrantes et fermantes
+                       Stack<Integer> p = new Stack<Integer>();
+                       boolean pb = false;
+                       for (int i = 0; i < _vod.get_struct().getText().length(); i++) {
+                               if (_vod.get_struct().getText().charAt(i) == '(') {
+                                       nbPO++;
+                                       p.push(i);
+                               } else if (_vod.get_struct().getText().charAt(i) == ')') {
+                                       nbPF++;
+                                       if (p.size() == 0) {
+                                               try {
+                                                       _hilit.addHighlight(i, i + 1, _painter);
+                                               } catch (BadLocationException e1) {
+                                                       _vod.get_varnaPanel().errorDialog(e1);
+                                               }
+                                               pb = true;
+                                       } else
+                                               p.pop();
+                               }
+                       }
+
+                       // si le nombre de parentheses ouvrantes/fermantes est different
+                       if (pb || p.size() > 0) {
+                               // colorie en rouge
+                               if (pb) {
+                                       infos.add("too many closing parentheses");
+                               }
+                               if (p.size() > 0) {
+                                       int indice;
+                                       while (!p.isEmpty()) {
+                                               indice = p.pop();
+                                               try {
+                                                       _hilit.addHighlight(indice, indice + 1, _painter);
+                                               } catch (BadLocationException e1) {
+                                                       _vod.get_varnaPanel().errorDialog(e1);
+                                               }
+                                       }
+                                       infos.add("too many opening parentheses");
+                               }
+                               _vod.get_info().setForeground(COLORERROR);
+                               _vod.get_seq().setForeground(COLORERROR);
+                               _vod.get_struct().setForeground(COLORERROR);
+                       } else {
+                               try {
+                                       // redraw the new RNA
+                                       _vod.get_varnaPanel().drawRNA(_vod.get_seq().getText(),
+                                                       _vod.get_struct().getText(),
+                                                       _vod.get_varnaPanel().getRNA().get_drawMode());
+                               } catch (ExceptionNonEqualLength e1) {
+                                       _vod.get_varnaPanel().errorDialog(e1);
+                               }
+                               // verifie la longueur de la structure et de la sequence
+                               if (_vod.get_seq().getText().length() != _vod.get_struct()
+                                               .getText().length()) {
+                                       // colorie en orange
+                                       infos.add("different lenghts");
+                                       _vod.get_seq().setForeground(COLORWARNING);
+                                       _vod.get_struct().setForeground(COLORWARNING);
+                               } else {
+                                       // sinon colorie en noir
+                                       _vod.get_seq().setForeground(Color.black);
+                                       _vod.get_struct().setForeground(Color.black);
+                               }
+                       }
+                       _vod.get_varnaPanel().getVARNAUI().UIReset();
+                       String info = new String();
+                       if (infos.size() != 0) {
+                               info += infos.get(0);
+                               for (int i = 1; i < infos.size(); i++) {
+                                       info += ", " + infos.get(i);
+                               }
+                               info += ".";
+                       }
+                       _vod.get_info().setText(info);
+               }
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurDraggedMolette.java b/src2/fr/orsay/lri/varna/controlers/ControleurDraggedMolette.java
new file mode 100644 (file)
index 0000000..8668faa
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Point;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+
+/**
+ * Controller of the mouse for scroll wheel click and dragged events
+ * 
+ * @author darty
+ * 
+ */
+public class ControleurDraggedMolette implements MouseListener,
+               MouseMotionListener {
+       private VARNAPanel _vp;
+       /**
+        * <code>true</code> if the right button is pressed<br>
+        * <code>false</code> if not
+        */
+       private static Boolean _rightButtonClick;
+       /**
+        * The vector which contains the direction of the mouse movement
+        */
+       private static Point _direction;
+       /**
+        * The position of the cursor before the mouse drag
+        */
+       private static Point _avant;
+       /**
+        * The position of the cursor after the mouse drag
+        */
+       private static Point _apres;
+
+       public ControleurDraggedMolette(VARNAPanel vp) {
+               _vp = vp;
+               _rightButtonClick = false;
+               _avant = _apres = _direction = new Point();
+       }
+
+       public void mouseDragged(MouseEvent e) {
+               // si le bon boutton a Ã©té pressé
+               if (_rightButtonClick) {
+                       _apres = e.getPoint();
+                       _direction = new Point(_apres.x - _avant.x, _apres.y - _avant.y);
+                       _vp.setTranslation(new Point(_vp.getTranslation().x + _direction.x,
+                                       _vp.getTranslation().y + _direction.y));
+                       _avant = _apres;
+                       _vp.checkTranslation();
+                       _vp.repaint();
+               }
+       }
+
+       public void mouseMoved(MouseEvent e) {
+       }
+
+       public void mouseClicked(MouseEvent e) {
+       }
+
+       public void mouseEntered(MouseEvent e) {
+       }
+
+       public void mouseExited(MouseEvent e) {
+       }
+
+       public void mousePressed(MouseEvent e) {
+               // lors du clic, la position du curseur est enregistrée
+               _avant = e.getPoint();
+               // si le boutton molette est pressé ou si le boutton gauche et shift
+               // sont pressés
+               if (e.getButton() == MouseEvent.BUTTON2)
+               {
+                       _rightButtonClick = true;
+               }
+               else
+               {
+                       _rightButtonClick = false;
+               }
+                       
+                       
+       }
+
+       public void mouseReleased(MouseEvent e) {
+               // si le boutton molette est relaché ou si le boutton gauche et shift
+               // sont relachés
+               if (e.getButton() == MouseEvent.BUTTON2)
+                       _rightButtonClick = false;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurGlobalRescale.java b/src2/fr/orsay/lri/varna/controlers/ControleurGlobalRescale.java
new file mode 100644 (file)
index 0000000..7e464b6
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.VARNAEdits;
+import fr.orsay.lri.varna.views.VueGlobalRescale;
+import fr.orsay.lri.varna.views.VueGlobalRotation;
+
+
+public class ControleurGlobalRescale implements ChangeListener {
+
+       private VueGlobalRescale _vGR;
+       private double _oldScale;
+       private VARNAPanel _vp;
+
+       public ControleurGlobalRescale(VueGlobalRescale vGR, VARNAPanel vp) {
+               _vGR = vGR;
+               _oldScale = 1.0;
+               _vp = vp;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               _vp.getVARNAUI().UIGlobalRescale(_vGR.getScale()/_oldScale);
+               _oldScale = _vGR.getScale();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurGlobalRotation.java b/src2/fr/orsay/lri/varna/controlers/ControleurGlobalRotation.java
new file mode 100644 (file)
index 0000000..e3dc8a8
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.VARNAEdits;
+import fr.orsay.lri.varna.views.VueGlobalRotation;
+
+
+public class ControleurGlobalRotation implements ChangeListener {
+
+       private VueGlobalRotation _vGR;
+       private double _oldAngle;
+       private VARNAPanel _vp;
+
+       public ControleurGlobalRotation(VueGlobalRotation vGR, VARNAPanel vp) {
+               _vGR = vGR;
+               _oldAngle = 0;
+               _vp = vp;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               _vp.getVARNAUI().UIGlobalRotation(_vGR.getAngle() - _oldAngle);
+               _oldAngle = _vGR.getAngle();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurInterpolator.java b/src2/fr/orsay/lri/varna/controlers/ControleurInterpolator.java
new file mode 100644 (file)
index 0000000..827f762
--- /dev/null
@@ -0,0 +1,660 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.Vector;
+
+import javax.swing.Timer;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.exceptions.MappingException;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class ControleurInterpolator extends Thread implements ActionListener {
+
+       private static final int START = 0;
+       private static final int LOOP = 1;
+       private static final int END = 2;
+
+       VARNAPanel _vpn;
+       protected int _numSteps = 25;  // BH SwingJS
+       private long _timeDelay = /** @j2sNative 2 || */15;
+       private boolean _running = false;
+       Targets _d = new Targets();
+       protected int _step;   // BH SwingJS
+       protected boolean _firstHalf;  // BH SwingJS
+
+       public ControleurInterpolator(VARNAPanel vpn) {
+               _vpn = vpn;
+       }
+
+       public synchronized void addTarget(RNA target, Mapping mapping) {
+               addTarget(target, null, mapping);
+       }
+
+       
+       public synchronized void addTarget(RNA target, VARNAConfig conf, Mapping mapping) {
+               _d.add(new TargetsHolder(target,conf,mapping));
+       }
+
+       public synchronized void addTarget(RNA target) {
+               addTarget(target, null, Mapping.DefaultOutermostMapping(_vpn.getRNA()
+                               .get_listeBases().size(), target.get_listeBases().size()));
+       }
+       
+       public boolean isInterpolationInProgress()
+       {
+               return _running;
+       }
+
+       private Point2D.Double computeDestination(Point2D pli, Point2D pri,
+                       Point2D pi, int i, int n, Point2D plf, Point2D prf) {
+               Point2D.Double plm = new Point2D.Double(
+                               (pli.getX() + plf.getX()) / 2.0,
+                               (pli.getY() + plf.getY()) / 2.0);
+               Point2D.Double prm = new Point2D.Double(
+                               (pri.getX() + prf.getX()) / 2.0,
+                               (pri.getY() + prf.getY()) / 2.0);
+               Point2D.Double pm = new Point2D.Double(((n - i) * plm.getX() + i
+                               * prm.getX())
+                               / n, ((n - i) * plm.getY() + i * prm.getY()) / n);
+               Point2D.Double v = new Point2D.Double(pm.getX() - pi.getX(), pm.getY()
+                               - pi.getY());
+               Point2D.Double pf = new Point2D.Double(pi.getX() + 2.0 * v.getX(), pi
+                               .getY()
+                               + 2.0 * v.getY());
+               return pf;
+       }
+
+       private Vector<Vector<Integer>> clusterIndices(int numIndices,
+                       int[] mappedIndices) throws MappingException {
+               int[] indices = new int[numIndices];
+               for (int i = 0; i < numIndices; i++) {
+                       indices[i] = i;
+               }
+               return clusterIndices(indices, mappedIndices);
+       }
+
+       /**
+        * Builds and returns an interval array, alternating unmatched regions and
+        * matched indices. Namely, returns a vector of vector such that the vectors
+        * found at odd positions contain those indices that are NOT associated with
+        * any other base in the current mapping. On the other hand, vectors found
+        * at even positions contain only one mapped index. <br/>
+        * Ex: If indices=<code>[1,2,3,4,5]</code> and mappedIndices=
+        * <code>[2,5]</code> then the function will return
+        * <code>[[1],[2],[3,4],[5],[]]</code>.
+        * 
+        * @param indices
+        *            The total list of indices
+        * @param mappedIndices
+        *            Matched indices, should be a subset of <code>indices</code>
+        * @return A clustered array
+        * @throws MappingException
+        *             If one of the parameters is an empty array
+        */
+       private Vector<Vector<Integer>> clusterIndices(int[] indices,
+                       int[] mappedIndices) throws MappingException {
+               if ((mappedIndices.length == 0) || (indices.length == 0)) {
+                       throw new MappingException(
+                                       "Mapping Error: Cannot cluster indices in an empty mapping");
+               }
+               Vector<Vector<Integer>> res = new Vector<Vector<Integer>>();
+
+               Arrays.sort(indices);
+               Arrays.sort(mappedIndices);
+               int i, j = 0, k;
+               Vector<Integer> tmp = new Vector<Integer>();
+               for (i = 0; (i < indices.length) && (j < mappedIndices.length); i++) {
+                       if (indices[i] == mappedIndices[j]) {
+                               res.add(tmp);
+                               tmp = new Vector<Integer>();
+                               tmp.add(indices[i]);
+                               res.add(tmp);
+                               tmp = new Vector<Integer>();
+                               j++;
+                       } else {
+                               tmp.add(indices[i]);
+                       }
+               }
+               k = i;
+               for (i = k; (i < indices.length); i++) {
+                       tmp.add(indices[i]);
+               }
+               res.add(tmp);
+               return res;
+       }
+       
+       
+
+       public void run() {
+               while (true)
+               {
+                       TargetsHolder d = _d.get();
+                       _running = true;
+                       try{
+                       nextTarget(d.target,d.conf,d.mapping);
+                       }
+                       catch(Exception e)
+                       {
+                               System.err.println(e);
+                               e.printStackTrace();
+                       }
+                       _running = false;
+                       /**
+                        * @j2sNative
+                        * 
+                        * break;
+                        */
+               }
+               
+       }
+       
+       /**
+        * Compute the centroid of the RNA bases that have their indexes
+        * in the given array.
+        */
+       private static Point2D.Double computeCentroid(ArrayList<ModeleBase> rnaBases, int[] indexes) {          
+               double centroidX = 0, centroidY = 0;
+               for (int i=0; i<indexes.length; i++) {
+                       int index = indexes[i];
+                       Point2D coords = rnaBases.get(index).getCoords();
+                       centroidX += coords.getX();
+                       centroidY += coords.getY();
+               }
+               centroidX /= indexes.length;
+               centroidY /= indexes.length;
+               
+               return new Point2D.Double(centroidX, centroidY);
+       }
+       
+       /**
+        * The purpose of this class is to compute the rotation that minimizes the
+        * RMSD between the bases of the first RNA and the bases of the second RNA.
+        * 
+        * @author Raphael Champeimont
+        */
+       private static class MinimizeRMSD {
+               private double[] X1, X2, Y1, Y2;
+               
+               public MinimizeRMSD(double[] X1, double[] Y1, double[] X2, double[] Y2) {
+                       this.X1 = X1;
+                       this.X2 = X2;
+                       this.Y1 = Y1;
+                       this.Y2 = Y2;
+               }
+               
+               /**
+                * A function such that minimizing it is equivalent to
+                * minimize the RMSD between between the two arrays of vectors,
+                * supposing we rotate the points in [X2,Y2] by theta.
+                */
+               private double f(double theta) {
+                   double cos_theta = Math.cos(theta);
+                   double sin_theta = Math.sin(theta);
+                   int n = X1.length;
+                   double sum = 0;
+                   for (int i=0; i<n; i++) {
+                       double dsx = X2[i]*cos_theta - Y2[i]*sin_theta - X1[i];
+                       double dsy = X2[i]*sin_theta + Y2[i]*cos_theta - Y1[i];
+                       sum = sum + dsx*dsx + dsy*dsy;
+                   }
+                   return sum;
+               }
+               
+               /**
+                * d/dtheta f(theta)
+                */
+               private double fprime(double theta) {
+                   double cos_theta = Math.cos(theta);
+                   double sin_theta = Math.sin(theta);
+                   int n = X1.length;
+                   double sum = 0;
+                   for (int i=0; i<n; i++) {
+                       sum = sum
+                           + (X1[i]*X2[i] + Y1[i]*Y2[i]) * sin_theta
+                           + (X1[i]*Y2[i] - X2[i]*Y1[i]) * cos_theta;
+                   }
+                   return sum;
+               }
+               
+               /**
+                * d^2/dtheta^2 f(theta)
+                */
+               private double fsecond(double theta) {
+                   double cos_theta = Math.cos(theta);
+                   double sin_theta = Math.sin(theta);
+                   int n = X1.length;
+                   double sum = 0;
+                   for (int i=0; i<n; i++) {
+                       sum = sum
+                           + (X1[i]*X2[i] + Y1[i]*Y2[i]) * cos_theta
+                           + (X2[i]*Y1[i] - X1[i]*Y2[i]) * sin_theta;
+                   }
+                   return sum;
+               }
+
+
+               /**
+                * Find the theta that minimizes f(theta).
+                * We use Newton's method.
+                */
+               public  double computeOptimalTheta() {
+                       final double epsilon = 1E-5;
+                       double x_n = 0;
+                       int numsteps = 0;
+                       // In practice the number of steps to reach precision 1E-5 is smaller that
+                       // 10 most of the time.
+                       final int maxnumsteps = 100;
+                       double x_n_plus_1;
+                       double result;
+                       while (true) {
+                           numsteps = numsteps + 1;
+                           double d = fsecond(x_n);
+                           if (d == 0) {
+                               // if f''(x_n) is 0 we cannot divide by it,
+                               // so we move a little.
+                               x_n_plus_1 = x_n + epsilon * (Math.random() - 0.5);
+                           } else {
+                               x_n_plus_1 = x_n - fprime(x_n)/fsecond(x_n);
+                               if (Math.abs(x_n_plus_1 - x_n) < epsilon) {
+                                    result = x_n_plus_1;
+                                    break;
+                               }
+                           }
+                           if (numsteps >= maxnumsteps) {
+                               // If things go bad (for example f''(x) keeps being 0)
+                               // we need to give up after what we consider to be too many steps.
+                               // In practice this can happen only in pathological cases
+                               // like f being constant, which is very unlikely.
+                               result = x_n_plus_1;
+                               break;
+                               }
+                           x_n = x_n_plus_1;
+                       }
+
+                       // We now have either found the min or the max at x = result.
+                       // If we have the max at x we know the min is at x+pi.
+                       if (f(result + Math.PI) < f(result)) {
+                           result = result + Math.PI;
+                       }
+                       
+                       return result;
+               }
+
+
+       }
+       
+       
+       /**
+        * We suppose we have two lists of points. The coordinates of the first
+        * list of points are X1 and Y1, and X2 and Y2 for the second list.
+        * We suppose that the centroids of [X1,Y1] and [X2,Y2] are both (0,0).
+        * This function computes the rotation to apply to the second set of
+        * points such that the RMSD (Root mean square deviation) between them
+        * is minimum. The returned angle is in radians.
+        */
+       private static double minimizeRotateRMSD(double[] X1, double[] Y1, double[] X2, double[] Y2) {
+               MinimizeRMSD minimizer = new MinimizeRMSD(X1, Y1, X2, Y2);
+               return minimizer.computeOptimalTheta();
+       }
+       
+       
+       /**
+        * Move rna2 using a rotation so that it would move as little as possible
+        * (in the sense that we minimize the RMSD) when transforming
+        * it to rna1 using the given mapping.
+        */
+       public static void moveNearOtherRNA(RNA rna1, RNA rna2, Mapping mapping) {
+               int[] rna1MappedElems = mapping.getSourceElems();
+               int[] rna2MappedElems = mapping.getTargetElems();
+               ArrayList<ModeleBase> rna1Bases = rna1.get_listeBases();
+               ArrayList<ModeleBase> rna2Bases = rna2.get_listeBases();
+               int n = rna1MappedElems.length;
+               
+               // If there is less than 2 points, it is useless to rotate the RNA.
+               if (n < 2) return;
+               
+               // We can now assume that n >= 2.
+               
+               // Compute the centroids of both RNAs
+               Point2D.Double rna1MappedElemsCentroid = computeCentroid(rna1Bases, rna1MappedElems);
+               Point2D.Double rna2MappedElemsCentroid = computeCentroid(rna2Bases, rna2MappedElems);
+
+               // Compute the optimal rotation
+               // We first compute coordinates for both RNAs, changing the origins
+               // to be the centroids.
+               double[] X1 = new double[rna1MappedElems.length];
+               double[] Y1 = new double[rna1MappedElems.length];
+               double[] X2 = new double[rna2MappedElems.length];
+               double[] Y2 = new double[rna2MappedElems.length];
+               for (int i=0; i<rna1MappedElems.length; i++) {
+                       int base1Index = rna1MappedElems[i];
+                       Point2D.Double coords1 = rna1Bases.get(base1Index).getCoords();
+                       X1[i] = coords1.x - rna1MappedElemsCentroid.x;
+                       Y1[i] = coords1.y - rna1MappedElemsCentroid.y;
+                       Point2D.Double coords2 = rna2Bases.get(mapping.getPartner(base1Index)).getCoords();
+                       X2[i] = coords2.x - rna2MappedElemsCentroid.x;
+                       Y2[i] = coords2.y - rna2MappedElemsCentroid.y;
+               }
+               
+               // Compute the optimal rotation angle theta
+               double theta = minimizeRotateRMSD(X1, Y1, X2, Y2);
+               
+               // Rotate RNA2
+               rna2.globalRotation(theta * 180.0 / Math.PI);
+       }
+
+       public void nextTarget(RNA _target, VARNAConfig _conf, Mapping _mapping) {
+               nextTarget(_target, _conf, _mapping, false);
+       }
+       
+       Runnable _loop, _end;
+       
+       /**
+        * The argument moveTarget specifies whether the RNA _target should
+        * be rotated so that bases move as little as possible when switching
+        * from the current RNA to _target using the animation.
+        * Note that this will modify the _target object directly.
+        */
+       public void nextTarget(final RNA _target, final VARNAConfig _conf, Mapping _mapping, boolean moveTarget)
+       {
+               _end = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               _vpn.showRNA(_target);
+                               _vpn.repaint();
+                       }
+                       
+               };
+               
+               try {
+                       final RNA source = _vpn.getRNA();
+                       
+                       if (moveTarget) moveNearOtherRNA(source, _target, _mapping);
+
+                       if (source.getSize()!=0&&_target.getSize()!=0)
+                       {
+                       ArrayList<ModeleBase> currBases = source.get_listeBases();
+                       ArrayList<ModeleBase> destBases = _target.get_listeBases();
+                       Vector<Vector<Integer>> intArrSource = new Vector<Vector<Integer>>();
+                       Vector<Vector<Integer>> intArrTarget = new Vector<Vector<Integer>>();
+                               // Building interval arrays
+                               intArrSource = clusterIndices(currBases.size(), _mapping
+                                               .getSourceElems());
+                               intArrTarget = clusterIndices(destBases.size(), _mapping
+                                               .getTargetElems());
+
+                       // Duplicating source and target coordinates
+                       final Point2D.Double[] initPosSource = new Point2D.Double[currBases
+                                       .size()];
+                       final Point2D.Double[] finalPosTarget = new Point2D.Double[destBases
+                                       .size()];
+
+                       for (int i = 0; i < currBases.size(); i++) {
+                               Point2D tmp = currBases.get(i).getCoords();
+                               initPosSource[i] = new Point2D.Double(tmp.getX(), tmp.getY());
+                       }
+                       for (int i = 0; i < destBases.size(); i++) {
+                               Point2D tmp = destBases.get(i).getCoords();
+                               finalPosTarget[i] = new Point2D.Double(tmp.getX(), tmp.getY());
+                       }
+
+                       /**
+                        * Assigning final (Source) and initial (Target) coordinates
+                        */
+                       final Point2D.Double[] finalPosSource = new Point2D.Double[initPosSource.length];
+                       final Point2D.Double[] initPosTarget = new Point2D.Double[finalPosTarget.length];
+                       // Final position of source model
+                       for (int i = 0; i < finalPosSource.length; i++) {
+                               if (_mapping.getPartner(i) != Mapping.UNKNOWN) {
+                                       Point2D dest;
+                                       dest = finalPosTarget[_mapping.getPartner(i)];
+                                       finalPosSource[i] = new Point2D.Double(dest.getX(), dest
+                                                       .getY());
+                               }
+                       }
+
+                       for (int i = 0; i < intArrSource.size(); i += 2) {
+                               int matchedNeighborLeft, matchedNeighborRight;
+                               if (i == 0) {
+                                       matchedNeighborLeft = intArrSource.get(1).get(0);
+                                       matchedNeighborRight = intArrSource.get(1).get(0);
+                               } else if (i == intArrSource.size() - 1) {
+                                       matchedNeighborLeft = intArrSource.get(
+                                                       intArrSource.size() - 2).get(0);
+                                       matchedNeighborRight = intArrSource.get(
+                                                       intArrSource.size() - 2).get(0);
+                               } else {
+                                       matchedNeighborLeft = intArrSource.get(i - 1).get(0);
+                                       matchedNeighborRight = intArrSource.get(i + 1).get(0);
+                               }
+                               Vector<Integer> v = intArrSource.get(i);
+                               for (int j = 0; j < v.size(); j++) {
+                                       int index = v.get(j);
+                                       finalPosSource[index] = computeDestination(
+                                                       initPosSource[matchedNeighborLeft],
+                                                       initPosSource[matchedNeighborRight],
+                                                       initPosSource[index], j + 1, v.size() + 1,
+                                                       finalPosSource[matchedNeighborLeft],
+                                                       finalPosSource[matchedNeighborRight]);
+                               }
+                       }
+                       for (int i = 0; i < initPosTarget.length; i++) {
+                               if (_mapping.getAncestor(i) != Mapping.UNKNOWN) {
+                                       Point2D dest;
+                                       dest = initPosSource[_mapping.getAncestor(i)];
+                                       initPosTarget[i] = new Point2D.Double(dest.getX(), dest.getY());
+                               }
+                       }
+                       for (int i = 0; i < intArrTarget.size(); i += 2) {
+                               int matchedNeighborLeft, matchedNeighborRight;
+                               if (i == 0) {
+                                       matchedNeighborLeft = intArrTarget.get(1).get(0);
+                                       matchedNeighborRight = intArrTarget.get(1).get(0);
+                               } else if (i == intArrTarget.size() - 1) {
+                                       matchedNeighborLeft = intArrTarget.get(
+                                                       intArrTarget.size() - 2).get(0);
+                                       matchedNeighborRight = intArrTarget.get(
+                                                       intArrTarget.size() - 2).get(0);
+                               } else {
+                                       matchedNeighborLeft = intArrTarget.get(i - 1).get(0);
+                                       matchedNeighborRight = intArrTarget.get(i + 1).get(0);
+                               }
+                               Vector<Integer> v = intArrTarget.get(i);
+                               for (int j = 0; j < v.size(); j++) {
+                                       int index = v.get(j);
+                                       initPosTarget[index] = computeDestination(
+                                                       finalPosTarget[matchedNeighborLeft],
+                                                       finalPosTarget[matchedNeighborRight],
+                                                       finalPosTarget[index], j + 1, v.size() + 1,
+                                                       initPosTarget[matchedNeighborLeft],
+                                                       initPosTarget[matchedNeighborRight]);
+                               }
+                       }
+
+                       mode = START;
+                       _loop = new Runnable(){
+
+                               @Override
+                               public void run() {
+                                       int i = _step;
+                                       RNA current = (_firstHalf ? source : _target);
+                                       if (i == _numSteps / 2) {
+                                               _vpn.showRNA(_target);
+                                               current = _target;
+                                               _firstHalf = false;
+                                               if (_conf!=null)
+                                               {_vpn.setConfig(_conf);}
+                                               
+                                               for (int j = 0; j < initPosSource.length; j++) {
+                                                       source.setCoord(j, initPosSource[j]);
+                                               }
+                                       }
+                                       ArrayList<ModeleBase> currBases = current.get_listeBases();
+                                       for (int j = 0; j < currBases.size(); j++) {
+                                               ModeleBase m = currBases.get(j);
+                                               Point2D mpc, mnc;
+                                               if (_firstHalf) {
+                                                       mpc = initPosSource[j];
+                                                       mnc = finalPosSource[j];
+                                               } else {
+                                                       mpc = initPosTarget[j];
+                                                       mnc = finalPosTarget[j];
+                                               }
+                                               m.setCoords(new Point2D.Double(((_numSteps - 1 - i)
+                                                               * mpc.getX() + (i) * mnc.getX())
+                                                               / (_numSteps - 1), ((_numSteps - 1 - i)
+                                                               * mpc.getY() + i * mnc.getY())
+                                                               / (_numSteps - 1)));
+                                       }
+                                       _vpn.repaint();
+                               }
+                               
+                       };
+                       actionPerformed(null);
+                       } else {
+                               _end.run();
+                       }
+               } catch (MappingException e) {
+                       e.printStackTrace();
+                       _end.run();
+               }catch (Exception e) {
+                       e.printStackTrace();
+                       _end.run();
+               }
+               
+
+       }
+
+       private class TargetsHolder
+       {
+               public RNA target;
+               public VARNAConfig conf;
+               public Mapping mapping;
+               public TargetsHolder(RNA t, VARNAConfig c, Mapping m)
+               {
+                       target = t;
+                       conf = c;
+                       mapping = m;
+               }
+       }
+       
+       private class Targets
+       {
+               LinkedList<TargetsHolder> _d = new LinkedList<TargetsHolder>();
+               public Targets() {
+                       // BH j2s SwingJS added only to remove Eclipse warning
+               }
+               public synchronized void add(TargetsHolder d)
+               {
+                       _d.addLast(d);
+                       
+                       @SuppressWarnings("unused")
+                       Runnable interpolator = ControleurInterpolator.this;
+                       /**
+                        * BH SwingJS no notify()
+                        * @j2sNative 
+                        * 
+                        * interpolator.run();
+                        * 
+                        */
+                       {
+                       notify();
+                       }
+               }
+
+               public synchronized TargetsHolder get() {
+
+                       /**
+                        * BH SwingJS no wait()
+                        * 
+                        * @j2sNative
+                        * 
+                        * 
+                        */
+                       {
+                               while (_d.size() == 0) {
+                                       try {
+                                               wait();
+                                       } catch (InterruptedException e) {
+                                               e.printStackTrace();
+                                       }
+                               }
+                       }
+                       TargetsHolder x = _d.getLast();
+                       _d.clear();
+                       return x;
+               }
+       }
+
+
+       @Override
+       public void actionPerformed(ActionEvent e) {
+               runAnimation();
+       }
+
+       private int mode;
+
+       private void runAnimation() {
+               switch (mode) {
+               case START:
+                       _firstHalf = true;
+                       _step = 0;
+                       mode = LOOP;
+                       // Fall through
+               case LOOP:
+                       if (_step < _numSteps) {
+                               _loop.run();
+                               ++_step;
+                               break;
+                       }
+                       mode = END;
+                       // Fall through
+               case END:
+                       _end.run();
+                       return;
+               }
+               Timer t = new Timer((int) _timeDelay, this);
+               t.setRepeats(false);
+               t.start();
+               // try {
+               // for (int i = 0; i < _numSteps; i++) {
+               // _step = i;
+               // loop.run();
+               //
+               // sleep(_timeDelay);
+               // }
+               // end.run();
+               // } catch (InterruptedException e) {
+               // e.printStackTrace();
+               // end.run();
+               // }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurJCheckBoxMenuItem.java b/src2/fr/orsay/lri/varna/controlers/ControleurJCheckBoxMenuItem.java
new file mode 100644 (file)
index 0000000..825c58c
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+
+/**
+ * Controller of check box menu items to repaint if item state changes
+ * 
+ * @author darty
+ * 
+ */
+public class ControleurJCheckBoxMenuItem implements ItemListener {
+
+       private VARNAPanel _vp;
+
+       public ControleurJCheckBoxMenuItem(VARNAPanel v) {
+               _vp = v;
+       }
+
+       public void itemStateChanged(ItemEvent e) {
+               _vp.repaint();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurMenu.java b/src2/fr/orsay/lri/varna/controlers/ControleurMenu.java
new file mode 100644 (file)
index 0000000..22c082f
--- /dev/null
@@ -0,0 +1,738 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Universit� Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+
+import java.awt.Color;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.File;
+import java.text.ParseException;
+import java.util.ArrayList;
+
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JColorChooser;
+import javax.swing.JOptionPane;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionJPEGEncoding;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionWritingForbidden;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.views.VueBPThickness;
+import fr.orsay.lri.varna.views.VueMenu;
+
+/**
+ * This listener controls menu items
+ * 
+ * @author darty
+ * 
+ */
+public class ControleurMenu implements InterfaceVARNAListener,
+               ActionListener {
+
+       private VARNAPanel _vp;
+       @SuppressWarnings("unused")
+       private VueMenu _vm;
+       private String _type;
+       private String _color;
+       private Object _source;
+
+       /**
+        * Creates the menu listener
+        * 
+        * @param _varnaPanel
+        *            The VARNAPanel
+        */
+       public ControleurMenu(VARNAPanel _varnaPanel, VueMenu _vueMenu) {
+               _vp = _varnaPanel;
+               _vm = _vueMenu;
+               _vp.getRNA().addVARNAListener(this);
+       }
+
+       public void actionPerformed(ActionEvent e) {
+               String[] temp = e.getActionCommand().split(",");
+               _source = e.getSource();
+               _type = temp[0];
+               if (temp.length > 1)
+                       _color = temp[1];
+               else
+                       _color = "";
+               // selon l'option choisie dans le menu:
+               if (!optionRedraw())
+                       if (!optionExport())
+                               if (!optionImport())
+                                       if (!optionRNADisplay())
+                                               if (!optionTitle())
+                                                       if (!optionColorMap())
+                                                               if (!optionView())
+                                                                       if (!optionBase())
+                                                                               if (!optionBasePair())
+                                                                                       if (!optionLoop())
+                                                                                               if (!option3prime())
+                                                                                                       if (!option5prime())
+                                                                                                               if (!optionHelix())
+                                                                                                                       if (!optionStem())
+                                                                                                                               if (!optionBulge())
+                                                                                                                                       if (!optionAnnotation())
+                                                                                                                                               if (!optionEditRNA())
+                                                                                                                                                       _vp.errorDialog(new Exception("Uknown action command '"+_type+"'"));
+       }
+       
+       private boolean optionEditRNA()
+       {
+               if (_type.equals("editallbps")) {
+                       _vp.getVARNAUI().UIEditAllBasePairs();
+               }
+               else if (_type.equals("editallbases")) {
+                       _vp.getVARNAUI().UIEditAllBases();
+               }
+               else return false;
+               return true;
+       }
+
+       private boolean optionAnnotation() {
+               if (!_type.contains("annotation"))
+                       return false;
+               // a partir du menu principale (gestion des annotations)
+               if (_type.equals("annotationsaddPosition")) {
+                       _vp.getVARNAUI().UIAnnotationsAddPosition(_vp.getPopup().getSpawnPoint().x,_vp.getPopup().getSpawnPoint().y);
+               } else if (_type.equals("annotationsaddBase")) {
+                       _vp.getVARNAUI().UIAnnotationsAddBase(_vp.getPopup().getSpawnPoint().x,_vp.getPopup().getSpawnPoint().y);
+               } else if (_type.equals("annotationsaddLoop")) {
+                       _vp.getVARNAUI().UIAnnotationsAddLoop(_vp.getPopup().getSpawnPoint().x,_vp.getPopup().getSpawnPoint().y);
+               } else if (_type.equals("annotationsaddChemProb")) {
+                       _vp.getVARNAUI().UIAnnotationsAddChemProb(_vp.getPopup().getSpawnPoint().x,_vp.getPopup().getSpawnPoint().y);
+               } else if (_type.equals("annotationsaddRegion")) {
+                       _vp.getVARNAUI().UIAnnotationsAddRegion(_vp.getPopup().getSpawnPoint().x,_vp.getPopup().getSpawnPoint().y);
+               } else if (_type.equals("annotationsaddHelix")) {
+                       _vp.getVARNAUI().UIAnnotationsAddHelix(_vp.getPopup().getSpawnPoint().x,_vp.getPopup().getSpawnPoint().y);
+               } else if (_type.equals("annotationsautohelices")) {
+                       _vp.getVARNAUI().UIAutoAnnotateHelices();
+               } else if (_type.equals("annotationsautointerior")) {
+                       _vp.getVARNAUI().UIAutoAnnotateInteriorLoops();
+               } else if (_type.equals("annotationsautoterminal")) {
+                       _vp.getVARNAUI().UIAutoAnnotateTerminalLoops();
+               } else if (_type.equals("annotationsautohelices")) {
+                       _vp.getVARNAUI().UIAutoAnnotateHelices();
+               } else if (_type.equals("annotationsremove")) {
+                       _vp.getVARNAUI().UIAnnotationsRemove();
+               } else if (_type.equals("annotationsautoextremites")) {
+                       _vp.getVARNAUI().UIAutoAnnotateStrandEnds();
+               } else if (_type.equals("annotationsedit")) {
+                       _vp.getVARNAUI().UIAnnotationsEdit();
+                       // a partir du menu selection (annotation la plus proche)
+               } else if (_type.equals("Selectionannotationremove")) {
+                       _vp.getVARNAUI().UIAnnotationRemoveFromAnnotation(_vp.get_selectedAnnotation());
+               } else if (_type.equals("Selectionannotationedit")) {
+                       _vp.getVARNAUI().UIAnnotationEditFromAnnotation(_vp.get_selectedAnnotation());
+
+                       // a partir d'une structure(base, loop, helix) dans l'arn
+                       // (annotation li� a la structure)
+               } else if (_type.endsWith("annotationadd")||_type.contains("annotationremove")||_type.contains("annotationedit")) 
+               {
+                       try {
+                               TextAnnotation.AnchorType type = trouverAncrage();
+                                ArrayList<Integer> listeIndex = new ArrayList<Integer>();
+                               switch(type)
+                               {
+                                       case BASE:
+                                               listeIndex.add(_vp.getNearestBase());
+                                       case LOOP:
+                                               if (_type.startsWith("loop1"))
+                                                       listeIndex = _vp.getRNA().findLoopForward(_vp.getNearestBase());
+                                               else if (_type.startsWith("loop2"))
+                                                       listeIndex = _vp.getRNA().findLoopBackward(_vp.getNearestBase());
+                                               else
+                                                       listeIndex = _vp.getRNA().findLoop(_vp.getNearestBase());
+                                       break;
+                                       case HELIX:
+                                               listeIndex = _vp.getRNA().findHelix(_vp.getNearestBase());
+                                       break;                          
+                               }
+                               if (_type.endsWith("annotationadd"))
+                               { _vp.getVARNAUI().UIAnnotationAddFromStructure(type,listeIndex); }
+                               else if (_type.contains("annotationremove")) 
+                               { _vp.getVARNAUI().UIAnnotationRemoveFromStructure(trouverAncrage(),listeIndex); }
+                               else if (_type.contains("annotationedit")) 
+                               { _vp.getVARNAUI().UIAnnotationEditFromStructure(trouverAncrage(),listeIndex); }
+                                       
+                       } catch (Exception e2) {
+                               e2.printStackTrace();
+                       }
+                       } else
+                       return false;
+               return true;
+       }
+
+       private TextAnnotation.AnchorType trouverAncrage() {
+               if (_type.contains("loop"))
+                       return TextAnnotation.AnchorType.LOOP;
+               if (_type.contains("helix"))
+                       return TextAnnotation.AnchorType.HELIX;
+               if (_type.contains("base"))
+                       return TextAnnotation.AnchorType.BASE;
+               errorDialog(new Exception("probleme d'identification de l'ancrage"));
+               return TextAnnotation.AnchorType.POSITION;
+       }
+
+       private boolean option5prime() {
+               return colorBases();
+       }
+
+       private boolean option3prime() {
+               return colorBases();
+       }
+
+       private boolean optionBulge() {
+               return colorBases();
+       }
+
+       private boolean optionStem() {
+               return colorBases();
+       }
+
+       private boolean optionHelix() {
+               return colorBases();
+       }
+
+       private boolean colorBases() {
+               // System.out.println(_type);
+               ArrayList<Integer> listBase = new ArrayList<Integer>();
+               String phrase = "Choose new " + _type;
+               if (_color.equals("InnerColor")) {
+                       phrase += " inner color";
+                       Color c = JColorChooser.showDialog(_vp, phrase,
+                                       VARNAConfig.BASE_INNER_COLOR_DEFAULT);
+                       if (c != null) {
+                               listBase = listSwitchType(_type);
+                               for (int i = 0; i < listBase.size(); i++) {
+                                       _vp.getRNA().get_listeBases().get(listBase.get(i))
+                                                       .getStyleBase().setBaseInnerColor(c);
+                               }
+                               _vp.repaint();
+                       }
+               } else if (_color.equals("OutlineColor")) {
+                       phrase += " outline color";
+                       Color c = JColorChooser.showDialog(_vp, phrase,
+                                       VARNAConfig.BASE_OUTLINE_COLOR_DEFAULT);
+                       if (c != null) {
+                               listBase = listSwitchType(_type);
+                               for (int i = 0; i < listBase.size(); i++) {
+                                       _vp.getRNA().get_listeBases().get(listBase.get(i))
+                                                       .getStyleBase().setBaseOutlineColor(c);
+                               }
+                               _vp.repaint();
+                       }
+               } else if (_color.equals("NameColor")) {
+                       phrase += " name color";
+                       Color c = JColorChooser.showDialog(_vp, phrase,
+                                       VARNAConfig.BASE_NAME_COLOR_DEFAULT);
+                       if (c != null) {
+                               listBase = listSwitchType(_type);
+                               for (int i = 0; i < listBase.size(); i++) {
+                                       _vp.getRNA().get_listeBases().get(listBase.get(i))
+                                                       .getStyleBase().setBaseNameColor(c);
+                               }
+                               _vp.repaint();
+                       }
+               } else if (_color.equals("NumberColor")) {
+                       phrase += " number color";
+                       Color c = JColorChooser.showDialog(_vp, phrase,
+                                       VARNAConfig.BASE_NUMBER_COLOR_DEFAULT);
+                       if (c != null) {
+                               listBase = listSwitchType(_type);
+                               for (int i = 0; i < listBase.size(); i++) {
+                                       _vp.getRNA().get_listeBases().get(listBase.get(i))
+                                                       .getStyleBase().setBaseNumberColor(c);
+                               }
+                               _vp.repaint();
+                       }
+               } else if (_color.equals("BPColor")) {
+                       phrase += " base-pair color";
+                       Color c = JColorChooser.showDialog(_vp, phrase,
+                                       VARNAConfig.BASE_NUMBER_COLOR_DEFAULT);
+                       if (c != null) {
+                               listBase = listSwitchType(_type);
+                               for (int i = 0; i < listBase.size(); i++) 
+                               {
+                                       for (ModeleBP msbp:_vp.getRNA().getBPsAt(listBase.get(i)))
+                                       {
+                                               if (msbp!=null) {
+                                                       msbp.getStyle().setCustomColor(c);
+                                               }       
+                                       }
+                               }
+                               _vp.repaint();
+                       }
+               } else if (_color.equals("BPColor")) {
+                       phrase += " base-pair color";
+                       Color c = JColorChooser.showDialog(_vp, phrase,
+                                       VARNAConfig.BASE_NUMBER_COLOR_DEFAULT);
+                       if (c != null) {
+                               listBase = listSwitchType(_type);
+                               for (int i = 0; i < listBase.size(); i++) {
+                                       ModeleBase mb = _vp.getRNA().get_listeBases().get(
+                                                       listBase.get(i));
+                                       if (mb.getElementStructure() != -1) {
+                                               mb.getStyleBP().getStyle().setCustomColor(c);
+                                       }
+                               }
+                               _vp.repaint();
+                       }
+               } else if (_color.equals("BPThickness")) {
+                       listBase = listSwitchType(_type);
+                       // System.out.println(listBase.size());
+                       ArrayList<ModeleBP> styleBPs = new ArrayList<ModeleBP>();
+                       for (int i = 0; i < listBase.size(); i++) {
+                               ModeleBase mb = _vp.getRNA().get_listeBases().get(
+                                               listBase.get(i));
+                               if (mb.getElementStructure() != -1) {
+                                       styleBPs.add(mb.getStyleBP());
+                               }
+                       }
+                       VueBPThickness vbpt = new VueBPThickness(_vp, styleBPs);
+                       if (JOptionPane.showConfirmDialog(_vp, vbpt.getPanel(),
+                                       "Set base pair(s) thickness", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) {
+                               vbpt.restoreThicknesses();
+                               _vp.repaint();
+                       }
+               } else
+                       return false;
+               return true;
+       }
+
+       private ArrayList<Integer> listSwitchType(String _type) {
+               if (_type.equals("helix"))
+                       return _vp.getRNA().findHelix(_vp.getNearestBase());
+               if (_type.equals("current")) {
+                       return _vp.getSelectionIndices();
+               }
+               if (_type.equals("allBases")) {
+                       return _vp.getRNA().findAll();
+               }
+               if (_type.equals("loop1")) {
+                       return _vp.getRNA().findLoopForward(_vp.getNearestBase());
+               }
+               if (_type.equals("loop2")) {
+                       return _vp.getRNA().findLoopBackward(_vp.getNearestBase());
+               }
+               if (_type.equals("stem"))
+                       return _vp.getRNA().findStem(_vp.getNearestBase());
+               if (_type.equals("base")) {
+                       ArrayList<Integer> list = new ArrayList<Integer>();
+                       list.add(_vp.getNearestBase());
+                       return list;
+               }
+               if (_type.equals("basepair") || _type.equals("bpcolor")
+                               || _type.equals("bp")) {
+                       ArrayList<Integer> list = new ArrayList<Integer>();
+                       int i = _vp.getNearestBase();
+                       list.add(i);
+                       ModeleBase mb = _vp.getRNA().get_listeBases().get(i);
+                       int j = mb.getElementStructure();
+                       if (mb.getElementStructure() != -1) {
+                               list.add(i);
+                               list.add(j);
+                       }
+                       return list;
+               }
+               if (_type.equals("5'"))
+                       return _vp.getRNA().findNonPairedBaseGroup(_vp.getNearestBase());
+               if (_type.equals("3'"))
+                       return _vp.getRNA().findNonPairedBaseGroup(_vp.getNearestBase());
+               if (_type.equals("bulge"))
+                       return _vp.getRNA().findNonPairedBaseGroup(_vp.getNearestBase());
+               if (_type.equals("all"))
+                       return _vp.getRNA().findAll();
+               return new ArrayList<Integer>();
+       }
+
+       private boolean optionLoop() {
+               return colorBases();
+       }
+
+       private boolean optionBase() {
+               if (_type.equals("baseChar")) {
+                       _vp.getVARNAUI().UISetBaseCharacter();
+                       return true;
+               } else {
+                       return colorBases();
+               }
+       }
+
+       private boolean optionBasePair() {
+               if (_type.equals("basepair")) {
+                       _vp.getVARNAUI().UIEditBasePair();
+                       return true;
+               } else if (_type.equals("bpcolor")) {
+                       _vp.getVARNAUI().UIColorBasePair();
+                       return true;
+               } else if (_type.equals("thickness")) {
+                       _vp.getVARNAUI().UIThicknessBasePair();
+                       return true;
+               }
+               return false;
+       }
+
+       
+       
+       private boolean optionView() {
+               if (_type.equals("background")) {
+                       _vp.getVARNAUI().UISetBackground();
+               } else if (_type.equals("shownc")) {
+                       _vp.getVARNAUI().UIToggleShowNCBP();
+               } else if (_type.equals("showbackbone")) {
+                       _vp.getVARNAUI().UIToggleDrawBackbone();
+               } else if (_type.equals("shownp")) {
+                       _vp.getVARNAUI().UIToggleShowNonPlanar();
+               } else if (_type.equals("spaceBetweenBases")) {
+                       _vp.getVARNAUI().UISetSpaceBetweenBases();
+               } else if (_type.equals("bpheightincrement")) {
+                       _vp.getVARNAUI().UISetBPHeightIncrement();
+               } else if (_type.equals("borderSize")) {
+                       _vp.getVARNAUI().UISetBorder();
+               } else if (_type.startsWith("zoom")) {
+                       if (_type.equals("zoom")) {
+                               _vp.getVARNAUI().UICustomZoom();
+                       } else {
+                               String factor = _type.substring("zoom".length());
+                               double pc = Integer.parseInt(factor);
+                               pc /= 100.0;
+                               _vp.setZoom(new Double(pc));
+                               _vp.repaint();
+                       }
+               } else if (_type.equals("rotation")) {
+                       _vp.getVARNAUI().UIGlobalRotation();
+               } else if (_type.equals("rescale")) {
+                       _vp.getVARNAUI().UIGlobalRescale();
+               } else
+                       return false;
+               return true;
+       }
+
+       
+       private boolean optionTitle() {
+               if (_type.equals("titleDisplay")) {
+                       _vp.getVARNAUI().UISetTitleFont();
+               } else if (_type.equals("setTitle")) {
+                       _vp.getVARNAUI().UISetTitle();
+               } else if (_type.equals("titleColor")) {
+                       _vp.getVARNAUI().UISetTitleColor();
+               } else
+                       return false;
+               return true;
+       }
+
+               
+       private boolean optionColorMap() {
+               if (_type.equals("toggleshowcolormap")) {
+                       _vp.getVARNAUI().UIToggleColorMap();
+               } else  if (_type.equals("colormapcaption")) {
+                       _vp.getVARNAUI().UISetColorMapCaption();
+               } else  if (_type.equals("colormapstyle")) {
+                       _vp.getVARNAUI().UISetColorMapStyle();
+               } else  if (_type.equals("colormaploadvalues")) {
+                       _vp.getVARNAUI().UILoadColorMapValues();
+               } else  if (_type.equals("colormapvalues")) {
+                       _vp.getVARNAUI().UISetColorMapValues();
+               } else
+                       return false;
+               return true;
+       }
+
+       private boolean optionRNADisplay() {
+               // les options d'affichages generales
+               if (_type.equals("gaspin")) {
+                       _vp.getVARNAUI().UIToggleGaspinMode();
+               } else if (_type.equals("backbone")) {
+                       _vp.getVARNAUI().UISetBackboneColor();
+               } else if (_type.equals("bonds")) {
+                       Color c = JColorChooser.showDialog(_vp, "Choose new bonds color",
+                                       _vp.getBackground());
+                       if (c != null) {
+                               _vp.setDefaultBPColor(c);
+                               _vp.repaint();
+                       }
+               } else if (_type.equals("basecolorforBP")) {
+                       if (_source != null) {
+                               if (_source instanceof JCheckBoxMenuItem) {
+                                       JCheckBoxMenuItem check = (JCheckBoxMenuItem) _source;
+                                       _vp.setUseBaseColorsForBPs(check.getState());
+                                       _vp.repaint();
+                               }
+                       }
+               } else if (_type.equals("bpstyle")) {
+                       _vp.getVARNAUI().UISetBPStyle();
+               } else if (_type.equals("specialbasecolored")) {
+                       _vp.getVARNAUI().UIToggleColorSpecialBases();
+               } else if (_type.equals("showwarnings")) {
+                       _vp.getVARNAUI().UIToggleShowWarnings();
+               } else if (_type.equals("dashbasecolored")) {
+                       _vp.getVARNAUI().UIToggleColorGapsBases();
+               } else if (_type.equals("numPeriod")) {
+                       _vp.getVARNAUI().UISetNumPeriod();
+               } else if (_type.equals("eachKind")) {
+                       if (_vp.getRNA().get_listeBases() != null) {
+                               _vp.getVARNAUI().UIBaseTypeColor();
+                       } else {
+                               _vp.emitWarning("No base");
+                       }
+               } else if (_type.equals("eachCouple")) {
+                       if (_vp.getRNA().get_listeBases() != null
+                                       && _vp.getRNA().get_listeBases().size() != 0) {
+                               _vp.getVARNAUI().UIBasePairTypeColor();
+                       } else {
+                               _vp.emitWarning("No base");
+                       }
+               } else if (_type.equals("eachBase")) {
+                       if (_vp.getRNA().get_listeBases() != null
+                                       && _vp.getRNA().get_listeBases().size() != 0) {
+                               _vp.getVARNAUI().UIBaseAllColor();
+                       } else {
+                               _vp.emitWarning("No base");
+                       }
+               } else if (_type.equals("specialBasesColor")) {
+                       _vp.getVARNAUI().UIPickSpecialBasesColor();
+               } else if (_type.equals("dashBasesColor")) {
+                       _vp.getVARNAUI().UIPickGapsBasesColor();
+               } else
+                       return colorBases();
+               return true;
+       }
+
+       private boolean optionImport() {
+               if (_type.equals("userInput")) {
+                       try {
+                               _vp.getVARNAUI().UIManualInput();
+                       } catch (ParseException e1) {
+                               errorDialog(e1);
+                       } catch (ExceptionNonEqualLength e2) {
+                               errorDialog(e2);
+                       }
+               } else if (_type.equals("file")) {
+                       try {
+                               _vp.getVARNAUI().UIFile();
+                       } catch (ExceptionNonEqualLength e1) {
+                               errorDialog(e1);
+                       }
+               } else if (_type.equals("print")) {
+                       _vp.getVARNAUI().UIPrint();
+               } else if (_type.equals("about")) {
+                       _vp.getVARNAUI().UIAbout();
+               } else
+                       return false;
+               return true;
+       }
+
+       private boolean optionRedraw() {
+               if (_type.equals("reset")) {
+                       _vp.getVARNAUI().UIReset();
+               } else if (_type.equals("circular")) {
+                       _vp.getVARNAUI().UICircular();
+               } else if (_type.equals("radiate")) {
+                       _vp.getVARNAUI().UIRadiate();
+               } else if (_type.equals("naview")) {
+                       _vp.getVARNAUI().UINAView();
+               } else if (_type.equals("varnaview")) {
+                       _vp.getVARNAUI().UIVARNAView();
+               } else if (_type.equals("motifview")) {
+                       _vp.getVARNAUI().UIMOTIFView();
+               } else if (_type.equals("line")) {
+                       _vp.getVARNAUI().UILine();
+               } else if (_type.equals("flat")) {
+                       _vp.getVARNAUI().UIToggleFlatExteriorLoop();
+               } else
+                       return false;
+               return true;
+       }
+
+       private boolean optionExport() {
+               if (_type.equals("saveas")) {
+                       try {
+                               _vp.getVARNAUI().UISaveAs();
+                       } catch (ExceptionExportFailed e1) {
+                               errorDialog(e1);
+                       } catch (ExceptionPermissionDenied e1) {
+                               errorDialog(e1);
+                       }
+               } else if (_type.equals("dbn")) {
+                       try {
+                               _vp.getVARNAUI().UISaveAsDBN();
+                       } catch (ExceptionExportFailed e) {
+                               errorDialog(e);
+                       } catch (ExceptionPermissionDenied e) {
+                               errorDialog(e);
+                       }
+               } else if (_type.equals("bpseq")) {
+                       try {
+                               _vp.getVARNAUI().UISaveAsBPSEQ();
+                       } catch (ExceptionExportFailed e) {
+                               errorDialog(e);
+                       } catch (ExceptionPermissionDenied e) {
+                               errorDialog(e);
+                       }
+               } else if (_type.equals("ct")) {
+                       try {
+                               _vp.getVARNAUI().UISaveAsCT();
+                       } catch (ExceptionExportFailed e) {
+                               errorDialog(e);
+                       } catch (ExceptionPermissionDenied e) {
+                               errorDialog(e);
+                       }
+               } else if (_type.equals("eps")) {
+                       try {
+                               _vp.getVARNAUI().UIExportEPS();
+                       } catch (ExceptionWritingForbidden e1) {
+                               errorDialog(e1);
+                       } catch (ExceptionExportFailed e) {
+                               errorDialog(e);
+                       }
+               } else if (_type.equals("tikz")) {
+                       try {
+                               _vp.getVARNAUI().UIExportTIKZ();
+                       } catch (ExceptionWritingForbidden e1) {
+                               errorDialog(e1);
+                       } catch (ExceptionExportFailed e) {
+                               errorDialog(e);
+                       }
+               } else if (_type.equals("xfig")) {
+                       try {
+                               _vp.getVARNAUI().UIExportXFIG();
+                       } catch (ExceptionWritingForbidden e1) {
+                               errorDialog(e1);
+                       } catch (ExceptionExportFailed e) {
+                               errorDialog(e);
+                       }
+               } else if (_type.equals("svg")) {
+                       try {
+                               _vp.getVARNAUI().UIExportSVG();
+                       } catch (ExceptionWritingForbidden e1) {
+                               errorDialog(e1);
+                       } catch (ExceptionExportFailed e) {
+                               errorDialog(e);
+                       }
+               } else if (_type.equals("jpeg")) {
+                       try {
+                               _vp.getVARNAUI().UIExportJPEG();
+                       } catch (ExceptionJPEGEncoding e1) {
+                               errorDialog(e1);
+                       } catch (ExceptionExportFailed e1) {
+                               errorDialog(e1);
+                       }
+               } else if (_type.equals("png")) {
+                       try {
+                               _vp.getVARNAUI().UIExportPNG();
+                       } catch (ExceptionExportFailed e1) {
+                               errorDialog(e1);
+                       }
+               } else
+                       return false;
+               return true;
+       }
+
+       /**
+        * Return the extension of a file, it means the string after the last dot of
+        * the file name
+        * 
+        * @param f
+        *            The file
+        * @return <code>null</code> if the file name have no dot<br>
+        *         <code>ext</code> if the file name contains a dot
+        */
+       public String getExtension(File f) {
+               String s = f.getName();
+               return getExtension(s);
+       }
+
+       /**
+        * Return the extension of a string, it means the string after the last dot
+        * of the path
+        * 
+        * @param s
+        *            The strnig o the path
+        * @return <code>null</code> if the path have no dot<br>
+        *         <code>ext</code> if the path contains a dot
+        */
+       public String getExtension(String s) {
+               String ext = null;
+               int i = s.lastIndexOf('.');
+
+               if (i > 0 && i < s.length() - 1) {
+                       ext = s.substring(i + 1).toLowerCase();
+               }
+               return ext;
+       }
+
+       /**
+        * Open an error message dialog with the exception message
+        * 
+        * @param e1
+        *            The <code>Exception</code>
+        */
+       public void errorDialog(Exception e1) {
+               if (_vp.isErrorsOn())
+                       JOptionPane.showMessageDialog(_vp, e1.getMessage(), "VARNA Error",
+                                       JOptionPane.ERROR_MESSAGE);
+       }
+
+       public void onStructureRedrawn() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onWarningEmitted(String s) {
+               if (_vp.isErrorsOn())
+                       JOptionPane.showMessageDialog(_vp,s, "VARNA Warning",
+                                       JOptionPane.ERROR_MESSAGE);
+       }
+
+       public void onLoad(String path) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onLoaded() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onUINewStructure(VARNAConfig v, RNA r) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onZoomLevelChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void onTranslationChanged() {
+               // TODO Auto-generated method stub
+               
+       }
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurMolette.java b/src2/fr/orsay/lri/varna/controlers/ControleurMolette.java
new file mode 100644 (file)
index 0000000..5783525
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Point;
+import java.awt.event.MouseWheelEvent;
+import java.awt.event.MouseWheelListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+
+/**
+ * Listener which control the zoom-in and zoom-out with mouse wheel.
+ * 
+ * @author DARTY Kevin
+ */
+public class ControleurMolette implements MouseWheelListener {
+
+       private VARNAPanel _vp;
+       public ControleurMolette(VARNAPanel vuep) {
+               _vp = vuep;
+       }
+
+       public void mouseWheelMoved(MouseWheelEvent e) {
+               if (_vp.isFocusOwner())
+               {
+                       // Roulement vers le haut => zoom in
+                       if (e.getWheelRotation() == -1) {
+                               _vp.getVARNAUI().UIZoomIn();
+                       }
+                       // Roulement vers le bas => zoom out
+                       else {
+                               _vp.getVARNAUI().UIZoomOut();
+                       }
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurNumPeriod.java b/src2/fr/orsay/lri/varna/controlers/ControleurNumPeriod.java
new file mode 100644 (file)
index 0000000..5a6aca8
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.views.VueNumPeriod;
+
+
+public class ControleurNumPeriod implements ChangeListener {
+
+       private VueNumPeriod _vnp;
+
+       public ControleurNumPeriod(VueNumPeriod vnp) {
+               _vnp = vnp;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               _vnp.get_vp().setNumPeriod(_vnp.getNumPeriod());
+               _vnp.get_vp().repaint();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurScriptParser.java b/src2/fr/orsay/lri/varna/controlers/ControleurScriptParser.java
new file mode 100644 (file)
index 0000000..4688f91
--- /dev/null
@@ -0,0 +1,551 @@
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Color;
+import java.io.StreamTokenizer;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import javax.swing.JOptionPane;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation.ChemProbAnnotationType;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class ControleurScriptParser {
+    private static String SCRIPT_ERROR_PREFIX = "Error";       
+
+
+       private static class Command{
+               Function _f;
+               Vector<Argument> _argv; 
+               public Command(Function f, Vector<Argument> argv)
+               {
+                       _f = f;
+                       _argv = argv;
+               }
+       }; 
+
+       private static abstract class Argument{
+               ArgumentType _t;
+               
+               public Argument(ArgumentType t)
+               {
+                       _t = t;
+               }
+               
+               public ArgumentType getType()
+               {
+                       return _t;
+               }
+               
+               public abstract String toString();
+               
+       }; 
+       
+
+       private static class NumberArgument extends Argument{
+               Number _val; 
+               public NumberArgument(Number val)
+               {
+                       super(ArgumentType.NUMBER_TYPE);
+                       _val = val;
+               }
+               public Number getNumber()
+               {
+                       return _val;
+               }
+               public String toString()
+               {
+                       return _val.toString();
+               }
+       }; 
+       
+       private static class ColorArgument extends Argument{
+               Color _val; 
+               public ColorArgument(Color val)
+               {
+                       super(ArgumentType.COLOR_TYPE);
+                       _val = val;
+               }
+               public Color getColor()
+               {
+                       return _val;
+               }
+               public String toString()
+               {
+                       return _val.toString();
+               }
+       }; 
+
+       private static class BooleanArgument extends Argument{
+               boolean _val; 
+               public BooleanArgument(boolean val)
+               {
+                       super(ArgumentType.BOOLEAN_TYPE);
+                       _val = val;
+               }
+               public boolean getBoolean()
+               {
+                       return _val;
+               }
+               public String toString()
+               {
+                       return ""+_val;
+               }
+       }; 
+
+       private static class StringArgument extends Argument{
+               String _val; 
+               public StringArgument(String val)
+               {
+                       super(ArgumentType.STRING_TYPE);
+                       _val = val;
+               }
+               public String toString()
+               {
+                       return _val.toString();
+               }
+       }; 
+
+       private static class ArrayArgument extends Argument{
+               Vector<Argument> _val; 
+               public ArrayArgument(Vector<Argument> val)
+               {
+                       super(ArgumentType.ARRAY_TYPE);
+                       _val = val;
+               }
+               public int getSize()
+               {
+                       return _val.size();
+               }
+               public Argument getArgument(int i)
+               {
+                       return _val.get(i);
+               }
+               public String toString()
+               {
+                       return _val.toString();
+               }
+       }; 
+       
+       
+       private enum ArgumentType{
+               STRING_TYPE,
+               NUMBER_TYPE,
+               BOOLEAN_TYPE,
+               ARRAY_TYPE,
+               COLOR_TYPE
+       };
+    
+    
+    private enum Function{
+               ADD_CHEM_PROB("addchemprob",new ArgumentType[] {ArgumentType.NUMBER_TYPE,ArgumentType.NUMBER_TYPE,ArgumentType.STRING_TYPE,ArgumentType.NUMBER_TYPE,ArgumentType.COLOR_TYPE,ArgumentType.BOOLEAN_TYPE}),
+       ERASE_SEQ("eraseseq",new ArgumentType[] {}),
+               RESET_CHEM_PROB("resetchemprob",new ArgumentType[] {}),
+               SET_COLOR_MAP_MIN("setcolormapminvalue",new ArgumentType[]{ArgumentType.NUMBER_TYPE}),
+               SET_COLOR_MAP_MAX("setcolormapmaxvalue",new ArgumentType[]{ArgumentType.NUMBER_TYPE}),
+               SET_COLOR_MAP("setcolormap",new ArgumentType[]{ArgumentType.STRING_TYPE}),
+               SET_CUSTOM_COLOR_MAP("setcustomcolormap",new ArgumentType[]{ArgumentType.ARRAY_TYPE}),
+               SET_SEQ("setseq",new ArgumentType[]{ArgumentType.STRING_TYPE}),
+               SET_STRUCT("setstruct",new ArgumentType[]{ArgumentType.STRING_TYPE}),
+               SET_STRUCT_SMOOTH("setstructsmooth",new ArgumentType[] {ArgumentType.STRING_TYPE}),
+               SET_TITLE("settitle",new ArgumentType[] {ArgumentType.STRING_TYPE}),
+               SET_RNA("setrna",new ArgumentType[]{ArgumentType.STRING_TYPE,ArgumentType.STRING_TYPE}),
+               SET_RNA_SMOOTH("setrnasmooth",new ArgumentType[]{ArgumentType.STRING_TYPE,ArgumentType.STRING_TYPE}),
+               SET_SELECTION("setselection",new ArgumentType[]{ArgumentType.ARRAY_TYPE}),
+               SET_VALUES("setvalues",new ArgumentType[]{ArgumentType.ARRAY_TYPE}),
+               TOGGLE_SHOW_COLOR_MAP("toggleshowcolormap",new ArgumentType[]{}),
+               REDRAW("redraw",new ArgumentType[] {ArgumentType.STRING_TYPE}),
+               UNKNOWN("N/A",new ArgumentType[] {});
+               
+               String _funName;
+               ArgumentType[] _args;
+               Function(String funName, ArgumentType[] args)
+               {
+                       _funName = funName;
+                       _args = args;
+               }
+               ArgumentType[] getPrototype()
+               {
+                       return this._args;
+               }
+               String getFunName()
+               {
+                       return this._funName;
+               }
+               
+       };
+       
+       private static Hashtable<String,Function> _name2Fun = new Hashtable<String,Function>();  
+       private static Hashtable<Function,ArgumentType[]> _fun2Prot = new Hashtable<Function,ArgumentType[]>();
+       
+       
+       private static void initFunctions()
+       {
+               if (_name2Fun.size()>0)
+               { return; }
+               Function[] funs = Function.values();
+               for(int i=0;i<funs.length;i++)
+               {
+                       Function fun = funs[i];
+                       _name2Fun.put(fun.getFunName(),fun);
+                       _fun2Prot.put(fun,fun.getPrototype());
+               }                       
+       }
+       
+       private static Function getFunction(String f)
+       {
+               String s = f.trim().toLowerCase();
+               if (_name2Fun.containsKey(s))
+                       return _name2Fun.get(s);
+               return Function.UNKNOWN;
+       }
+
+       private static ArgumentType[] getPrototype(Function f)
+       {
+               if (_fun2Prot.containsKey(f))
+                       return _fun2Prot.get(f);
+               return new ArgumentType[0];
+       }       
+       
+    public static void executeScript(VARNAPanel vp, String cmdtxt) throws Exception
+    {
+       Vector<Command> cmds = parseScript(cmdtxt);
+       for(int i=0;i<cmds.size();i++)
+       {
+               Command cmd = cmds.get(i);
+               switch(cmd._f)
+               {
+                       case ADD_CHEM_PROB:
+                       {
+                               int from = (int)((NumberArgument) cmd._argv.get(0)).getNumber().intValue();
+                               int to = (int)((NumberArgument) cmd._argv.get(1)).getNumber().intValue();
+                               ChemProbAnnotationType t = ChemProbAnnotation.annotTypeFromString(((StringArgument) cmd._argv.get(2)).toString());
+                               double intensity = ((NumberArgument) cmd._argv.get(3)).getNumber().doubleValue();
+                               Color c = ((ColorArgument) cmd._argv.get(4)).getColor();
+                               boolean out = ((BooleanArgument) cmd._argv.get(5)).getBoolean();
+                               vp.getRNA().addChemProbAnnotation(new ChemProbAnnotation(
+                                               vp.getRNA().getBaseAt(from),
+                                               vp.getRNA().getBaseAt(to),
+                                               t,
+                                               intensity,
+                                               c,
+                                               out));
+                       }
+                       break;
+                       case ERASE_SEQ:
+                       {
+                               vp.eraseSequence();
+                       }
+                       break;
+                       case RESET_CHEM_PROB:
+                       {
+                               vp.getRNA().clearChemProbAnnotations();
+                               vp.repaint();
+                       }
+                       break;
+                       case SET_COLOR_MAP_MIN:
+                       {
+                               vp.setColorMapMinValue(((NumberArgument) cmd._argv.get(0)).getNumber().doubleValue());
+                       }
+                       break;
+                       case SET_COLOR_MAP_MAX:
+                       {
+                               vp.setColorMapMaxValue(((NumberArgument) cmd._argv.get(0)).getNumber().doubleValue());
+                       }
+                       break;
+                       case SET_COLOR_MAP:
+                       {
+                               vp.setColorMap(ModeleColorMap.parseColorMap(cmd._argv.get(0).toString()));
+                       }
+                       break;
+                       case SET_CUSTOM_COLOR_MAP:
+                       {
+                               ModeleColorMap cm = new ModeleColorMap();
+                               //System.out.println("a"+cmd._argv.get(0));
+                               ArrayArgument arg = (ArrayArgument) cmd._argv.get(0);
+                               for (int j=0;j<arg.getSize();j++)
+                               {
+                                       Argument a = arg.getArgument(j);
+                                       if (a._t==ArgumentType.ARRAY_TYPE)
+                                       { 
+                                       //System.out.println("%");
+                                               ArrayArgument aarg = (ArrayArgument) a; 
+                                               if (aarg.getSize()==2)
+                                               {
+                                                       Argument a1 = aarg.getArgument(0);
+                                                       Argument a2 = aarg.getArgument(1);
+                                               //System.out.println("& |"+a1+"| ["+a1.getType()+"] |"+a2+"| ["+a2.getType()+"]");
+                                                       if ((a1.getType()==ArgumentType.NUMBER_TYPE)&&(a2.getType()==ArgumentType.COLOR_TYPE))
+                                                       {
+                                               //System.out.println("+");
+                                                               cm.addColor(((NumberArgument)a1).getNumber().doubleValue(),((ColorArgument)a2).getColor());
+                                                       }
+                                               }
+                                       }
+                               }                               
+                               vp.setColorMap(cm);
+                       }
+                       break;
+                       case SET_RNA:
+                       {
+                               String seq = cmd._argv.get(0).toString();
+                               String str = cmd._argv.get(1).toString();
+                               vp.drawRNA(seq, str);
+                       }
+                       break;
+                       case SET_RNA_SMOOTH:
+                       {
+                               String seq = cmd._argv.get(0).toString();
+                               String str = cmd._argv.get(1).toString();
+                               vp.drawRNAInterpolated(seq, str);
+                               vp.repaint();
+                       }
+                       break;
+                       case SET_SELECTION:
+                       {
+                               ArrayArgument arg = (ArrayArgument) cmd._argv.get(0);
+                               ArrayList<Integer> vals = new ArrayList<Integer>();
+                               for (int j=0;j<arg.getSize();j++)
+                               {
+                                       Argument a = arg.getArgument(j);
+                                       if (a._t==ArgumentType.NUMBER_TYPE)
+                                       { 
+                                               NumberArgument narg = (NumberArgument) a; 
+                                               vals.add(narg.getNumber().intValue()); 
+                                       }
+                               }                               
+                               vp.setSelection(vals);
+                               vp.repaint();
+                       }
+                       break;  
+                       case SET_SEQ:
+                       {
+                               String seq = cmd._argv.get(0).toString();
+                               vp.setSequence(seq);
+                       }
+                       break;
+                       case SET_STRUCT:
+                       {
+                               String seq = vp.getRNA().getSeq();
+                               String str = cmd._argv.get(0).toString();
+                               vp.drawRNA(seq, str);
+                       }
+                       break;
+                       case SET_STRUCT_SMOOTH:
+                       {
+                               String seq = vp.getRNA().getSeq();
+                               String str = cmd._argv.get(0).toString();
+                               vp.drawRNAInterpolated(seq, str);
+                               vp.repaint();
+                       }
+                       break;
+                       case SET_TITLE:
+                       {
+                               vp.setTitle(cmd._argv.get(0).toString());
+                       }
+                       break;
+                       case SET_VALUES:
+                       {
+                               ArrayArgument arg = (ArrayArgument) cmd._argv.get(0);
+                               Double[] vals = new Double[arg.getSize()];
+                               for (int j=0;j<arg.getSize();j++)
+                               {
+                                       Argument a = arg.getArgument(j);
+                                       if (a._t==ArgumentType.NUMBER_TYPE)
+                                       { 
+                                               NumberArgument narg = (NumberArgument) a; 
+                                               vals[j] = narg.getNumber().doubleValue(); 
+                                       }
+                               }                               
+                               vp.setColorMapValues(vals);
+                               vp.repaint();
+                       }
+                       break;
+                       case REDRAW:
+                       {
+                               int mode = -1;
+                               String modeStr = cmd._argv.get(0).toString().toLowerCase(); 
+                               if (modeStr.equals("radiate"))
+                                       mode = RNA.DRAW_MODE_RADIATE;
+                               else if (modeStr.equals("circular"))
+                                       mode = RNA.DRAW_MODE_CIRCULAR;
+                               else if (modeStr.equals("naview"))
+                                       mode = RNA.DRAW_MODE_NAVIEW;
+                               else if (modeStr.equals("linear"))
+                                       mode = RNA.DRAW_MODE_LINEAR;
+                               if (mode != -1)
+                                 vp.drawRNA(vp.getRNA(), mode);
+                       }
+                       break;
+                       case TOGGLE_SHOW_COLOR_MAP:
+                       {
+                               vp.setColorMapVisible(!vp.getColorMapVisible());
+                       }
+                       break;
+                       default:
+                               throw new Exception(SCRIPT_ERROR_PREFIX+": Method '"+cmd._f+"' unimplemented.");
+               }
+               vp.repaint();
+       }
+    }
+
+       
+       
+       private static Color parseColor(String s)
+       {
+               Color result = null;
+               try {result = Color.decode(s); }
+               catch (Exception e) {}
+               return result;
+       }
+
+       private static Boolean parseBoolean(String s)
+       {
+               Boolean result = null;
+               if (s.toLowerCase().equals("true"))
+                       result = new Boolean(true);
+               if (s.toLowerCase().equals("false"))
+                       result = new Boolean(false);
+               return result;
+       }
+
+       
+       private static Vector<Argument> parseArguments(StreamTokenizer st, boolean parType) throws Exception
+       {
+               Vector<Argument> result = new Vector<Argument>();
+               while((st.ttype!=')' && parType) || (st.ttype!=']' && !parType))
+               {
+                       st.nextToken();
+                         //System.out.println(""+ (parType?"Par.":"Bra.")+" "+(char)st.ttype);
+                       switch(st.ttype)
+                       {
+                         case(StreamTokenizer.TT_NUMBER):
+                         {
+                                 result.add(new NumberArgument(st.nval));
+                         }
+                         break;
+                         case(StreamTokenizer.TT_WORD):
+                         {
+                                 Color c = parseColor(st.sval);
+                                 if (c!=null)
+                                 {
+                                        result.add(new ColorArgument(c));
+                                 }
+                                 else
+                                 {
+                                         Boolean b = parseBoolean(st.sval);
+                                         if (b!=null)
+                                         {
+                                                result.add(new BooleanArgument(b));
+                                         }
+                                         else
+                                         {
+                                                result.add(new StringArgument(st.sval));                                         
+                                         }
+                                 }
+                         }
+                         break;
+                         case('"'):
+                         {
+                                 result.add(new StringArgument(st.sval));
+                         }
+                         break;
+                         case('['):
+                         {
+                                 result.add(new ArrayArgument(parseArguments(st, false)));
+                         }
+                         break;
+                         case('('):
+                         {
+                                 result.add(new ArrayArgument(parseArguments(st, true)));
+                         }
+                         break;
+                         case(')'):
+                         {
+                                 if (parType)
+                                   return result;
+                                 else
+                                       throw new Exception(SCRIPT_ERROR_PREFIX+": Opening "+(parType?"parenthesis":"bracket")+" matched with a closing "+(!parType?"parenthesis":"bracket"));                                    
+                         }
+                         case(']'):
+                         {
+                                 if (!parType)
+                                   return result;
+                                 else
+                                       throw new Exception(SCRIPT_ERROR_PREFIX+": Opening "+(parType?"parenthesis":"bracket")+" matched with a closing "+(!parType?"parenthesis":"bracket"));                                    
+                         }
+                         case(','):
+                                 break;
+                         case(StreamTokenizer.TT_EOF):
+                         {
+                                 throw new Exception(SCRIPT_ERROR_PREFIX+": Unmatched opening "+(parType?"parenthesis":"bracket"));
+                         }
+                         
+                       }
+               }
+               return result;
+       }
+       
+       
+       private static Command parseCommand(String cmd) throws Exception
+       {
+               int cut = cmd.indexOf("(");
+               if (cut==-1)
+               {
+                       throw new Exception(SCRIPT_ERROR_PREFIX+": Syntax error");
+               }
+               String fun = cmd.substring(0,cut);
+               Function f  = getFunction(fun);
+               if (f==Function.UNKNOWN)
+               { throw new Exception(SCRIPT_ERROR_PREFIX+": Unknown function \""+fun+"\""); }
+               StreamTokenizer st = new StreamTokenizer(new StringReader(cmd.substring(cut+1)));
+               st.eolIsSignificant(false);
+               st.parseNumbers();
+               st.quoteChar('\"');
+               st.ordinaryChar('=');
+               st.ordinaryChar(',');
+               st.ordinaryChar('[');
+               st.ordinaryChar(']');
+               st.ordinaryChar('(');
+               st.ordinaryChar(')');
+               st.wordChars('#', '#');
+               Vector<Argument> argv = parseArguments(st,true);
+               checkArgs(f,argv);
+               Command result = new Command(f,argv); 
+               return result;
+       }
+       
+       private static boolean checkArgs(Function f, Vector<Argument> argv) throws Exception
+       {
+               ArgumentType[] argtypes = getPrototype(f);
+               if (argtypes.length!=argv.size())
+                       throw new Exception(SCRIPT_ERROR_PREFIX+": Wrong number of argument for function \""+f+"\".");
+               for (int i=0;i<argtypes.length;i++)
+               {
+                       if (argtypes[i] != argv.get(i)._t)
+                       {
+                               throw new Exception(SCRIPT_ERROR_PREFIX+": Bad type ("+argtypes[i]+"!="+argv.get(i)._t+") for argument #"+(i+1)+" in function \""+f+"\".");
+                       }
+               }
+               return true;
+       }
+       
+       private static Vector<Command> parseScript(String cmd) throws Exception
+       {
+               initFunctions();
+               Vector<Command> cmds = new Vector<Command>();
+               String[] data = cmd.split(";");
+               for (int i=0;i<data.length;i++)
+               {
+                       cmds.add(parseCommand(data[i].trim()));
+               }
+               return cmds;
+       }
+       
+       
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurSelectionHighlight.java b/src2/fr/orsay/lri/varna/controlers/ControleurSelectionHighlight.java
new file mode 100644 (file)
index 0000000..11e0134
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Vector;
+
+import javax.swing.JMenuItem;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+
+
+public class ControleurSelectionHighlight implements ChangeListener {
+       private Collection<? extends ModeleBase> _selection;
+       private VARNAPanel _target;
+       private JMenuItem _parent;
+
+       public ControleurSelectionHighlight(int elem, VARNAPanel v, JMenuItem parent) {
+               ArrayList<Integer> sel = new ArrayList<Integer>();
+               sel.add(elem);
+               _selection = v.getRNA().getBasesAt(sel);
+               _target = v;
+               _parent = parent;
+       }
+
+       public ControleurSelectionHighlight(Vector<Integer> sel, VARNAPanel v,
+                       JMenuItem parent) {
+               this(new ArrayList<Integer>(sel), v, parent);
+       }
+
+       public ControleurSelectionHighlight(ArrayList<Integer> sel, VARNAPanel v,
+                       JMenuItem parent) {
+               this(v.getRNA().getBasesAt(sel),v,parent);
+       }
+       
+       public ControleurSelectionHighlight(Collection<? extends ModeleBase> sel, VARNAPanel v,
+                       JMenuItem parent) {
+               _selection = sel;
+               _target = v;
+               _parent = parent;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               if (_parent.isSelected()) {
+                       _target.saveSelection();
+                       _target.setSelection(_selection);
+               } else {
+                       _target.restoreSelection();
+               }
+
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurSliderLabel.java b/src2/fr/orsay/lri/varna/controlers/ControleurSliderLabel.java
new file mode 100644 (file)
index 0000000..c78544e
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import javax.swing.JLabel;
+import javax.swing.JSlider;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+public class ControleurSliderLabel implements ChangeListener {
+
+       private JLabel _l;
+       private double _factor = 1.0;
+
+       public ControleurSliderLabel(JLabel zoomAmountValueLabel) {
+               _l = zoomAmountValueLabel;
+               _factor = 1.0;
+       }
+
+       public ControleurSliderLabel(JLabel zoomAmountValueLabel, boolean percent) {
+               _l = zoomAmountValueLabel;
+               if (percent)
+                       _factor = 0.01;
+       }
+
+       public ControleurSliderLabel(JLabel zoomAmountValueLabel, double factor) {
+               _l = zoomAmountValueLabel;
+               _factor = factor;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               double value = ((JSlider) e.getSource()).getValue();
+               value *= _factor;
+               _l.setText(String.valueOf(value));
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurSpaceBetweenBases.java b/src2/fr/orsay/lri/varna/controlers/ControleurSpaceBetweenBases.java
new file mode 100644 (file)
index 0000000..2ae40a1
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.views.VueSpaceBetweenBases;
+
+
+public class ControleurSpaceBetweenBases implements ChangeListener {
+
+       private VueSpaceBetweenBases _vsbb;
+
+       public ControleurSpaceBetweenBases(VueSpaceBetweenBases vsbb) {
+               _vsbb = vsbb;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               _vsbb.get_vp().setSpaceBetweenBases(_vsbb.getSpace());
+               _vsbb.get_vp().drawRNA();
+               _vsbb.get_vp().repaint();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurTableAnnotations.java b/src2/fr/orsay/lri/varna/controlers/ControleurTableAnnotations.java
new file mode 100644 (file)
index 0000000..5db2797
--- /dev/null
@@ -0,0 +1,167 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+
+import javax.swing.JTable;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.views.VueAnnotation;
+import fr.orsay.lri.varna.views.VueChemProbAnnotation;
+import fr.orsay.lri.varna.views.VueHighlightRegionEdit;
+
+
+/**
+ * Mouse action and motion listener for AnnotationTableModel
+ * 
+ * @author Darty@lri.fr
+ * 
+ */
+public class ControleurTableAnnotations implements MouseListener,
+               MouseMotionListener {
+       public static final int REMOVE = 0, EDIT = 1;
+       private JTable _table;
+       private VARNAPanel _vp;
+       private int _type;
+
+       /**
+        * 
+        * @param table
+        * @param vp
+        * @param type
+        *            : REMOVE = 0, EDIT = 1
+        */
+       public ControleurTableAnnotations(JTable table, VARNAPanel vp, int type) {
+               _table = table;
+               _vp = vp;
+               _type = type;
+       }
+
+       public void mouseClicked(MouseEvent arg0) {
+               switch (_type) {
+               case EDIT:
+                       edit();
+                       break;
+               case REMOVE:
+                       remove();
+                       break;
+               default:
+                       break;
+               }
+       }
+
+       /**
+        * if remove case
+        */
+       private void remove() {
+               _vp.set_selectedAnnotation(null);
+               Object o = _table.getValueAt(_table.getSelectedRow(), 0);
+               if (o instanceof TextAnnotation) {
+                       if (!_vp.removeAnnotation((TextAnnotation) o))
+                               _vp.errorDialog(new Exception("Impossible de supprimer"));
+                       _table.setValueAt("Deleted!", _table.getSelectedRow(), 0);
+               }
+               else if (o instanceof ChemProbAnnotation) {
+                       _vp.getRNA().removeChemProbAnnotation((ChemProbAnnotation) o);
+                       _table.setValueAt("Deleted!", _table.getSelectedRow(), 0);
+               }
+               else if (o instanceof HighlightRegionAnnotation) {
+                       _vp.getRNA().removeHighlightRegion((HighlightRegionAnnotation) o);
+                       _table.setValueAt("Deleted!", _table.getSelectedRow(), 0);
+               }
+               _vp.repaint();
+       }
+
+       /**
+        * if edit case
+        */
+       private void edit() {
+               Object o = _table.getValueAt(_table
+                               .getSelectedRow(), 0);
+               if (o instanceof TextAnnotation)
+               {
+               TextAnnotation textAnnot = (TextAnnotation) o; 
+               VueAnnotation vueAnnotation;
+               vueAnnotation = new VueAnnotation(_vp, textAnnot, false);
+               vueAnnotation.show();
+               }else if (o instanceof HighlightRegionAnnotation)
+               {
+                       HighlightRegionAnnotation annot = (HighlightRegionAnnotation) o; 
+                       HighlightRegionAnnotation an = annot.clone(); 
+                       VueHighlightRegionEdit vueAnnotation = new VueHighlightRegionEdit(_vp,annot);
+                       if (!vueAnnotation.show())
+                       {
+                               annot.setBases(an.getBases());
+                               annot.setFillColor(an.getFillColor());
+                               annot.setOutlineColor(an.getOutlineColor());
+                               annot.setRadius(an.getRadius());
+                       }
+               }else if (o instanceof ChemProbAnnotation)
+               {
+                       ChemProbAnnotation annot = (ChemProbAnnotation) o; 
+                       ChemProbAnnotation an = annot.clone(); 
+                       VueChemProbAnnotation vueAnnotation = new VueChemProbAnnotation(_vp,annot);
+                       if (!vueAnnotation.show())
+                       {
+                               annot.setColor(an.getColor());
+                               annot.setIntensity(an.getIntensity());
+                               annot.setType(an.getType());
+                               annot.setOut(an.isOut());
+                       }
+               }
+
+       }
+
+       public void mouseEntered(MouseEvent arg0) {
+       }
+
+       public void mouseExited(MouseEvent arg0) {
+               _vp.set_selectedAnnotation(null);
+               _vp.repaint();
+       }
+
+       public void mousePressed(MouseEvent arg0) {
+       }
+
+       public void mouseReleased(MouseEvent arg0) {
+       }
+
+       public void mouseDragged(MouseEvent arg0) {
+       }
+
+       /**
+        * update selected annotation
+        */
+       public void mouseMoved(MouseEvent arg0) {
+               if (_table.rowAtPoint(arg0.getPoint()) < 0)
+                       return;
+               Object o = _table.getValueAt(_table.rowAtPoint(arg0.getPoint()), 0);
+               if (o.getClass().equals(TextAnnotation.class)
+                               && o != _vp.get_selectedAnnotation()) {
+                       _vp.set_selectedAnnotation((TextAnnotation) o);
+                       _vp.repaint();
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurVARNAPanelKeys.java b/src2/fr/orsay/lri/varna/controlers/ControleurVARNAPanelKeys.java
new file mode 100644 (file)
index 0000000..8dc6eac
--- /dev/null
@@ -0,0 +1,412 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Point;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.geom.Point2D;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.views.VueUI;
+
+
+/**
+ * VARNAPanel Shortcuts Controller
+ * 
+ * @author darty
+ * 
+ */
+public class ControleurVARNAPanelKeys implements KeyListener, FocusListener {
+
+       private VARNAPanel _vp;
+       
+
+       public ControleurVARNAPanelKeys(VARNAPanel vp) {
+               _vp = vp;
+       }
+
+       public void mouseClicked(MouseEvent e) {
+       }
+
+       public void mouseEntered(MouseEvent e) {
+               // prise du focus
+               //_vp.requestFocus();
+               
+       }
+
+       public void mouseExited(MouseEvent e) {
+       }
+
+       public void mousePressed(MouseEvent e) {
+       }
+
+       public void mouseReleased(MouseEvent e) {
+       }
+
+       public void keyPressed(KeyEvent e) {
+               boolean controlDown = (e.getModifiersEx() & (KeyEvent.CTRL_DOWN_MASK)) == KeyEvent.CTRL_DOWN_MASK;
+               boolean shiftDown = (e.getModifiersEx() & (KeyEvent.SHIFT_DOWN_MASK)) == KeyEvent.SHIFT_DOWN_MASK;
+               boolean altDown = (e.getModifiersEx() & (KeyEvent.ALT_DOWN_MASK)) == KeyEvent.ALT_DOWN_MASK;
+               VueUI ui = _vp.getVARNAUI();
+               try {
+                       switch (e.getKeyCode()) {
+                       case (KeyEvent.VK_A):
+                               if (controlDown) {
+                                       ui.UIAbout();
+                               }
+                               break;
+                       case (KeyEvent.VK_B):
+                               if (controlDown) {
+                                       ui.UISetBorder();
+                               }
+                               else
+                                       if (altDown) {
+                                               ui.UIToggleDrawBackbone();
+                                       }
+                               break;
+                       case (KeyEvent.VK_C):
+                               if (shiftDown && controlDown) {
+                                       ui.UISetColorMapCaption();
+                               }
+                               break;
+                       case (KeyEvent.VK_D):
+                               if (controlDown) {
+                                       if (shiftDown) {
+                                               ui.UIPickGapsBasesColor();
+                                       } else {
+                                               ui.UIToggleColorGapsBases();
+                                       }
+                               }
+                               break;
+                       case (KeyEvent.VK_E):
+                               if (controlDown) {
+                                       ui.UIToggleShowNonPlanar();
+                               }
+                               break;
+                       case (KeyEvent.VK_F):
+                               if (controlDown) {
+                                       ui.UIToggleFlatExteriorLoop();
+                               }
+                               break;
+                       case (KeyEvent.VK_G):
+                               if (controlDown) {
+                                       ui.UISetBackground();
+                               }
+                               else if (!shiftDown && altDown) {
+                                 ui.UIToggleGaspinMode();
+                               }
+                               break;
+                       case (KeyEvent.VK_H):
+                               if (controlDown && !shiftDown) {
+                                       ui.UISetBPHeightIncrement();
+                               }
+                               else if (controlDown && shiftDown)
+                               {
+                                       Point2D.Double p = _vp.getLastSelectedPosition();
+                                       ui.UIAnnotationsAddPosition((int)p.x,(int)p.y);
+                               }
+                               break;
+                       case (KeyEvent.VK_J):
+                               if (controlDown) {
+                                       if (shiftDown) {
+                                               ui.UIPickSpecialBasesColor();
+                                       } else {
+                                               ui.UIToggleColorSpecialBases();
+                                       }
+                               }
+                               break;
+                       case (KeyEvent.VK_K):
+                               if (controlDown && shiftDown) {
+                                       ui.UILoadColorMapValues();
+                               }
+                               else if (controlDown) {
+                                       ui.UISetBackboneColor();
+                               }
+                               break;
+                       case (KeyEvent.VK_L):
+                               if (shiftDown && controlDown) {
+                                       ui.UIToggleColorMap();
+                               } else if (controlDown)
+                               {
+                                       ui.UISetColorMapStyle();
+                               } else if (shiftDown)
+                               {
+                                       ui.UISetColorMapValues();
+                               } 
+                               break;
+                       case (KeyEvent.VK_M):
+                               if (controlDown) {
+                                       ui.UISetNumPeriod();
+                               } else if (shiftDown && altDown) {
+                                       ui.UIToggleModifiable();
+                               }
+                               break;
+                       case (KeyEvent.VK_N):
+                               if (controlDown) {
+                                       ui.UIManualInput();
+                               }
+                               break;
+                       case (KeyEvent.VK_O):
+                               if (controlDown) {
+                                       ui.UIFile();
+                               }
+                               break;
+                       case (KeyEvent.VK_P):
+                               if (controlDown && shiftDown) {
+                                       ui.UISetBPStyle();
+                               }
+                               else if (controlDown && !shiftDown) {
+                                       ui.UIPrint();
+                               }
+                               break;
+                       case (KeyEvent.VK_Q):
+                               if      (controlDown && !shiftDown && !altDown) {
+                                       _vp.getVARNAUI().UIAutoAnnotateHelices();
+                               }
+                               else if (controlDown && shiftDown && !altDown) {
+                                       _vp.getVARNAUI().UIAutoAnnotateTerminalLoops();                                 
+                               }
+                               else if (!controlDown && shiftDown && altDown) {
+                                       _vp.getVARNAUI().UIAutoAnnotateInteriorLoops();                                 
+                               }
+                               else if (controlDown && !shiftDown && altDown) {
+                                       _vp.getVARNAUI().UIAutoAnnotateStrandEnds();                                    
+                               }
+                               break;
+                       case (KeyEvent.VK_R):
+                               if (controlDown) {
+                                       if (shiftDown) {
+                                               ui.UIReset();
+                                       } else {
+                                               ui.UIGlobalRotation();
+                                       }
+                               }
+                               break;
+                       case (KeyEvent.VK_S):
+                               if (controlDown) {
+                                       if (shiftDown) {
+                                               ui.UISetSpaceBetweenBases();
+                                       } else {
+                                               ui.UISaveAs();
+                                       }
+                               }
+                               break;
+                       case (KeyEvent.VK_T):
+                               if (controlDown) {
+                                       if (shiftDown) {
+                                               ui.UISetTitleFont();
+                                       } else if (altDown) {
+                                               ui.UISetTitleColor();
+                                       } else {
+                                               ui.UISetTitle();
+                                       }
+                               }
+                               break;
+                       case (KeyEvent.VK_U):
+                               if (controlDown && !shiftDown && !altDown) {
+                                       _vp.getVARNAUI().UIBaseTypeColor();
+                               } else if (!controlDown && shiftDown && !altDown) {
+                                       _vp.getVARNAUI().UIBasePairTypeColor();
+                               } else if (!controlDown && !shiftDown && altDown) {
+                                       _vp.getVARNAUI().UIBaseAllColor();
+                               }
+                               break;
+                       case (KeyEvent.VK_W):
+                               if (controlDown) {
+                                       ui.UIToggleShowNCBP();
+                               }
+                               break;
+                       case (KeyEvent.VK_X):
+                               if (controlDown) {
+                                       ui.UIExport();
+                               }
+                               break;
+                       case (KeyEvent.VK_Y):
+                               if (controlDown) {
+                                       ui.UIRedo();
+                               }
+                       break;
+
+                       case (KeyEvent.VK_Z):
+                               if (controlDown && !shiftDown) {
+                                       ui.UIUndo();
+                               }
+                               else if (controlDown && shiftDown) {
+                                       ui.UIRedo();
+                               }
+                               else if (!controlDown && !shiftDown) {
+                                       ui.UICustomZoom();
+                               }
+                               break;
+                       case (KeyEvent.VK_1):
+                               if (controlDown) {
+                                       ui.UILine();
+                               }
+                               break;
+                       case (KeyEvent.VK_2):
+                               if (controlDown) {
+                                       ui.UICircular();
+                               }
+                               break;
+                       case (KeyEvent.VK_3):
+                               if (controlDown) {
+                                       ui.UIRadiate();
+                               }
+                               break;
+                       case (KeyEvent.VK_4):
+                               if (controlDown) {
+                                       ui.UINAView();
+                               }
+                               break;
+                       case (KeyEvent.VK_5):
+                               if (controlDown) {
+                                       ui.UIVARNAView();
+                               }
+                               break;
+                       case (KeyEvent.VK_6):
+                               if (controlDown) {
+                                       ui.UIMOTIFView();
+                               }
+                               break;
+
+                       // Navigation control keys (Zoom in/out, arrow keys ...)
+                       case (KeyEvent.VK_DOWN):
+                               if (_vp.getZoom() > 1) {
+                                       _vp.setTranslation(new Point(_vp.getTranslation().x,_vp.getTranslation().y-5));
+                                       _vp.checkTranslation();
+                               }
+                               break;
+                       case (KeyEvent.VK_UP):
+                               if (_vp.getZoom() > 1) {
+                                       _vp.setTranslation(new Point(_vp.getTranslation().x,_vp.getTranslation().y+5));
+                                       _vp.checkTranslation();
+                               }
+                               break;
+                       case (KeyEvent.VK_LEFT):
+                               if (_vp.getZoom() > 1) {
+                                       _vp.setTranslation(new Point(_vp.getTranslation().x+5,_vp.getTranslation().y));
+                                       _vp.checkTranslation();
+                               }
+                               break;
+                       case (KeyEvent.VK_RIGHT):
+                               if (_vp.getZoom() > 1) {
+                                       _vp.setTranslation(new Point(_vp.getTranslation().x-5,_vp.getTranslation().y));
+                                       _vp.checkTranslation();
+                               }
+                               break;
+                       case (KeyEvent.VK_EQUALS):
+                       case (KeyEvent.VK_PLUS):
+                               ui.UIZoomIn();
+                               break;
+                       case (KeyEvent.VK_MINUS):
+                               ui.UIZoomOut();
+                               break;
+                       }
+               } catch (Exception e1) {
+                       _vp.errorDialog(e1);
+               }
+               _vp.repaint();
+       }
+
+       /**
+        * if ((e.getKeyCode() == KeyEvent.VK_PLUS)||(e.getKeyChar() == '+')) {
+        * _vp.getVARNAUI().UIZoomIn(); } else if (e.getKeyCode() ==
+        * KeyEvent.VK_MINUS) { _vp.getVARNAUI().UIZoomOut(); } // 1 pour Redraw
+        * Radiate else if (e.getKeyChar() == KeyEvent.VK_1) {
+        * _vp.getVARNAUI().UIRadiate(); } // 2 pour Redraw Circular else if
+        * (e.getKeyChar() == KeyEvent.VK_2) { _vp.getVARNAUI().UICircular(); } // 3
+        * pour Redraw NAView else if (e.getKeyChar() == KeyEvent.VK_3) {
+        * _vp.getVARNAUI().UINAView(); }
+        * 
+        * // 4 for RNA on a line else if (e.getKeyChar() == KeyEvent.VK_4) {
+        * _vp.getVARNAUI().UILine(); } // 5 fun arn random coord else if
+        * (e.isControlDown() && e.getKeyChar() == KeyEvent.VK_9) { for (int i = 0;
+        * i < _vp.getRNA().get_listeBases().size(); i++) {
+        * _vp.getRNA().get_listeBases().get(i).set_coords( new
+        * Point2D.Double(_vp.getWidth() * Math.random(), _vp.getHeight() *
+        * Math.random())); _vp.getRNA().get_listeBases().get(i).set_center( new
+        * Point2D.Double(_vp.getWidth() / 2 Math.random(), _vp.getHeight() / 2
+        * Math.random())); } } // 6 fun random arn structure else if
+        * (e.isControlDown() & e.getKeyChar() == KeyEvent.VK_8) { try {
+        * _vp.drawRNA(_vp.getRNA().getListeBasesToString(), getRandomRNA(), _vp
+        * .getRNA().get_drawMode()); } catch (ExceptionNonEqualLength e1) {
+        * _vp.errorDialog(e1); } } _vp.repaint(); }
+        **/
+
+       public String getRandomRNA() {
+               int pile = 0, j, i = 0;
+               double l;
+               String fun = "";
+               while (i < 2000) {
+                       if (Math.random() > 0.5) {
+                               j = 0;
+                               l = Math.random() * 10;
+                               while (j < l) {
+                                       fun += '.';
+                                       i++;
+                                       j++;
+                               }
+                       } else {
+                               if (Math.random() > 0.5 && pile > 0) {
+                                       j = 0;
+                                       l = Math.random() * 5;
+                                       while (j < l && pile > 0) {
+                                               fun += ')';
+                                               pile--;
+                                               j++;
+                                               i++;
+                                       }
+                               } else {
+                                       j = 0;
+                                       l = Math.random() * 5;
+                                       while (j < l) {
+                                               fun += '(';
+                                               pile++;
+                                               j++;
+                                               i++;
+                                       }
+
+                               }
+                       }
+               }
+               while (pile > 0) {
+                       fun += ')';
+                       pile--;
+               }
+               return fun;
+       }
+
+       public void keyReleased(KeyEvent e) {
+       }
+
+       public void keyTyped(KeyEvent e) {
+       }
+
+       public void focusGained(FocusEvent arg0) {
+               _vp.repaint();
+       }
+
+       public void focusLost(FocusEvent arg0) {
+               _vp.repaint();
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurVueAnnotation.java b/src2/fr/orsay/lri/varna/controlers/ControleurVueAnnotation.java
new file mode 100644 (file)
index 0000000..74da336
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import java.awt.Color;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JColorChooser;
+import javax.swing.event.CaretEvent;
+import javax.swing.event.CaretListener;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.views.VueAnnotation;
+import fr.orsay.lri.varna.views.VueUI;
+
+/**
+ * Annotation View Controller
+ * 
+ * @author Darty@lri.fr
+ * 
+ */
+public class ControleurVueAnnotation implements CaretListener, ChangeListener,
+               ActionListener {
+
+       protected VueAnnotation _vueAnnot;
+
+       /**
+        * Creates a ControleurVueAnnotation
+        * 
+        * @param vueAnnot
+        */
+       public ControleurVueAnnotation(VueAnnotation vueAnnot) {
+               _vueAnnot = vueAnnot;
+       }
+
+       public void caretUpdate(CaretEvent arg0) {
+               _vueAnnot.update();
+       }
+
+       public void stateChanged(ChangeEvent arg0) {
+               _vueAnnot.update();
+       }
+
+       public void actionPerformed(ActionEvent arg0) {
+               if (arg0.getActionCommand().equals("setcolor")) {
+                       final VueUI vui = _vueAnnot.get_vp().getVARNAUI(); // BH SwingJS
+                       vui.showColorDialog("Pick a color", _vueAnnot.getTextAnnotation().getColor(), new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       Color c = (Color) vui.dialogReturnValue;
+                                       if (c != null)
+                                               _vueAnnot.updateColor(c);
+                                       _vueAnnot.update();
+                               }
+                               
+                       });
+                       
+//was:                 Color c = JColorChooser.showDialog(_vueAnnot.get_vp(),
+//                                     "Pick a color", _vueAnnot.getTextAnnotation().getColor());
+//                     if (c != null) {
+//                             _vueAnnot.updateColor(c);
+//                     }
+
+               }
+               _vueAnnot.update();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/controlers/ControleurZoom.java b/src2/fr/orsay/lri/varna/controlers/ControleurZoom.java
new file mode 100644 (file)
index 0000000..7987fd3
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.controlers;
+
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.views.VueZoom;
+
+
+public class ControleurZoom implements ChangeListener {
+
+       private VueZoom _vz;
+
+       public ControleurZoom(VueZoom vz) {
+               _vz = vz;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               _vz.get_vp().setZoom(_vz.getZoom());
+               _vz.get_vp().repaint();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionDrawingAlgorithm.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionDrawingAlgorithm.java
new file mode 100644 (file)
index 0000000..6ed626e
--- /dev/null
@@ -0,0 +1,18 @@
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Exceptions of this class, or of a derived class,
+ * are thrown by the RNA drawing algorithms.
+ * 
+ * @author Raphael Champeimont
+ */
+public class ExceptionDrawingAlgorithm extends Exception {
+       private static final long serialVersionUID = -8705033963886770829L;
+
+       public ExceptionDrawingAlgorithm(String message) {
+               super(message);
+       }
+       
+       public ExceptionDrawingAlgorithm() {
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionEdgeEndpointAlreadyConnected.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionEdgeEndpointAlreadyConnected.java
new file mode 100644 (file)
index 0000000..8c0a98c
--- /dev/null
@@ -0,0 +1,21 @@
+package fr.orsay.lri.varna.exceptions;
+
+
+/**
+ * Thrown by an EdgeEndPoint when it is already connected and you try
+ * to connect it.
+ * 
+ * @author Raphael Champeimont
+ */
+public class ExceptionEdgeEndpointAlreadyConnected extends ExceptionInvalidRNATemplate {
+       private static final long serialVersionUID = 3978166870034913842L;
+
+       public ExceptionEdgeEndpointAlreadyConnected(String message) {
+               super(message);
+       }
+       
+       public ExceptionEdgeEndpointAlreadyConnected() {
+               super("Edge endpoint is already connected");
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionExportFailed.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionExportFailed.java
new file mode 100644 (file)
index 0000000..c04911b
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Exception for export problems
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionExportFailed extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String _errorMessage;
+       private String _path;
+
+       public ExceptionExportFailed(String errorMessage, String path) {
+               _errorMessage = errorMessage;
+               _path = path;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return "Export failed, File " + _path
+                               + " cannot be created or overwritten !\n";
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionFileFormatOrSyntax.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionFileFormatOrSyntax.java
new file mode 100644 (file)
index 0000000..9fff0f9
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Exception for any problem with the format or the syntax of a file loaded
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionFileFormatOrSyntax extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+       private String _path;
+       private String _errorMessage;
+
+       public ExceptionFileFormatOrSyntax(String errorMessage, String path) {
+               _path = path;
+               _errorMessage = errorMessage;
+       }
+
+       public ExceptionFileFormatOrSyntax(String path) {
+               _path = path;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return "Unknown format or syntax error in file ' " + _path
+                               + " '. \nLoading cancelled !";
+       }
+
+       public void setPath(String path) {
+               _path = path;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionInvalidRNATemplate.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionInvalidRNATemplate.java
new file mode 100644 (file)
index 0000000..be710bf
--- /dev/null
@@ -0,0 +1,18 @@
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * This exception is thrown when we discover that a template is invalid
+ * (it contains impossible connections between elements).
+ * 
+ * @author Raphael Champeimont
+ */
+public class ExceptionInvalidRNATemplate extends Exception {
+       private static final long serialVersionUID = 3866618355319087333L;
+       
+       public ExceptionInvalidRNATemplate(String message) {
+               super(message);
+       }
+       
+       public ExceptionInvalidRNATemplate() {
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionJPEGEncoding.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionJPEGEncoding.java
new file mode 100644 (file)
index 0000000..fd100f6
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Specific problems with JPEG encoding
+ */
+public class ExceptionJPEGEncoding extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String _errorMessage;
+
+       public ExceptionJPEGEncoding(String errorMessage) {
+               _errorMessage = errorMessage;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return "JPEG encoding failed!";
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionLoadingFailed.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionLoadingFailed.java
new file mode 100644 (file)
index 0000000..c18abe8
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Exception for file load problems
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionLoadingFailed extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String _errorMessage;
+       private String _path;
+
+       public ExceptionLoadingFailed(String errorMessage, String path) {
+               _errorMessage = errorMessage;
+               _path = path;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return "Loading failed!\n File '" + _path + "' cannot be read !";
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionModeleStyleBaseSyntaxError.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionModeleStyleBaseSyntaxError.java
new file mode 100644 (file)
index 0000000..7f2c775
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Exception for problems with the script about modele style base creation
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionModeleStyleBaseSyntaxError extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+       private String _details;
+
+       public ExceptionModeleStyleBaseSyntaxError(String details) {
+               _details = details;
+       }
+
+       public String getMessage() {
+               return _details;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionNAViewAlgorithm.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionNAViewAlgorithm.java
new file mode 100644 (file)
index 0000000..7ad306f
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+public class ExceptionNAViewAlgorithm extends ExceptionDrawingAlgorithm {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String _errorMessage;
+
+       public ExceptionNAViewAlgorithm(String errorMessage) {
+               _errorMessage = errorMessage;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return _errorMessage;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionNonEqualLength.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionNonEqualLength.java
new file mode 100644 (file)
index 0000000..bd9abab
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Exception for different rna lenghts
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionNonEqualLength extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String _errorMessage;
+
+       public ExceptionNonEqualLength(String errorMessage) {
+               _errorMessage = errorMessage;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return "Both RNA have not the same length, cannot resolve secondary structure.";
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionParameterError.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionParameterError.java
new file mode 100644 (file)
index 0000000..9c5b5b7
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Exception for parameter problems
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionParameterError extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String _errorMessage;
+       private String _details;
+
+       public ExceptionParameterError(String errorMessage, String details) {
+               _errorMessage = errorMessage;
+               _details = details;
+       }
+
+       public ExceptionParameterError(String details) {
+               _errorMessage = "";
+               _details = details;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return _details;
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionPermissionDenied.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionPermissionDenied.java
new file mode 100644 (file)
index 0000000..f6667f2
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Exception for permission denied problems due to security
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionPermissionDenied extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String _errorMessage;
+
+       public ExceptionPermissionDenied(String errorMessage) {
+               _errorMessage = errorMessage;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return "Permission denied for security reason !\n"
+                               + "Consider using the VARNA panel class in a signed context.\n";
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionUnmatchedClosingParentheses.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionUnmatchedClosingParentheses.java
new file mode 100644 (file)
index 0000000..195d275
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+import java.text.ParseException;
+
+/**
+ * Exception used when a rna has not the same number of opening and clothing
+ * parentheses
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionUnmatchedClosingParentheses extends ParseException {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       public ExceptionUnmatchedClosingParentheses(String s, int errorOffset) {
+               super(s, errorOffset);
+       }
+
+       public ExceptionUnmatchedClosingParentheses(int errorOffset) {
+               super("", errorOffset);
+       }
+
+       public String getMessage() {
+               return "Unbalanced parentheses expression, cannot resolve secondary structure.\n"
+                               + "Bad secondary structure (DBN format):Unmatched closing parentheses ')' at "
+                               + getErrorOffset();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionWritingForbidden.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionWritingForbidden.java
new file mode 100644 (file)
index 0000000..06f0b57
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Used when writing file problems append due to security policy
+ * 
+ * @author darty
+ * 
+ */
+public class ExceptionWritingForbidden extends Exception {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private String _errorMessage;
+
+       public ExceptionWritingForbidden(String errorMessage) {
+               _errorMessage = errorMessage;
+       }
+
+       public String getError() {
+               return _errorMessage;
+       }
+
+       public String getMessage() {
+               return "Writing is not allowed within current security policy.";
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionXMLGeneration.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionXMLGeneration.java
new file mode 100644 (file)
index 0000000..ac07e6f
--- /dev/null
@@ -0,0 +1,17 @@
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Thrown by XML-generating algorithms when they fail.
+ * 
+ * @author Raphael Champeimont
+ */
+public class ExceptionXMLGeneration extends Exception {
+       private static final long serialVersionUID = 8867910395701431387L;
+
+       public ExceptionXMLGeneration(String message) {
+               super(message);
+       }
+       
+       public ExceptionXMLGeneration() {
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/exceptions/ExceptionXmlLoading.java b/src2/fr/orsay/lri/varna/exceptions/ExceptionXmlLoading.java
new file mode 100644 (file)
index 0000000..1efaf50
--- /dev/null
@@ -0,0 +1,17 @@
+package fr.orsay.lri.varna.exceptions;
+
+/**
+ * Thrown by algorithms that load data from XML when they fail.
+ * 
+ * @author Raphael Champeimont
+ */
+public class ExceptionXmlLoading extends Exception {
+       private static final long serialVersionUID = -6267373620339074008L;
+
+       public ExceptionXmlLoading(String message) {
+               super(message);
+       }
+       
+       public ExceptionXmlLoading() {
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/exceptions/MappingException.java b/src2/fr/orsay/lri/varna/exceptions/MappingException.java
new file mode 100644 (file)
index 0000000..bc31021
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.exceptions;
+
+public class MappingException extends Exception {
+       private static final long serialVersionUID = 1L;
+
+       public static final int MULTIPLE_PARTNERS_DEFINITION_ATTEMPT = 1;
+       public static final int BAD_ALIGNMENT_INPUT = 2;
+       public static final int CUSTOM_MESSAGE = 3;
+
+       private String _errorMessage;
+       private int _type;
+
+       public MappingException(String errorMessage) {
+               _errorMessage = errorMessage;
+               _type = CUSTOM_MESSAGE;
+       }
+
+       public MappingException(int type) {
+               _type = type;
+       }
+
+       public String getMessage() {
+               switch (_type) {
+               case MULTIPLE_PARTNERS_DEFINITION_ATTEMPT:
+                       return "Mapping error: Attempt to define multiple partners for a base-pair";
+               case BAD_ALIGNMENT_INPUT:
+                       return "Mapping error: Bad input alignment";
+
+               case CUSTOM_MESSAGE:
+                       return _errorMessage;
+               default:
+                       return "Mapping error: Type is unknown.";
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/factories/RNAAlignment.java b/src2/fr/orsay/lri/varna/factories/RNAAlignment.java
new file mode 100644 (file)
index 0000000..0cbf17c
--- /dev/null
@@ -0,0 +1,106 @@
+package fr.orsay.lri.varna.factories;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Hashtable;
+import java.util.Stack;
+
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+/**
+ * BH SwingJS -- must explicitly check for array out of bounds
+ */
+public class RNAAlignment {
+   private ArrayList<String> _lst = new ArrayList<String> (); 
+   private Hashtable<String, Integer> _index = new Hashtable<String, Integer> ();
+   private Hashtable<String, String> _accession = new Hashtable<String, String> ();
+   private String _secStr = "";
+   
+   public void addSequence(String id, String s)
+   {
+          if (!_index.containsKey(id))
+          {
+                  _index.put(id,_lst.size());
+                  _lst.add(s);
+          }
+          _lst.set(_index.get(id),s);
+   }
+   
+   public void setSecStr(String s)
+   {
+          _secStr = s;
+   }
+   
+  public void setAccession(String id, String AC)
+  {
+         _accession.put(id,AC);
+  }
+   
+   public ArrayList<RNA> getRNAs() throws ExceptionUnmatchedClosingParentheses
+   {
+          ArrayList<RNA> result = new ArrayList<RNA>(); 
+          int[] str = RNAFactory.parseSecStr(_secStr);
+          ArrayList<String> ids = new ArrayList<String>(_index.keySet());
+          Collections.sort(ids,new Comparator<String>(){
+               public int compare(String o1, String o2) {
+                       return o1.compareToIgnoreCase(o2);
+               }});
+          for (String id: ids )
+          {
+                  int n = _index.get(id);
+                  String seq = _lst.get(n);
+                  if (seq.length() != str.length)
+                          throw new ArrayIndexOutOfBoundsException(); // BH SwingJS -- must explicitly check for array out of bounds
+                  String nseq ="";
+                  String nstr ="";
+                  for(int i=0;i<seq.length();i++)
+                  {
+                          char c = seq.charAt(i);
+                          int j = str[i];
+                          
+                          if (!(c=='.' || c==':' || c=='-'))
+                          {
+                                  nseq += c;
+                                  if (j==-1)
+                                  {
+                                          nstr += '.';
+                                  }
+                                  else
+                                  {
+                                          int cp = seq.charAt(j);
+                                          if (cp=='.' || cp==':' || cp=='-')
+                                          {
+                                                  nstr += '.';                                            
+                                          }
+                                          else
+                                          {
+                                                  nstr += _secStr.charAt(i);
+                                          }
+                                  }
+                          }
+                  }
+                  RNA r = new RNA();
+                  try {
+                       r.setRNA(nseq, nstr);
+                       r.setName(id);
+                       if (_accession.containsKey(id))
+                       {
+                               r.setID(_accession.get(id));
+                       }
+                       else
+                       {
+                               r.setID(id);
+                       }
+                       result.add(r);
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+          }
+          return result;
+   }
+}
diff --git a/src2/fr/orsay/lri/varna/factories/RNAFactory.java b/src2/fr/orsay/lri/varna/factories/RNAFactory.java
new file mode 100644 (file)
index 0000000..c514f31
--- /dev/null
@@ -0,0 +1,805 @@
+package fr.orsay.lri.varna.factories;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.EmptyStackException;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Stack;
+import java.util.Vector;
+
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.xml.sax.InputSource;
+
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBackboneElement;
+import fr.orsay.lri.varna.models.rna.ModeleBackboneElement.BackboneType;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.utils.RNAMLParser;
+
+/**
+ * BH JAVA FIX: mostly here we are just removing a lot of unnecessary stack traces when doing a drag-drop of a file
+ * BH JAVA FIX: making sure the file reader is closed properly
+ *  
+ */
+public class RNAFactory
+{
+
+  public enum RNAFileType
+  {
+    FILE_TYPE_STOCKHOLM, FILE_TYPE_TCOFFEE, FILE_TYPE_BPSEQ, FILE_TYPE_CT, FILE_TYPE_DBN, FILE_TYPE_RNAML, FILE_TYPE_UNKNOWN
+  }
+
+private static boolean isQuiet;
+
+  public static ArrayList<RNA> loadSecStrRNAML(Reader r)
+      throws ExceptionPermissionDenied, ExceptionLoadingFailed,
+      ExceptionFileFormatOrSyntax
+  {
+
+    ArrayList<RNA> result = new ArrayList<RNA>();
+    try
+    {
+      // System.setProperty("javax.xml.parsers.SAXParserFactory",
+      // "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
+      SAXParserFactory saxFact = javax.xml.parsers.SAXParserFactory
+          .newInstance();
+      saxFact.setValidating(false);
+      saxFact.setXIncludeAware(false);
+      saxFact.setNamespaceAware(false);
+      SAXParser sp = saxFact.newSAXParser();
+      RNAMLParser RNAMLData = new RNAMLParser();
+      sp.parse(new InputSource(r), RNAMLData);
+
+      /*
+       * XMLReader xr = XMLReaderFactory.createXMLReader(); RNAMLParser
+       * RNAMLData = new RNAMLParser(); xr.setContentHandler(RNAMLData);
+       * xr.setErrorHandler(RNAMLData); xr.setEntityResolver(RNAMLData);
+       * xr.parse(new InputSource(r));
+       */
+      for (RNAMLParser.RNATmp rnaTmp : RNAMLData.getMolecules())
+      {
+        RNA current = new RNA();
+        // Retrieving parsed data
+        List<String> seq = rnaTmp.getSequence();
+        // Creating empty structure of suitable size
+        int[] str = new int[seq.size()];
+        for (int i = 0; i < str.length; i++)
+        {
+          str[i] = -1;
+        }
+        current.setRNA(seq, str);
+        Vector<RNAMLParser.BPTemp> allbpsTmp = rnaTmp.getStructure();
+        ArrayList<ModeleBP> allbps = new ArrayList<ModeleBP>();
+        for (int i = 0; i < allbpsTmp.size(); i++)
+        {
+          RNAMLParser.BPTemp bp = allbpsTmp.get(i);
+          // System.err.println(bp);
+          int bp5 = bp.pos5;
+          int bp3 = bp.pos3;
+          ModeleBase mb = current.getBaseAt(bp5);
+          ModeleBase part = current.getBaseAt(bp3);
+          ModeleBP newStyle = bp.createBPStyle(mb, part);
+          allbps.add(newStyle);
+        }
+
+        current.applyBPs(allbps);
+        result.add(current);
+      }
+
+    }
+    catch (IOException ioe)
+    {
+      throw new ExceptionLoadingFailed(
+          "Couldn't load file due to I/O or security policy issues.", "");
+    }
+    catch (Exception ge)
+    {
+       if (!isQuiet) // BH
+      ge.printStackTrace();
+    }
+    return result;
+  }
+
+  public static int[] parseSecStr(String _secStr)
+      throws ExceptionUnmatchedClosingParentheses
+  {
+    Hashtable<Character, Stack<Integer>> stacks = new Hashtable<Character, Stack<Integer>>();
+    int[] result = new int[_secStr.length()];
+    int i = 0;
+    try
+    {
+      for (i = 0; i < _secStr.length(); i++)
+      {
+        result[i] = -1;
+        char c = _secStr.charAt(i);
+        char c2 = Character.toUpperCase(c);
+        if (!stacks.containsKey(c2))
+        {
+          stacks.put(c2, new Stack<Integer>());
+        }
+        switch (c)
+        {
+        case '<':
+        case '{':
+        case '(':
+        case '[':
+          stacks.get(c).push(i);
+          break;
+        case '>':
+        {
+          int j = stacks.get('<').pop();
+          result[i] = j;
+          result[j] = i;
+          break;
+        }
+        case '}':
+        {
+          int j = stacks.get('{').pop();
+          result[i] = j;
+          result[j] = i;
+          break;
+        }
+        case ')':
+        {
+          int j = stacks.get('(').pop();
+          result[i] = j;
+          result[j] = i;
+          break;
+        }
+        case ']':
+        {
+          int j = stacks.get('[').pop();
+          result[i] = j;
+          result[j] = i;
+          break;
+        }
+        case '.':
+          break;
+        default:
+        {
+          if (Character.isLetter(c) && Character.isUpperCase(c))
+          {
+            stacks.get(c).push(i);
+          }
+          else if (Character.isLetter(c) && Character.isLowerCase(c))
+          {
+            int j = stacks.get(Character.toUpperCase(c)).pop();
+            result[i] = j;
+            result[j] = i;
+          }
+        }
+        }
+      }
+    }
+    catch (EmptyStackException e)
+    {
+      throw new ExceptionUnmatchedClosingParentheses(i);
+    }
+    return result;
+  }
+
+  public static ArrayList<RNA> loadSecStrDBN(Reader r)
+      throws ExceptionLoadingFailed, ExceptionPermissionDenied,
+      ExceptionUnmatchedClosingParentheses, ExceptionFileFormatOrSyntax
+  {
+    boolean loadOk = false;
+    ArrayList<RNA> result = new ArrayList<RNA>();
+    RNA current = new RNA();
+    try
+    {
+      BufferedReader fr = new BufferedReader(r);
+      String line = fr.readLine();
+      String title = "";
+      String seqTmp = "";
+      String strTmp = "";
+      while ((line != null) && (strTmp.equals("")))
+      {
+        line = line.trim();
+        if (!line.startsWith(">"))
+        {
+          if (seqTmp.equals(""))
+          {
+            seqTmp = line;
+          }
+          else
+          {
+            strTmp = line;
+          }
+        }
+        else
+        {
+          title = line.substring(1).trim();
+        }
+        line = fr.readLine();
+      }
+      if (strTmp.length() != 0)
+      {
+        current.setRNA(seqTmp, strTmp);
+        current.setName(title);
+        loadOk = true;
+      }
+    }
+    catch (IOException e)
+    {
+      throw new ExceptionLoadingFailed(e.getMessage(), "");
+    }
+    if (loadOk)
+    {
+      result.add(current);
+    }
+    return result;
+  }
+
+  public static ArrayList<RNA> loadSecStr(File f)
+             throws ExceptionFileFormatOrSyntax
+         {
+           try {
+                       return loadSecStr(new BufferedReader(new FileReader(f)), RNAFileType.FILE_TYPE_UNKNOWN);
+               } catch (FileNotFoundException e) {
+                       throw new ExceptionFileFormatOrSyntax(f.toString());
+               }
+         }
+
+  public static ArrayList<RNA> loadSecStr(Reader r)
+      throws ExceptionFileFormatOrSyntax
+  {
+    return loadSecStr(new BufferedReader(r), RNAFileType.FILE_TYPE_UNKNOWN);
+  }
+
+       public static ArrayList<RNA> loadSecStr(BufferedReader r, RNAFileType fileType) throws ExceptionFileFormatOrSyntax {
+               try {
+                       switch (fileType) {
+                       case FILE_TYPE_DBN: {
+                               try {
+                                       ArrayList<RNA> result = loadSecStrDBN(r);
+                                       if (result.size() != 0)
+                                               return result;
+                               } catch (Exception e) {
+                               }
+                       }
+                               break;
+                       case FILE_TYPE_CT: {
+                               try {
+                                       ArrayList<RNA> result = loadSecStrCT(r);
+                                       if (result.size() != 0)
+                                               return result;
+                               } catch (Exception e) {
+                                       if (!isQuiet) // BH
+                                               e.printStackTrace();
+                               }
+                       }
+                               break;
+                       case FILE_TYPE_BPSEQ: {
+                               try {
+                                       ArrayList<RNA> result = loadSecStrBPSEQ(r);
+                                       if (result.size() != 0)
+                                               return result;
+                               } catch (Exception e) {
+                                       if (!isQuiet) // BH
+                                               e.printStackTrace();
+                               }
+                       }
+                               break;
+                       case FILE_TYPE_TCOFFEE: {
+                               try {
+                                       ArrayList<RNA> result = loadSecStrTCoffee(r);
+                                       if (result.size() != 0)
+                                               return result;
+                               } catch (Exception e) {
+                                       if (!isQuiet) // BH
+                                               e.printStackTrace();
+                               }
+                       }
+                               break;
+                       case FILE_TYPE_STOCKHOLM: {
+                               try {
+                                       ArrayList<RNA> result = loadSecStrStockholm(r);
+                                       if (result.size() != 0)
+                                               return result;
+                               } catch (Exception e) {
+                                       if (!isQuiet) // BH
+                                               e.printStackTrace();
+                               }
+                       }
+                               break;
+                       case FILE_TYPE_RNAML: {
+                               try {
+                                       ArrayList<RNA> result = loadSecStrRNAML(r);
+                                       if (result.size() != 0)
+                                               return result;
+                               } catch (Exception e) {
+                                       if (!isQuiet) // BH
+                                               e.printStackTrace();
+                               }
+                       }
+                               break;
+
+                       case FILE_TYPE_UNKNOWN: {
+                               try {
+                                       r.mark(1000000);
+                                       RNAFactory.RNAFileType[] types = RNAFactory.RNAFileType.values();
+                                       isQuiet = true; // BH to not report errors when
+                                                                       // drag-dropping
+                                       ArrayList<RNA> result = null;
+                                       RNAFactory.RNAFileType t = null;
+                                       for (int i = 0; i < types.length; i++) {
+                                               r.reset();
+                                               t = types[i];
+                                               if (t != RNAFactory.RNAFileType.FILE_TYPE_UNKNOWN) {
+                                                       try {
+                                                               result = loadSecStr(r, t);
+                                                               if (result.size() != 0) {
+                                                                       break;
+                                                               }
+                                                       } catch (Exception e) {
+                                                               if (!isQuiet) // BH
+                                                                       System.err.println(e.toString());
+                                                       }
+                                               }
+                                       }
+                                       System.out.println(t); // BH
+                                       isQuiet = false; // BH
+                                       return result;
+                               } catch (IOException e2) {
+                                       e2.printStackTrace();
+                               }
+                       }
+                       }
+                       throw new ExceptionFileFormatOrSyntax("Couldn't parse this file as " + fileType + ".");
+               } finally { // BH !!
+                       try {
+                               if (!isQuiet)
+                                       r.close();
+                       } catch (IOException e) {
+                               // ignore
+                       }
+               }
+       }
+
+  public static RNAFileType guessFileTypeFromExtension(String path)
+  {
+    if (path.toLowerCase().endsWith("ml"))
+    {
+      return RNAFileType.FILE_TYPE_RNAML;
+    }
+    else if (path.toLowerCase().endsWith("dbn")
+        || path.toLowerCase().endsWith("faa"))
+    {
+      return RNAFileType.FILE_TYPE_DBN;
+    }
+    else if (path.toLowerCase().endsWith("ct"))
+    {
+      return RNAFileType.FILE_TYPE_CT;
+    }
+    else if (path.toLowerCase().endsWith("bpseq"))
+    {
+      return RNAFileType.FILE_TYPE_BPSEQ;
+    }
+    else if (path.toLowerCase().endsWith("rfold"))
+    {
+      return RNAFileType.FILE_TYPE_TCOFFEE;
+    }
+    else if (path.toLowerCase().endsWith("stockholm")
+        || path.toLowerCase().endsWith("stk"))
+    {
+      return RNAFileType.FILE_TYPE_STOCKHOLM;
+    }
+
+    return RNAFileType.FILE_TYPE_UNKNOWN;
+
+  }
+
+  public static ArrayList<RNA> loadSecStr(String path)
+      throws ExceptionExportFailed, ExceptionPermissionDenied,
+      ExceptionLoadingFailed, ExceptionFileFormatOrSyntax,
+      ExceptionUnmatchedClosingParentheses, FileNotFoundException
+  {
+    FileReader fr = null;
+    try
+    {
+      fr = new FileReader(path);
+      RNAFileType type = guessFileTypeFromExtension(path);
+      return loadSecStr(new BufferedReader(fr), type);
+    }
+    catch (ExceptionFileFormatOrSyntax e)
+    {
+      if (fr != null)
+        try
+        {
+          fr.close();
+        }
+        catch (IOException e2)
+        {
+        }
+      e.setPath(path);
+      throw e;
+    }
+  }
+
+  public static ArrayList<RNA> loadSecStrStockholm(BufferedReader r)
+      throws IOException, ExceptionUnmatchedClosingParentheses
+  {
+    RNAAlignment a = StockholmIO.readAlignement(r);
+    return a.getRNAs();
+  }
+
+  public static ArrayList<RNA> loadSecStrBPSEQ(Reader r)
+      throws ExceptionPermissionDenied, ExceptionLoadingFailed,
+      ExceptionFileFormatOrSyntax
+  {
+    boolean loadOk = false;
+    ArrayList<RNA> result = new ArrayList<RNA>();
+    RNA current = new RNA();
+    try
+    {
+      BufferedReader fr = new BufferedReader(r);
+      String line = fr.readLine();
+      ArrayList<String> seqTmp = new ArrayList<String>();
+      Hashtable<Integer, Vector<Integer>> strTmp = new Hashtable<Integer, Vector<Integer>>();
+
+      int bpFrom;
+      String base;
+      int bpTo;
+      int minIndex = -1;
+      boolean noWarningYet = true;
+      String title = "";
+      String id = "";
+      String filenameStr = "Filename:";
+      String organismStr = "Organism:";
+      String ANStr = "Accession Number:";
+      while (line != null)
+      {
+        line = line.trim();
+        String[] tokens = line.split("\\s+");
+        ArrayList<Integer> numbers  = new ArrayList<Integer>(); 
+        Hashtable<Integer,Integer> numberToIndex  = new Hashtable<Integer,Integer>(); 
+        if ((tokens.length >= 3) && !tokens[0].contains("#")
+            && !line.startsWith("Organism:") && !line.startsWith("Citation")
+            && !line.startsWith("Filename:")
+            && !line.startsWith("Accession Number:"))
+        {
+          base = tokens[1];
+          seqTmp.add(base);
+          bpFrom = (Integer.parseInt(tokens[0]));
+          numbers.add(bpFrom);
+          if (minIndex < 0)
+            minIndex = bpFrom;
+
+          if (seqTmp.size() < (bpFrom - minIndex + 1))
+          {
+            if (noWarningYet)
+            {
+              noWarningYet = false;
+              /*
+               * warningEmition( "Discontinuity detected between nucleotides " +
+               * (seqTmp.size()) + " and " + (bpFrom + 1) +
+               * "!\nFilling in missing portions with unpaired unknown 'X' nucleotides ..."
+               * );
+               */
+            }
+            while (seqTmp.size() < (bpFrom - minIndex + 1))
+            {
+              // System.err.println(".");
+              seqTmp.add("X");
+            }
+          }
+          for (int i = 2; i < tokens.length; i++)
+          {
+            bpTo = (Integer.parseInt(tokens[i]));
+            if ((bpTo != 0) || (i != tokens.length - 1))
+            {
+              if (!strTmp.containsKey(bpFrom))
+                strTmp.put(bpFrom, new Vector<Integer>());
+              strTmp.get(bpFrom).add(bpTo);
+            }
+          }
+        }
+        else if (tokens[0].startsWith("#"))
+        {
+          int occur = line.indexOf("#");
+          String tmp = line.substring(occur + 1);
+          title += tmp.trim() + " ";
+        }
+        else if (tokens[0].startsWith(filenameStr))
+        {
+          int occur = line.indexOf(filenameStr);
+          String tmp = line.substring(occur + filenameStr.length());
+          title += tmp.trim();
+        }
+        else if (tokens[0].startsWith(organismStr))
+        {
+          int occur = line.indexOf(organismStr);
+          String tmp = line.substring(occur + organismStr.length());
+          if (title.length() != 0)
+          {
+            title = "/" + title;
+          }
+          title = tmp.trim() + title;
+        }
+        else if (line.contains(ANStr))
+        {
+          int occur = line.indexOf(ANStr);
+          String tmp = line.substring(occur + ANStr.length());
+          id = tmp.trim();
+        }
+        line = fr.readLine();
+      }
+      if (strTmp.size() != 0)
+      {
+        ArrayList<String> seq = seqTmp;
+        int[] str = new int[seq.size()];
+        for (int i = 0; i < seq.size(); i++)
+        {
+          str[i] = -1;
+        }
+        current.setRNA(seq, str, minIndex);
+        ArrayList<ModeleBP> allbps = new ArrayList<ModeleBP>();
+        for (int i : strTmp.keySet())
+        {
+          for (int j : strTmp.get(i))
+          {
+                 if (i<=j)
+                 {
+                   ModeleBase mb = current.getBaseAt(i - minIndex);
+                   ModeleBase part = current.getBaseAt(j - minIndex);
+                   ModeleBP newStyle = new ModeleBP(mb, part);
+                   allbps.add(newStyle);
+                 }
+          }
+        }
+        current.applyBPs(allbps);
+        current.setName(title);
+        current.setID(id);
+        loadOk = true;
+      }
+    }
+    catch (NumberFormatException e)
+    {
+       if (!isQuiet) // BH SwingJS
+      e.printStackTrace();
+    }
+    catch (IOException e)
+    {
+      // TODO Auto-generated catch block
+      e.printStackTrace();
+    }
+    catch (Exception e)
+    {
+      throw new ExceptionLoadingFailed(e.getMessage(), "");
+    }
+    if (loadOk)
+      result.add(current);
+    return result;
+  }
+
+  public static ArrayList<RNA> loadSecStrTCoffee(Reader r)
+      throws ExceptionPermissionDenied, ExceptionLoadingFailed,
+      ExceptionFileFormatOrSyntax
+  {
+    boolean loadOk = false;
+    ArrayList<RNA> result = new ArrayList<RNA>();
+    try
+    {
+      BufferedReader fr = new BufferedReader(r);
+      String line = fr.readLine();
+      ArrayList<String> seqs = new ArrayList<String>();
+      ArrayList<String> ids = new ArrayList<String>();
+      int numSeqs = -1;
+      int currSeq = -1;
+      RNA current = null;
+      while (line != null)
+      {
+        if (!line.startsWith("!"))
+        {
+          String[] tokens = line.split("\\s+");
+          // This may indicate new secondary structure
+          if (line.startsWith("#"))
+          {
+            currSeq = Integer.parseInt(tokens[0].substring(1));
+            int currSeq2 = Integer.parseInt(tokens[1]);
+            // For TCoffee, a sec str is a matching between a seq and itself
+            // => Disregard any alignment by filtering on the equality of sequence indices.
+            if (currSeq == currSeq2)
+            {
+              current = new RNA();
+              current.setName(ids.get(currSeq - 1));
+              current.setSequence(seqs.get(currSeq - 1));
+              result.add(current);
+            }
+            else
+            {
+              current = null;
+            }
+          }
+          // Beginning of the file... 
+          else if (current == null)
+          {
+            //... either this is the number of sequences...
+            if (numSeqs < 0)
+            {
+              numSeqs = Integer.parseInt(tokens[0]);
+            }
+            //... or this is a sequence definition...
+            else
+            {
+              String id = tokens[0];
+              String seq = tokens[2];
+              seqs.add(seq);
+              ids.add(id);
+            }
+          }
+          //Otherwise, this is a base-pair definition, related to the currently selected sequence
+          else if (tokens.length == 3)
+          {
+            int from = Integer.parseInt(tokens[0]) - 1;
+            int to = Integer.parseInt(tokens[1]) - 1;
+            current.addBP(from, to);
+          }
+        }
+        line = fr.readLine();
+      }
+      loadOk = true;
+    }
+    catch (NumberFormatException e)
+    {
+       if (!isQuiet) // BH SwingJS
+      e.printStackTrace();
+    }
+    catch (IOException e)
+    {
+       if (!isQuiet) // BH SwingJS
+               e.printStackTrace();
+    }
+    if (!loadOk)
+    {
+      throw new ExceptionLoadingFailed("Parse Error", "");
+    }
+    return result;
+  }
+
+  public static ArrayList<RNA> loadSecStrCT(Reader r)
+      throws ExceptionPermissionDenied, ExceptionLoadingFailed,
+      ExceptionFileFormatOrSyntax
+  {
+    boolean loadOk = false;
+    ArrayList<RNA> result = new ArrayList<RNA>();
+    RNA current = new RNA();
+    try
+    {
+      BufferedReader fr = new BufferedReader(r);
+      String line = fr.readLine();
+      ArrayList<String> seq = new ArrayList<String>();
+      ArrayList<String> lbls = new ArrayList<String>();
+      Vector<Integer> strTmp = new Vector<Integer>();
+      Vector<Integer> newStrands = new Vector<Integer>();
+      int bpFrom;
+      String base;
+      String lbl;
+      int bpTo;
+      boolean noWarningYet = true;
+      int minIndex = -1;
+      String title = "";
+      while (line != null)
+      {
+        line = line.trim();
+        String[] tokens = line.split("\\s+");
+        if (tokens.length >= 6)
+        {
+          try
+          {
+            bpFrom = (Integer.parseInt(tokens[0]));
+            bpTo = (Integer.parseInt(tokens[4]));
+            if (minIndex == -1)
+              minIndex = bpFrom;
+            bpFrom -= minIndex;
+            if (bpTo != 0)
+              bpTo -= minIndex;
+            else
+              bpTo = -1;
+            base = tokens[1];
+            lbl = tokens[5];
+            int before = Integer.parseInt(tokens[2]);
+            int after = Integer.parseInt(tokens[3]);
+            
+            if (before==0 && !seq.isEmpty())
+            {
+               newStrands.add(strTmp.size()-1);
+            }
+            if (bpFrom != seq.size())
+            {
+              if (noWarningYet)
+              {
+                noWarningYet = false;
+                /*
+                 * warningEmition( "Discontinuity detected between nucleotides "
+                 * + (seq.size()) + " and " + (bpFrom + 1) +
+                 * "!\nFilling in missing portions with unpaired unknown 'X' nucleotides ..."
+                 * );
+                 */
+              }
+              while (bpFrom > seq.size())
+              {
+                seq.add("X");
+                strTmp.add(-1);
+                lbls.add("");
+              }
+            }
+            seq.add(base);
+            strTmp.add(bpTo);
+            lbls.add(lbl);
+          }
+          catch (NumberFormatException e)
+          {
+                 if (strTmp.size()!=0)
+                         e.printStackTrace();
+          }
+        }
+        if ((line.contains("ENERGY = ")) || line.contains("dG = "))
+        {
+          String[] ntokens = line.split("\\s+");
+          if (ntokens.length >= 4)
+          {
+            String energy = ntokens[3];
+            for (int i = 4; i < ntokens.length; i++)
+            {
+              title += ntokens[i] + " ";
+            }
+            title += "(E=" + energy + " kcal/mol)";
+          }
+        }
+        line = fr.readLine();
+      }
+      if (strTmp.size() != 0)
+      {
+        int[] str = new int[strTmp.size()];
+        for (int i = 0; i < strTmp.size(); i++)
+        {
+          str[i] = strTmp.elementAt(i).intValue();
+        }
+        current.setRNA(seq, str, minIndex);
+        current.setName(title);
+        for (int i = 0; i < current.getSize(); i++)
+        {
+          current.getBaseAt(i).setLabel(lbls.get(i));
+        }
+        for (int i : newStrands)
+        {
+               current.getBackbone().addElement(new ModeleBackboneElement(i,BackboneType.DISCONTINUOUS_TYPE));
+        }
+
+        
+        loadOk = true;
+      }
+    }
+    catch (IOException e)
+    {
+       e.printStackTrace();
+      throw new ExceptionLoadingFailed(e.getMessage(), "");
+    }
+    catch (NumberFormatException e)
+    {
+       if (!isQuiet) // BH SwingJS
+       e.printStackTrace();
+      throw new ExceptionFileFormatOrSyntax(e.getMessage(), "");
+    }
+    if (loadOk)
+      result.add(current);
+    return result;
+  }
+
+}
diff --git a/src2/fr/orsay/lri/varna/factories/StockholmIO.java b/src2/fr/orsay/lri/varna/factories/StockholmIO.java
new file mode 100644 (file)
index 0000000..a237251
--- /dev/null
@@ -0,0 +1,91 @@
+package fr.orsay.lri.varna.factories;
+
+import java.io.BufferedReader;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+
+public class StockholmIO {
+       public static RNAAlignment readAlignementFromFile(String path) throws IOException
+       {
+               return StockholmIO.readAlignement(new BufferedReader(new FileReader(path)));
+       }
+       public static RNAAlignment readAlignementFromURL(String url) throws UnsupportedEncodingException, IOException
+       {
+               URL urlAb = new URL(url);
+               URLConnection urlConn = urlAb.openConnection(); 
+               urlConn.setUseCaches(false);
+               Reader r = new InputStreamReader(urlConn.getInputStream(),"UTF-8");
+               return readAlignement(new BufferedReader(r));
+       }
+
+       
+       /*public static Alignment readAlignement(Reader r) throws IOException
+       {
+               return readAlignement(new BufferedReader(r));
+       }*/
+       
+       public static RNAAlignment readAlignement(BufferedReader r) throws IOException
+       {
+               LinkedHashMap<String,StringBuffer> rawSeqs = new LinkedHashMap<String,StringBuffer>();
+               RNAAlignment result = new RNAAlignment();
+               String line = r.readLine(); 
+               String str = "";
+
+               while(line!=null)
+               {
+                       if (!line.startsWith("#"))
+                       {
+                               String[] data = line.split("\\s+");
+                               if (data.length>1)
+                               {
+                                       String seqName = data[0].trim();
+                                       String seq = data[1].trim();
+                                       if (!rawSeqs.containsKey(seqName))
+                                       {
+                                               rawSeqs.put(seqName,new StringBuffer());
+                                       }
+                                       StringBuffer val =  rawSeqs.get(seqName);
+                                       val.append(seq);
+                               }
+                               
+                       }
+                       else if (line.startsWith("#"))
+                       {
+                               String[] data = line.split("\\s+");
+                               if (line.startsWith("#=GC SS_cons"))
+                               {
+                                       str += data[2].trim();  
+                               }
+                               else if (line.startsWith("#=GS"))
+                               {
+                                       if (data[2].trim().equals("AC"))
+                                       {
+                                         result.setAccession(data[1].trim(),data[3].trim());
+                                         
+                                       }
+                               }
+                       }
+                               
+                       line = r.readLine(); 
+               }
+               result.setSecStr(str);
+               for(Map.Entry<String,StringBuffer> entry : rawSeqs.entrySet())
+               {
+                       String s = entry.getValue().toString();
+                       result.addSequence(entry.getKey(), s);
+               }
+               return result;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/interfaces/InterfaceParameterLoader.java b/src2/fr/orsay/lri/varna/interfaces/InterfaceParameterLoader.java
new file mode 100644 (file)
index 0000000..954f145
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.interfaces;
+
+public interface InterfaceParameterLoader {
+       public String getParameterValue(String key, String def);
+}
diff --git a/src2/fr/orsay/lri/varna/interfaces/InterfaceParseExport.java b/src2/fr/orsay/lri/varna/interfaces/InterfaceParseExport.java
new file mode 100644 (file)
index 0000000..417c5df
--- /dev/null
@@ -0,0 +1,8 @@
+package fr.orsay.lri.varna.interfaces;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+public interface InterfaceParseExport {
+       public void parse(String s, VARNAPanel vp);
+       public String export();
+}
diff --git a/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNABasesListener.java b/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNABasesListener.java
new file mode 100644 (file)
index 0000000..d2cb290
--- /dev/null
@@ -0,0 +1,19 @@
+package fr.orsay.lri.varna.interfaces;
+
+import java.awt.event.MouseEvent;
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Set;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+
+public interface InterfaceVARNABasesListener {
+
+       /**
+        * Reacts to click over base
+        * @param mb The base which has just been clicked
+        */
+       public void onBaseClicked(ModeleBase mb, MouseEvent e);
+}
diff --git a/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNAListener.java b/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNAListener.java
new file mode 100644 (file)
index 0000000..aafd94d
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.interfaces;
+
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+/**
+ * Observable design pattern
+ * 
+ * @author darty
+ * 
+ */
+public abstract interface InterfaceVARNAListener {
+       public abstract void onWarningEmitted(String s);
+       public abstract void onStructureRedrawn();
+       public abstract void onUINewStructure(VARNAConfig v, RNA r);
+       public abstract void onZoomLevelChanged();
+       public abstract void onTranslationChanged();
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNAObservable.java b/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNAObservable.java
new file mode 100644 (file)
index 0000000..35b5f9d
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.interfaces;
+
+/**
+ * Observable design pattern
+ * 
+ * @author darty
+ * 
+ */
+public abstract class InterfaceVARNAObservable {
+       public abstract void addVARNAListener(InterfaceVARNAListener rl);
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNARNAListener.java b/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNARNAListener.java
new file mode 100644 (file)
index 0000000..aeeaa5b
--- /dev/null
@@ -0,0 +1,32 @@
+package fr.orsay.lri.varna.interfaces;
+
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Set;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+public interface InterfaceVARNARNAListener {
+       /**
+        * Reacts to changes being made at the sequence level. 
+        * @param index The sequence index where a change of base content is observed
+        * @param oldseq Previous base content   
+        * @param newseq New base content
+        */
+       public void onSequenceModified(int index, String oldseq, String newseq);
+       
+       /**
+        * Reacts to modification of the structure (Base-pair addition/removal).
+        * @param current Current list of base-pairs (can be also accessed within the current RNA object).
+        * @param addedBasePairs Newly created base-pairs
+        * @param removedBasePairs Newly removed base-pairs
+        */
+       public void onStructureModified(Set<ModeleBP> current, Set<ModeleBP> addedBasePairs, Set<ModeleBP> removedBasePairs);
+       
+       /**
+        * Reacts to displacement of 
+        * @param previousPositions
+        */
+       public void onRNALayoutChanged(Hashtable<Integer,Point2D.Double> previousPositions);
+}
diff --git a/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNASelectionListener.java b/src2/fr/orsay/lri/varna/interfaces/InterfaceVARNASelectionListener.java
new file mode 100644 (file)
index 0000000..20bf2eb
--- /dev/null
@@ -0,0 +1,21 @@
+package fr.orsay.lri.varna.interfaces;
+
+import fr.orsay.lri.varna.models.BaseList;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+
+public interface InterfaceVARNASelectionListener {
+       /**
+        * Specifies an action that should be performed upon changing the hovered base.
+        * @param oldbase Previously hovered base (possibly null).
+        * @param newBase Newly hovered base (possibly null).
+        */
+       public void onHoverChanged(ModeleBase oldbase, ModeleBase newBase);
+       
+       /**
+        * Specifies the action to be performed upon changing the selection.
+        * @param selection The list of bases currently selected 
+        * @param addedBases The list of bases added since previous selection event
+        * @param removedBases The list of bases removed since previous selection event
+        */
+       public void onSelectionChanged(BaseList selection, BaseList addedBases, BaseList removedBases);
+}
diff --git a/src2/fr/orsay/lri/varna/models/BaseList.java b/src2/fr/orsay/lri/varna/models/BaseList.java
new file mode 100644 (file)
index 0000000..01ac0b1
--- /dev/null
@@ -0,0 +1,200 @@
+package fr.orsay.lri.varna.models;
+
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+
+public class BaseList {
+       private HashSet<ModeleBase> _bases = new HashSet<ModeleBase>(); 
+       private String _caption;
+
+       public BaseList( BaseList b)
+       {
+               _caption = b._caption;
+               _bases = new HashSet<ModeleBase>(b._bases);
+       }
+
+       
+       public BaseList( String caption)
+       {
+               _caption = caption;
+       }
+       
+       
+       public BaseList( String caption, ModeleBase mb)
+       {
+               this(caption);
+               addBase(mb);
+       }
+
+       public boolean contains(ModeleBase mb)
+       {
+               return _bases.contains(mb);
+       }
+
+       
+       public String getCaption()
+       {
+               return _caption;
+       }
+       
+       public void addBase(ModeleBase b)
+       {
+               _bases.add(b);
+       }
+
+       public void removeBase(ModeleBase b)
+       {
+               _bases.remove(b);
+       }
+
+       
+       public void addBases(Collection<? extends ModeleBase> mbs)
+       {
+               _bases.addAll(mbs);
+       }
+
+       public ArrayList<ModeleBase> getBases()
+       {
+               return new ArrayList<ModeleBase>(_bases);
+       }
+
+       public void clear()
+       {
+               _bases.clear();
+       }
+
+       public static Color getAverageColor(ArrayList<Color> cols)
+       {
+               int r=0,g=0,b=0;
+               for (Color c : cols)
+               {
+                       r += c.getRed();
+                       g += c.getGreen();
+                       b += c.getBlue();
+               }
+               if (cols.size()>0)
+               { 
+                       r /= cols.size();
+                       g /= cols.size();
+                       b /= cols.size();
+               }
+               return new Color(r,g,b);
+       }
+       
+       public Color getAverageOutlineColor()
+       {
+               ArrayList<Color> cols = new ArrayList<Color>(); 
+               for (ModeleBase mb : _bases)
+               {  cols.add(mb.getStyleBase().getBaseOutlineColor()); }
+               return getAverageColor(cols);
+       }
+
+       public Color getAverageNameColor()
+       {
+               ArrayList<Color> cols = new ArrayList<Color>(); 
+               for (ModeleBase mb : _bases)
+               {  cols.add(mb.getStyleBase().getBaseNameColor()); }
+               return getAverageColor(cols);
+       }
+
+       public Color getAverageNumberColor()
+       {
+               ArrayList<Color> cols = new ArrayList<Color>(); 
+               for (ModeleBase mb : _bases)
+               {  cols.add(mb.getStyleBase().getBaseNumberColor()); }
+               return getAverageColor(cols);
+       }
+
+       public Color getAverageInnerColor()
+       {
+               ArrayList<Color> cols = new ArrayList<Color>(); 
+               for (ModeleBase mb : _bases)
+               {  cols.add(mb.getStyleBase().getBaseInnerColor()); }
+               return getAverageColor(cols);
+       }
+
+       public String getNumbers()
+       {
+               String result = ""; 
+               boolean first = true;
+               for (ModeleBase mb:_bases)
+               {  
+                       if (!first)
+                       { result += ","; }
+                       else
+                       { first = false; }
+                       result += "" + mb.getBaseNumber(); 
+               }
+               result += "";
+               return result;
+       }
+
+       public String getContents()
+       {
+               String result = ""; 
+               boolean first = true;
+               for (ModeleBase mb:_bases)
+               {  
+                       if (!first)
+                       { result += ","; }
+                       else
+                       { first = false; }
+                       result += "" + mb.getContent(); 
+               }
+               result += "";
+               return result;
+       }
+
+       public ArrayList<Integer> getIndices()
+       {
+               ArrayList<Integer> indices = new ArrayList<Integer>();
+               for (ModeleBase mb : _bases)
+               {
+                       indices.add(mb.getIndex());
+               }
+               return indices;
+       }
+       
+       /**
+        * Returns, in a new BaseList, the intersection of the current BaseList and of the argument.
+        * @param mb The base list to be used for the intersection
+        * @return The intersection of the current base list and the argument.
+        */
+       
+       public BaseList retainAll(BaseList mb)
+       {
+               HashSet<ModeleBase> cp = new HashSet<ModeleBase>();
+               cp.addAll(_bases);
+               cp.retainAll(mb._bases);
+               BaseList result = new BaseList("TmpIntersection");
+               result.addBases(cp);
+               return result;
+       }
+
+       /**
+        * Returns, in a new BaseList, the list consisting of the current BaseList minus the list passed as argument.
+        * @param mb The base list to be subtracted from the current one
+        * @return The current base list minus the list passed as argument.
+        */
+       
+       public BaseList removeAll(BaseList mb)
+       {
+               HashSet<ModeleBase> cp = new HashSet<ModeleBase>();
+               cp.addAll(_bases);
+               cp.removeAll(mb._bases);
+               BaseList result = new BaseList("TmpMinus");
+               result.addBases(cp);
+               return result;
+       }       
+       
+       public int size()
+       {
+               return _bases.size();
+       }
+
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/FullBackup.java b/src2/fr/orsay/lri/varna/models/FullBackup.java
new file mode 100644 (file)
index 0000000..623b691
--- /dev/null
@@ -0,0 +1,38 @@
+package fr.orsay.lri.varna.models;
+
+import java.io.Serializable;
+
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class FullBackup implements Serializable{
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -5468893731117925140L;
+    public VARNAConfig config; 
+    public RNA rna;
+    public String name; 
+    
+    public FullBackup(VARNAConfig c, RNA r, String n){
+       config = c;
+       rna = r;
+       name = n;
+    }
+
+    public FullBackup(RNA r, String n){
+       config = null;
+       rna = r;
+       name = n;
+    }
+    
+    public String toString()
+    {
+       return name;
+    }
+    public boolean hasConfig()
+    {
+       return config!=null;
+    }
+    
+}
diff --git a/src2/fr/orsay/lri/varna/models/VARNAConfig.java b/src2/fr/orsay/lri/varna/models/VARNAConfig.java
new file mode 100644 (file)
index 0000000..c6fb103
--- /dev/null
@@ -0,0 +1,395 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBPStyle;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+public class VARNAConfig implements Serializable, Cloneable {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 2853916694420964233L;
+       /**
+        * 
+        */
+       public static final int MAJOR_VERSION = 3;
+       public static final int MINOR_VERSION = 9;
+       
+       public static String getFullName()
+       {
+               return "VARNA "+MAJOR_VERSION+"."+MINOR_VERSION;
+       }
+
+       /**
+        * Enum types and internal classes
+        */
+
+       public enum BP_STYLE implements Serializable {
+               NONE, SIMPLE, RNAVIZ, LW, LW_ALT;
+               public String toString()
+               {
+                       switch(this)
+                       {
+                               case LW: return "Leontis/Westhof (Centered)";
+                               case SIMPLE: return "Line";
+                               case RNAVIZ: return "Circles";
+                               case NONE: return "None";
+                               case LW_ALT: return "Leontis/Westhof (End)";
+                       }
+                       return "Unspecified";
+               }
+               public String getOpt()
+               {
+                       switch(this)
+                       {
+                               case NONE: return "none";
+                               case SIMPLE: return "simple";
+                               case LW: return "lw";
+                               case RNAVIZ: return "rnaviz";
+                               case LW_ALT: return "lwalt";
+                       }
+                       return "x";
+               }
+               public static BP_STYLE getStyle(String opt)
+               {
+                       for(BP_STYLE b: BP_STYLE.values())
+                       {
+                               if (opt.toLowerCase().equals(b.getOpt().toLowerCase()))
+                                       return b;
+                       }
+                       return null;
+               }
+       };
+
+       /**
+        * Default values for config options
+        */
+
+       public static final double MAX_ZOOM = 60;
+       public static final double MIN_ZOOM = 0.5;
+       public static final double DEFAULT_ZOOM = 1;
+       public static final double MAX_AMOUNT = 2;
+       public static final double MIN_AMOUNT = 1.01;
+       public static final double DEFAULT_AMOUNT = 1.2;
+       public static final double DEFAULT_BP_THICKNESS = 1.0;
+       public static final double DEFAULT_DIST_NUMBERS = 3.0;
+
+       public static final int DEFAULT_PERIOD = 10;
+
+       public static final Color DEFAULT_TITLE_COLOR = Color.black;
+       public static final Color DEFAULT_BACKBONE_COLOR = Color.DARK_GRAY.brighter();
+       public static final Color DEFAULT_BOND_COLOR = Color.blue;
+       public static final Color DEFAULT_SPECIAL_BASE_COLOR = Color.green.brighter();
+       public static final Color DEFAULT_DASH_BASE_COLOR = Color.yellow.brighter();
+       public static final double DEFAULT_BASE_OUTLINE_THICKNESS = 1.5;
+       public static final Color BASE_OUTLINE_COLOR_DEFAULT = Color.DARK_GRAY.brighter();
+       public static final Color BASE_INNER_COLOR_DEFAULT = new Color(242, 242,242);
+       public static final Color BASE_NUMBER_COLOR_DEFAULT = Color.DARK_GRAY;
+       public static final Color BASE_NAME_COLOR_DEFAULT = Color.black;
+       
+       public static final Color DEFAULT_HOVER_COLOR  =  new Color(230, 230,230);
+
+       public static final Color DEFAULT_BACKGROUND_COLOR = Color.WHITE;
+       public static final Font DEFAULT_TITLE_FONT = new Font("SansSerif", Font.BOLD,18);
+       public static final Font DEFAULT_BASE_FONT = new Font("SansSerif", Font.PLAIN, 18);
+       public static final Font DEFAULT_NUMBERS_FONT = new Font("SansSerif",
+                       Font.BOLD, 18);
+       public static final Font DEFAULT_MESSAGE_FONT = Font.decode("dialog-PLAIN-25");
+       public static final Color DEFAULT_MESSAGE_COLOR = new Color(230, 230,230);
+
+
+       public static final BP_STYLE DEFAULT_BP_STYLE = BP_STYLE.LW;
+
+       public static final ModeleColorMap DEFAULT_COLOR_MAP = ModeleColorMap.defaultColorMap();
+       public static final Color DEFAULT_COLOR_MAP_OUTLINE = Color.gray;
+       public static final double DEFAULT_BP_INCREMENT = 0.65;
+
+       public static double DEFAULT_COLOR_MAP_WIDTH = 120; 
+       public static double DEFAULT_COLOR_MAP_HEIGHT = 30; 
+       public static double DEFAULT_COLOR_MAP_X_OFFSET = 40; 
+       public static double DEFAULT_COLOR_MAP_Y_OFFSET = 0; 
+       public static int DEFAULT_COLOR_MAP_STRIPE_WIDTH = 2; 
+       public static int DEFAULT_COLOR_MAP_FONT_SIZE = 20; 
+       public static Color DEFAULT_COLOR_MAP_FONT_COLOR = Color.gray.darker(); 
+
+       public static double DEFAULT_SPACE_BETWEEN_BASES = 1.0; 
+
+       /**
+        * Various options.
+        */
+       
+       public static String XML_VAR_DRAW_OUTLINE = "drawoutline";
+       public static String XML_VAR_FILL_BASE = "fillbase";
+       public static String XML_VAR_AUTO_FIT = "autofit";
+       public static String XML_VAR_AUTO_CENTER = "autocenter";
+       public static String XML_VAR_MODIFIABLE = "modifiable";
+       public static String XML_VAR_ERRORS = "errors";
+       public static String XML_VAR_SPECIAL_BASES = "specialbases";
+       public static String XML_VAR_DASH_BASES = "dashbases";
+       public static String XML_VAR_USE_BASE_BPS = "usebasebps";
+       public static String XML_VAR_DRAW_NC = "drawnc";
+       public static String XML_VAR_DRAW_NON_PLANAR = "drawnonplanar";
+       public static String XML_VAR_SHOW_WARNINGS = "warnings";
+       public static String XML_VAR_COMPARISON_MODE = "comparison";
+       public static String XML_VAR_FLAT = "flat";
+       public static String XML_VAR_DRAW_BACKGROUND = "drawbackground";
+       public static String XML_VAR_COLOR_MAP = "drawcm";
+       public static String XML_VAR_DRAW_BACKBONE = "drawbackbone";
+       
+       public static String XML_VAR_CM_HEIGHT = "cmh";
+       public static String XML_VAR_CM_WIDTH = "cmw";
+       public static String XML_VAR_CM_X_OFFSET = "cmx";
+       public static String XML_VAR_CM_Y_OFFSET = "cmy";
+       public static String XML_VAR_DEFAULT_ZOOM = "defaultzoom";
+       public static String XML_VAR_ZOOM_AMOUNT = "zoominc";
+       public static String XML_VAR_BP_THICKNESS = "bpthick";
+       public static String XML_VAR_BASE_THICKNESS = "basethick";
+       public static String XML_VAR_DIST_NUMBERS = "distnumbers";
+       
+       public static String XML_VAR_NUM_PERIOD = "numperiod";
+       
+       public static String XML_VAR_MAIN_BP_STYLE = "bpstyle";
+
+       public static String XML_VAR_CM = "cm";
+       
+       public static String XML_VAR_BACKBONE_COLOR = "backbonecol";
+       public static String XML_VAR_HOVER_COLOR = "hovercol";
+       public static String XML_VAR_BACKGROUND_COLOR = "backgroundcol";
+       public static String XML_VAR_BOND_COLOR = "bondcol";
+       public static String XML_VAR_TITLE_COLOR = "titlecol";
+       public static String XML_VAR_SPECIAL_BASES_COLOR = "specialco";
+       public static String XML_VAR_DASH_BASES_COLOR = "dashcol";
+       public static String XML_VAR_SPACE_BETWEEN_BASES = "spacebetweenbases";
+       
+       public static String XML_VAR_TITLE_FONT = "titlefont";
+       public static String XML_VAR_NUMBERS_FONT = "numbersfont";
+       public static String XML_VAR_FONT_BASES = "basefont";
+       
+       public static String XML_VAR_CM_CAPTION = "cmcaption";
+       public static String XML_VAR_TITLE = "title";
+       
+    
+       public boolean _drawOutlineBases = true;
+       public boolean _fillBases = true;
+       public boolean _autoFit = true;
+       public boolean _autoCenter = true;
+       public boolean _modifiable = true;
+       public boolean _errorsOn = false;
+       public boolean _colorSpecialBases = false;
+       public boolean _colorDashBases = false;
+       public boolean _useBaseColorsForBPs = false;
+       public boolean _drawnNonCanonicalBP = true;
+       public boolean _drawnNonPlanarBP = true;
+       public boolean _showWarnings = false;
+       public boolean _comparisonMode = false;
+       public boolean _flatExteriorLoop = true;
+       public boolean _drawBackground = false;
+       public boolean _drawColorMap = false;
+       public boolean _drawBackbone = true;
+       
+       public double _colorMapHeight  = DEFAULT_COLOR_MAP_HEIGHT; 
+       public double _colorMapWidth   = DEFAULT_COLOR_MAP_WIDTH; 
+       public double _colorMapXOffset = DEFAULT_COLOR_MAP_X_OFFSET; 
+       public double _colorMapYOffset = DEFAULT_COLOR_MAP_Y_OFFSET; 
+       public double _zoom            = DEFAULT_ZOOM;
+       public double _zoomAmount      = DEFAULT_AMOUNT;
+       public double _bpThickness     = 1.0;
+       public double _baseThickness   = DEFAULT_BASE_OUTLINE_THICKNESS;
+       public double _distNumbers     = DEFAULT_DIST_NUMBERS;
+       public double _spaceBetweenBases = DEFAULT_SPACE_BETWEEN_BASES;
+       
+       public int _numPeriod = DEFAULT_PERIOD;
+       public BP_STYLE _mainBPStyle = DEFAULT_BP_STYLE;
+       
+       public ModeleColorMap _cm = DEFAULT_COLOR_MAP;  
+
+       public Color _backboneColor      = DEFAULT_BACKBONE_COLOR;
+       public Color _hoverColor         = DEFAULT_HOVER_COLOR;
+       public Color _backgroundColor    = DEFAULT_BACKGROUND_COLOR;
+       public Color _bondColor          = DEFAULT_BOND_COLOR;
+       public Color _titleColor         = DEFAULT_TITLE_COLOR;
+       public Color _specialBasesColor  = DEFAULT_SPECIAL_BASE_COLOR;
+       public Color _dashBasesColor     = DEFAULT_DASH_BASE_COLOR;
+       
+       public Font _titleFont           = DEFAULT_TITLE_FONT;
+       public Font _numbersFont         = DEFAULT_NUMBERS_FONT;
+       public Font _fontBasesGeneral    = DEFAULT_BASE_FONT;
+       
+       public String _colorMapCaption = "";
+       //public String _title = "";
+
+       
+       public static String XML_ELEMENT_NAME = "config";
+       
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_DRAW_OUTLINE,"CDATA",   ""+_drawOutlineBases);
+               atts.addAttribute("","",XML_VAR_FILL_BASE,"CDATA",      ""+_fillBases);
+               atts.addAttribute("","",XML_VAR_AUTO_FIT,"CDATA",       ""+_autoFit);
+               atts.addAttribute("","",XML_VAR_AUTO_CENTER,"CDATA",    ""+_autoCenter);
+               atts.addAttribute("","",XML_VAR_MODIFIABLE,"CDATA",     ""+_modifiable);
+               atts.addAttribute("","",XML_VAR_ERRORS,"CDATA",         ""+_errorsOn);
+               atts.addAttribute("","",XML_VAR_SPECIAL_BASES,"CDATA",  ""+_colorSpecialBases);
+               atts.addAttribute("","",XML_VAR_DASH_BASES,"CDATA",     ""+_colorDashBases);
+               atts.addAttribute("","",XML_VAR_USE_BASE_BPS,"CDATA",   ""+_useBaseColorsForBPs);
+               atts.addAttribute("","",XML_VAR_DRAW_NC,"CDATA",        ""+_drawnNonCanonicalBP);
+               atts.addAttribute("","",XML_VAR_DRAW_NON_PLANAR,"CDATA",""+_drawnNonPlanarBP);
+               atts.addAttribute("","",XML_VAR_SHOW_WARNINGS,"CDATA",  ""+_showWarnings);
+               atts.addAttribute("","",XML_VAR_COMPARISON_MODE,"CDATA",""+_comparisonMode);
+               atts.addAttribute("","",XML_VAR_FLAT,"CDATA",           ""+_flatExteriorLoop);
+               atts.addAttribute("","",XML_VAR_DRAW_BACKGROUND,"CDATA",""+_drawBackground);
+               atts.addAttribute("","",XML_VAR_COLOR_MAP,"CDATA",      ""+_drawColorMap);
+               atts.addAttribute("","",XML_VAR_DRAW_BACKBONE,"CDATA",  ""+_drawBackbone);
+
+               atts.addAttribute("","",XML_VAR_CM_HEIGHT,"CDATA",      ""+_colorMapHeight);
+               atts.addAttribute("","",XML_VAR_CM_WIDTH,"CDATA",       ""+_colorMapWidth);
+               atts.addAttribute("","",XML_VAR_CM_X_OFFSET,"CDATA",    ""+_colorMapXOffset);
+               atts.addAttribute("","",XML_VAR_CM_Y_OFFSET,"CDATA",    ""+_colorMapYOffset);
+               atts.addAttribute("","",XML_VAR_DEFAULT_ZOOM,"CDATA",   ""+_zoom);
+               atts.addAttribute("","",XML_VAR_ZOOM_AMOUNT,"CDATA",    ""+_zoomAmount);
+               atts.addAttribute("","",XML_VAR_BP_THICKNESS,"CDATA",   ""+_bpThickness);
+               atts.addAttribute("","",XML_VAR_BASE_THICKNESS,"CDATA", ""+_baseThickness);
+               atts.addAttribute("","",XML_VAR_DIST_NUMBERS,"CDATA",   ""+_distNumbers);
+               atts.addAttribute("","",XML_VAR_SPACE_BETWEEN_BASES,"CDATA",   ""+_spaceBetweenBases);
+               
+                       
+               atts.addAttribute("","",XML_VAR_NUM_PERIOD,"CDATA",     ""+_numPeriod);
+                       
+               atts.addAttribute("","",XML_VAR_MAIN_BP_STYLE,"CDATA",  ""+_mainBPStyle.getOpt());
+                       
+               atts.addAttribute("","",XML_VAR_BACKBONE_COLOR,"CDATA",     XMLUtils.toHTMLNotation(_backboneColor));
+               atts.addAttribute("","",XML_VAR_HOVER_COLOR,"CDATA",        XMLUtils.toHTMLNotation(_hoverColor));
+               atts.addAttribute("","",XML_VAR_BACKGROUND_COLOR,"CDATA",   XMLUtils.toHTMLNotation(_backgroundColor));
+               atts.addAttribute("","",XML_VAR_BOND_COLOR,"CDATA",         XMLUtils.toHTMLNotation(_bondColor));
+               atts.addAttribute("","",XML_VAR_TITLE_COLOR,"CDATA",        XMLUtils.toHTMLNotation(_titleColor));
+               atts.addAttribute("","",XML_VAR_SPECIAL_BASES_COLOR,"CDATA",XMLUtils.toHTMLNotation(_specialBasesColor));
+               atts.addAttribute("","",XML_VAR_DASH_BASES_COLOR,"CDATA",   XMLUtils.toHTMLNotation(_dashBasesColor)); 
+
+               atts.addAttribute("","",XML_VAR_CM,"CDATA",                             _cm.getParamEncoding()); 
+               
+               
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               XMLUtils.toXML(hd, _titleFont,XML_VAR_TITLE_FONT);
+               XMLUtils.toXML(hd, _numbersFont,XML_VAR_NUMBERS_FONT);
+               XMLUtils.toXML(hd, _fontBasesGeneral,XML_VAR_FONT_BASES);
+               
+               XMLUtils.exportCDATAElem(hd,XML_VAR_CM_CAPTION, _colorMapCaption);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }
+       
+       
+       
+
+       public void loadFromXMLAttributes(Attributes attributes)
+       {
+               _drawOutlineBases      = Boolean.parseBoolean(attributes.getValue(XML_VAR_DRAW_OUTLINE));                             
+               _fillBases             = Boolean.parseBoolean(attributes.getValue(XML_VAR_FILL_BASE));                                
+               _autoFit              = Boolean.parseBoolean(attributes.getValue(XML_VAR_AUTO_FIT));                                 
+               _autoCenter           = Boolean.parseBoolean(attributes.getValue(XML_VAR_AUTO_CENTER));                              
+               _modifiable           = Boolean.parseBoolean(attributes.getValue(XML_VAR_MODIFIABLE));                               
+               _errorsOn             = Boolean.parseBoolean(attributes.getValue(XML_VAR_ERRORS));                                   
+               _colorSpecialBases    = Boolean.parseBoolean(attributes.getValue(XML_VAR_SPECIAL_BASES));                            
+               _colorDashBases       = Boolean.parseBoolean(attributes.getValue(XML_VAR_DASH_BASES));                               
+               _useBaseColorsForBPs  = Boolean.parseBoolean(attributes.getValue(XML_VAR_USE_BASE_BPS));                             
+               _drawnNonCanonicalBP  = Boolean.parseBoolean(attributes.getValue(XML_VAR_DRAW_NC));                                  
+               _drawnNonPlanarBP     = Boolean.parseBoolean(attributes.getValue(XML_VAR_DRAW_NON_PLANAR));                          
+               _showWarnings         = Boolean.parseBoolean(attributes.getValue(XML_VAR_SHOW_WARNINGS));                            
+               _comparisonMode       = Boolean.parseBoolean(attributes.getValue(XML_VAR_COMPARISON_MODE));                          
+               _flatExteriorLoop     = Boolean.parseBoolean(attributes.getValue(XML_VAR_FLAT));                                     
+               _drawBackground       = Boolean.parseBoolean(attributes.getValue(XML_VAR_DRAW_BACKGROUND));                          
+               _drawColorMap         = Boolean.parseBoolean(attributes.getValue(XML_VAR_COLOR_MAP));                                
+               _drawBackbone         = Boolean.parseBoolean(attributes.getValue(XML_VAR_DRAW_BACKBONE));     
+               
+               _colorMapHeight       = Double.parseDouble(attributes.getValue(XML_VAR_CM_HEIGHT));
+               _colorMapWidth        = Double.parseDouble(attributes.getValue(XML_VAR_CM_WIDTH));
+               _colorMapXOffset      = Double.parseDouble(attributes.getValue(XML_VAR_CM_X_OFFSET));
+               _colorMapYOffset      = Double.parseDouble(attributes.getValue(XML_VAR_CM_Y_OFFSET));
+               _zoom                             = Double.parseDouble(attributes.getValue(XML_VAR_DEFAULT_ZOOM));
+               _zoomAmount                   = Double.parseDouble(attributes.getValue(XML_VAR_ZOOM_AMOUNT));
+               _bpThickness          = Double.parseDouble(attributes.getValue(XML_VAR_BP_THICKNESS));
+               _baseThickness        = Double.parseDouble(attributes.getValue(XML_VAR_BASE_THICKNESS));
+               _distNumbers          = Double.parseDouble(attributes.getValue(XML_VAR_DIST_NUMBERS));
+               _spaceBetweenBases    = XMLUtils.getDouble(attributes, XML_VAR_SPACE_BETWEEN_BASES, DEFAULT_SPACE_BETWEEN_BASES);
+                                                                       
+               _numPeriod            = Integer.parseInt(attributes.getValue(XML_VAR_NUM_PERIOD));
+                                                                       
+               _mainBPStyle          = BP_STYLE.getStyle(attributes.getValue(XML_VAR_MAIN_BP_STYLE));           
+                                                                       
+               _backboneColor        = Color.decode(attributes.getValue(XML_VAR_BACKBONE_COLOR));                     
+               _hoverColor           = Color.decode(attributes.getValue(XML_VAR_HOVER_COLOR));                        
+               _backgroundColor      = Color.decode(attributes.getValue(XML_VAR_BACKGROUND_COLOR));                   
+               _bondColor            = Color.decode(attributes.getValue(XML_VAR_BOND_COLOR));                         
+               _titleColor           = Color.decode(attributes.getValue(XML_VAR_TITLE_COLOR));                        
+               _specialBasesColor    = Color.decode(attributes.getValue(XML_VAR_SPECIAL_BASES_COLOR));                
+               _dashBasesColor       = Color.decode(attributes.getValue(XML_VAR_DASH_BASES_COLOR));                   
+                                                                             
+               _cm                   = ModeleColorMap.parseColorMap(attributes.getValue(XML_VAR_CM)); 
+       }
+       
+       
+       
+    public VARNAConfig clone ()
+    {
+      
+      /**
+       * @j2sNative
+       * 
+       * return this;
+       * 
+       */
+        try
+        {
+            ByteArrayOutputStream out = new ByteArrayOutputStream ();
+            ObjectOutputStream oout = new ObjectOutputStream (out);
+            oout.writeObject (this);
+            
+            ObjectInputStream in = new ObjectInputStream (
+                new ByteArrayInputStream (out.toByteArray ()));
+            return (VARNAConfig)in.readObject ();
+        }
+        catch (Exception e)
+        {
+            throw new RuntimeException ("cannot clone class [" +
+                this.getClass ().getName () + "] via serialization: " +
+                e.toString ());
+        }
+    }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/VARNAConfigLoader.java b/src2/fr/orsay/lri/varna/models/VARNAConfigLoader.java
new file mode 100644 (file)
index 0000000..f62b187
--- /dev/null
@@ -0,0 +1,1357 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models;
+
+/*
+ * VARNA is a Java library for quick automated drawings RNA secondary structure
+ * Copyright (C) 2007 Yann Ponty
+ * 
+ * This program 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 3 of the License, or (at your option) any later
+ * version.
+ * 
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
+ * details.
+ * 
+ * You should have received a copy of the GNU General Public License along with
+ * this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Point;
+import java.awt.geom.Point2D;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.Collection;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.exceptions.ExceptionDrawingAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.interfaces.InterfaceParameterLoader;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModelBaseStyle;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+/**
+ * An RNA 2d Panel demo applet
+ * 
+ * @author Yann Ponty
+ * 
+ */
+
+public class VARNAConfigLoader {
+
+       private static final int MAXSTYLE = 50;
+
+       // Applet Options
+
+       public static String algoOpt = "algorithm";
+       public static String annotationsOpt = "annotations";
+       public static String applyBasesStyleOpt = "applyBasesStyle";
+       public static String auxBPsOpt = "auxBPs";
+       public static String autoHelicesOpt = "autoHelices";
+       public static String autoInteriorLoopsOpt = "autoInteriorLoops";
+       public static String autoTerminalLoopsOpt = "autoTerminalLoops";
+
+       public static String backboneColorOpt = "backbone";
+       public static String backgroundColorOpt = "background";
+       public static String baseInnerColorOpt = "baseInner";
+       public static String baseNameColorOpt = "baseName";
+       public static String baseNumbersColorOpt = "baseNum";
+       public static String baseOutlineColorOpt = "baseOutline";
+       public static String basesStyleOpt = "basesStyle";
+       public static String borderOpt = "border";
+       public static String bondColorOpt = "bp";
+       public static String bpIncrementOpt = "bpIncrement";
+       public static String bpStyleOpt = "bpStyle";
+
+       public static String colorMapOpt = "colorMap";
+       public static String colorMapCaptionOpt = "colorMapCaption";
+       public static String colorMapDefOpt = "colorMapStyle";
+       public static String colorMapMinOpt = "colorMapMin";
+       public static String colorMapMaxOpt = "colorMapMax";
+       public static String comparisonModeOpt = "comparisonMode";
+       public static String chemProbOpt = "chemProb";
+       public static String customBasesOpt = "customBases";
+       public static String customBPsOpt = "customBPs";
+
+       public static String drawNCOpt = "drawNC";
+       public static String drawBasesOpt = "drawBases";
+       public static String drawTertiaryOpt = "drawTertiary";
+       public static String drawColorMapOpt = "drawColorMap";
+       public static String drawBackboneOpt = "drawBackbone";
+
+       public static String errorOpt = "error";
+
+       public static String fillBasesOpt = "fillBases";
+       public static String firstSequenceForComparisonOpt = "firstSequence";
+       public static String firstStructureForComparisonOpt = "firstStructure";
+       public static String flatExteriorLoopOpt = "flat";
+       public static String flipOpt = "flip";
+
+       public static String gapsBaseColorOpt = "gapsColor";
+
+       public static String highlightRegionOpt = "highlightRegion";
+
+       public static String nonStandardColorOpt = "nsBasesColor";
+       public static String numColumnsOpt = "rows";
+       public static String numRowsOpt = "columns";
+
+       public static String orientationOpt = "orientation";
+
+       public static String modifiableOpt = "modifiable";
+
+       public static String periodNumOpt = "periodNum";
+
+       public static String rotationOpt = "rotation";
+
+       public static String secondSequenceForComparisonOpt = "secondSequence";
+       public static String secondStructureForComparisonOpt = "secondStructure";
+       public static String sequenceOpt = "sequenceDBN";
+       public static String spaceBetweenBasesOpt = "spaceBetweenBases";
+       public static String structureOpt = "structureDBN";
+
+       public static String titleOpt = "title";
+       public static String titleColorOpt = "titleColor";
+       public static String titleSizeOpt = "titleSize";
+
+       public static String URLOpt = "url";
+
+       public static String warningOpt = "warning";
+
+       public static String zoomOpt = "zoom";
+       public static String zoomAmountOpt = "zoomAmount";
+
+       // Applet assignable parameters
+       private String _algo;
+       public String _annotations;
+       public String _chemProbs;
+       private double _rotation;
+
+       private String _sseq;
+       private String _sstruct;
+
+       private int _numRows;
+       private int _numColumns;
+
+       private String _title;
+       private int _titleSize;
+       private Color _titleColor;
+
+       private String _auxBPs;
+       private String _highlightRegion;
+
+       private boolean _autoHelices;
+       private boolean _autoInteriorLoops;
+       private boolean _autoTerminalLoops;
+
+       private boolean _drawBackbone;
+       private Color _backboneColor;
+       private Color _bondColor;
+       private VARNAConfig.BP_STYLE _bpStyle;
+       private Color _baseOutlineColor;
+       private Color _baseInnerColor;
+       private Color _baseNumColor;
+       private Color _baseNameColor;
+       private Color _gapsColor;
+       private Color _nonStandardColor;
+
+       private boolean _flatExteriorLoop;
+       private String _flip;
+
+       private String _customBases;
+       private String _customBPs;
+
+       private String _colorMapStyle;
+       private String _colorMapCaption;
+       private String _colorMapValues;
+       private double _colorMapMin = Double.MIN_VALUE;
+       private double _colorMapMax = Double.MAX_VALUE;
+
+       private double _spaceBetweenBases = Double.MIN_VALUE;
+
+       private boolean _drawNC;
+       private boolean _drawBases;
+       private boolean _drawTertiary;
+       private boolean _drawColorMap;
+
+       private boolean _fillBases;
+
+       private int _periodResNum;
+       private Dimension _border;
+
+       private Color _backgroundColor;
+
+       private String _orientation;
+
+       private boolean _warning, _error;
+
+       private boolean _modifiable;
+
+       private double _zoom, _zoomAmount;
+
+       private ArrayList<ModelBaseStyle> _basesStyleList;
+
+       private boolean _comparisonMode;
+
+       private String _firstSequence;
+       private String _secondSequence;
+       private String _firstStructure;
+       private String _secondStructure;
+
+       private VARNAPanel _mainSurface;
+
+       private boolean _useNonStandardColor;
+       private boolean _useGapsColor;
+       private double _bpIncrement;
+
+       private boolean _useInnerBaseColor;
+       private boolean _useBaseNameColor;
+       private boolean _useBaseNumbersColor;
+       private boolean _useBaseOutlineColor;
+
+       private String _URL;
+
+       protected ArrayList<VARNAPanel> _VARNAPanelList = new ArrayList<VARNAPanel>();
+
+       InterfaceParameterLoader _optionProducer;
+
+       public VARNAConfigLoader(InterfaceParameterLoader il) {
+               _optionProducer = il;
+       }
+
+       public ArrayList<VARNAPanel> createVARNAPanels()
+                       throws ExceptionParameterError,
+                       ExceptionModeleStyleBaseSyntaxError, ExceptionNonEqualLength,
+                       IOException, ExceptionFileFormatOrSyntax, ExceptionLoadingFailed {
+               _VARNAPanelList.clear();
+               retrieveParametersValues();
+               return _VARNAPanelList;
+       }
+
+       public int getNbRows() {
+               return this._numRows;
+       }
+
+       public int getNbColumns() {
+               return this._numColumns;
+       }
+
+       private void initValues() {
+
+               // Applet assignable parameters
+               _algo = "radiate";
+               _auxBPs = "";
+               _autoHelices = false;
+               _autoInteriorLoops = false;
+               _autoTerminalLoops = false;
+               _annotations = "";
+               _backgroundColor = VARNAConfig.DEFAULT_BACKGROUND_COLOR;
+               _customBases = "";
+               _customBPs = "";
+               _chemProbs = "";
+
+               _colorMapStyle = "";
+               _colorMapValues = "";
+               _colorMapCaption = "";
+               _drawColorMap = false;
+
+               _drawBases = true;
+               _fillBases = true;
+               _drawNC = true;
+               _drawTertiary = true;
+               _border = new Dimension(0, 0);
+               _sseq = "";// =
+               // "CAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIACAGCACGACACUAGCAGUCAGUGUCAGACUGCAIA";
+               _sstruct = "";// =
+               // "..(((((...(((((...(((((...(((((.....)))))...))))).....(((((...(((((.....)))))...))))).....)))))...)))))..";
+               _periodResNum = VARNAConfig.DEFAULT_PERIOD;
+               _rotation = 0.0;
+               _title = "";
+               _titleSize = VARNAConfig.DEFAULT_TITLE_FONT.getSize();
+
+               _backboneColor = VARNAConfig.DEFAULT_BACKBONE_COLOR;
+               _drawBackbone = true;
+
+               _bondColor = VARNAConfig.DEFAULT_BOND_COLOR;
+               _bpStyle = VARNAConfig.DEFAULT_BP_STYLE;
+
+               _highlightRegion = "";
+
+               _baseOutlineColor = VARNAConfig.BASE_OUTLINE_COLOR_DEFAULT;
+               _baseInnerColor = VARNAConfig.BASE_INNER_COLOR_DEFAULT;
+               _baseNumColor = VARNAConfig.BASE_NUMBER_COLOR_DEFAULT;
+               _baseNameColor = VARNAConfig.BASE_NAME_COLOR_DEFAULT;
+
+               _titleColor = VARNAConfig.DEFAULT_TITLE_COLOR;
+               _warning = false;
+               _error = true;
+               _modifiable = true;
+               _zoom = VARNAConfig.DEFAULT_ZOOM;
+               _zoomAmount = VARNAConfig.DEFAULT_AMOUNT;
+
+               _comparisonMode = false;
+               _firstSequence = "";
+               _firstStructure = "";
+               _secondSequence = "";
+               _secondStructure = "";
+
+               _gapsColor = VARNAConfig.DEFAULT_DASH_BASE_COLOR;
+               _useGapsColor = false;
+               _nonStandardColor = VARNAConfig.DEFAULT_SPECIAL_BASE_COLOR;
+               _useNonStandardColor = false;
+
+               _useInnerBaseColor = false;
+               _useBaseNameColor = false;
+               _useBaseNumbersColor = false;
+               _useBaseOutlineColor = false;
+
+               _bpIncrement = VARNAConfig.DEFAULT_BP_INCREMENT;
+
+               _URL = "";
+               _flatExteriorLoop = true;
+               _flip = "";
+               _orientation = "";
+               _spaceBetweenBases = VARNAConfig.DEFAULT_SPACE_BETWEEN_BASES;
+       }
+
+       public static Color getSafeColor(String col, Color def) {
+               Color result;
+               try {
+                       result = Color.decode(col);
+
+               } catch (NumberFormatException e) {
+                       try {
+                               result = Color.getColor(col, def);
+                       } catch (Exception e2) {
+                               // Not a valid color
+                               return def;
+                       }
+               }
+               return result;
+       }
+
+       public static final String LEONTIS_WESTHOF_BP_STYLE = "lw";
+       public static final String LEONTIS_WESTHOF_BP_STYLE_ALT = "lwalt";
+       public static final String SIMPLE_BP_STYLE = "simple";
+       public static final String RNAVIZ_BP_STYLE = "rnaviz";
+       public static final String NONE_BP_STYLE = "none";
+
+       private VARNAConfig.BP_STYLE getSafeBPStyle(String opt,
+                       VARNAConfig.BP_STYLE def) {
+               VARNAConfig.BP_STYLE b = VARNAConfig.BP_STYLE.getStyle(opt);
+               if (b!= null)
+               {
+                       return b;
+               } else {
+                       return def;
+               }
+       }
+
+       public static String[][] getParameterInfo() {
+               String[][] info = {
+                               // Parameter Name Kind of Value Description
+                               {
+                                               algoOpt,
+                                               "String",
+                                               "Drawing algorithm, choosen from ["
+                                                               + VARNAConfigLoader.ALGORITHM_NAVIEW + ","
+                                                               + VARNAConfigLoader.ALGORITHM_LINE + ","
+                                                               + VARNAConfigLoader.ALGORITHM_RADIATE + ","
+                                                               + VARNAConfigLoader.ALGORITHM_CIRCULAR + "]" },
+                               { annotationsOpt, "string", "A set of textual annotations" },
+                               { applyBasesStyleOpt, "String", "Base style application" },
+                               {
+                                               auxBPsOpt,
+                                               "String",
+                                               "Adds a list of (possibly non-canonical) base-pairs to those already defined by the main secondary structure (Ex: \"(1,10);(2,11);(3,12)\"). Custom BP styles can be specified (Ex: \"(2,11):thickness=4;(3,12):color=#FF0000\")." },
+                               { autoHelicesOpt, "", "" },
+                               { autoInteriorLoopsOpt, "", "" },
+                               { autoTerminalLoopsOpt, "", "" },
+                               { backboneColorOpt, "Color", "Backbone color (Ex: #334455)" },
+                               { backgroundColorOpt, "Color", "Background color (Ex: #334455)" },
+                               { baseInnerColorOpt, "Color",
+                                               "Default value for inner base color (Ex: #334455)" },
+                               { baseNameColorOpt, "Color",
+                                               "Residues font color (Ex: #334455)" },
+                               { baseNumbersColorOpt, "Color",
+                                               "Base numbers font color (Ex: #334455)" },
+                               { baseOutlineColorOpt, "Color",
+                                               "Base outline color (Ex: #334455)" },
+                               { basesStyleOpt, "String", "Base style declaration" },
+                               { borderOpt, "String",
+                                               "Border width and height in pixels (Ex: \"20x40\")" },
+                               { bondColorOpt, "Color", "Base pair color (Ex: #334455)" },
+                               { bpIncrementOpt, "float",
+                                               "Distance between nested base-pairs (i.e. arcs) in linear representation" },
+                               {
+                                               bpStyleOpt,
+                                               "String",
+                                               "Look and feel for base pairs drawings, choosen from ["
+                                                               + VARNAConfigLoader.LEONTIS_WESTHOF_BP_STYLE+ "," 
+                                                               + VARNAConfigLoader.LEONTIS_WESTHOF_BP_STYLE_ALT+ "," 
+                                                               + VARNAConfigLoader.NONE_BP_STYLE + ","
+                                                               + VARNAConfigLoader.SIMPLE_BP_STYLE + ","
+                                                               + VARNAConfigLoader.RNAVIZ_BP_STYLE + "]" },
+                               { chemProbOpt, "", "" },
+                               {
+                                               colorMapOpt,
+                                               "String",
+                                               "Associates a list of numerical values (eg '0.2,0.4,0.6,0.8') with the RNA bases with respect to their natural order, and modifies the color used to fill these bases according to current color map style." },
+                               { colorMapCaptionOpt, "String",
+                                               "Sets current color map caption." },
+                               {
+                                               colorMapDefOpt,
+                                               "String",
+                                               "Selects a specific color map style. It can be either one of the predefined styles (eg 'red', 'green', 'blue', 'bw', 'heat', 'energy') or a new one (eg '0:#FFFF00;1:#ffFFFF;6:#FF0000')." },
+                               { colorMapMinOpt, "", "" },
+                               { colorMapMaxOpt, "", "" },
+                               { comparisonModeOpt, "boolean", "Activates comparison mode" },
+                               { customBasesOpt, "", "" },
+                               { customBPsOpt, "", "" },
+                               { drawBackboneOpt, "boolean",
+                                               "True if the backbone must be drawn, false otherwise" },
+                               { drawColorMapOpt, "", "" },
+                               { drawNCOpt, "boolean",
+                                               "Toggles on/off display of non-canonical base-pairs" },
+                               { drawBasesOpt, "boolean", "Shows/hide the outline of bases" },
+                               { drawTertiaryOpt, "boolean",
+                                               "Toggles on/off display of tertiary interaction, ie pseudoknots" },
+                               { errorOpt, "boolean", "Show errors" },
+                               { fillBasesOpt, "boolean",
+                                               "Fills or leaves empty the inner portions of bases" },
+                               { firstSequenceForComparisonOpt, "String",
+                                               "In comparison mode, sequence of first RNA" },
+                               { firstStructureForComparisonOpt, "String",
+                                               "In comparison mode, structure of first RNA" },
+                               { flatExteriorLoopOpt, "boolean",
+                                               "Toggles on/off (true/false) drawing exterior bases on a straight line" },
+                               { flipOpt, "String",
+                                               "Draws a set of exterior helices, identified by the argument string, in clockwise order (default drawing is counter-clockwise). The argument is a semicolon-separated list of helices, each identified by a base or a base-pair (eg. \"2;20-34\")." },
+                               { gapsBaseColorOpt, "Color",
+                                               "Define and use custom color for gaps bases in comparison mode" },
+                               { highlightRegionOpt, "string", "Highlight a set of contiguous regions" },
+                               { modifiableOpt, "boolean", "Allows/prohibits modifications" },
+                               { nonStandardColorOpt, "Color",
+                                               "Define and use custom color for non-standard bases in comparison mode" },
+                               { numColumnsOpt, "int", "Sets number of columns" },
+                               { numRowsOpt, "int", "Sets number of rows" },
+                               {
+                                               orientationOpt,
+                                               "float",
+                                               "Sets the general orientation of an RNA, i.e. the deviation of the longest axis (defined by the most distant couple of bases) from the horizontal axis." },
+                               { periodNumOpt, "int", "Periodicity of base-numbering" },
+                               { secondSequenceForComparisonOpt, "String",
+                                               "In comparison mode, sequence of second RNA" },
+                               { secondStructureForComparisonOpt, "String",
+                                               "In comparison mode, structure of second RNA" },
+                               { sequenceOpt, "String", "Raw RNA sequence" },
+                               { structureOpt, "String",
+                                               "RNA structure given in dot bracket notation (DBN)" },
+                               {
+                                               rotationOpt,
+                                               "float",
+                                               "Rotates RNA after initial drawing (Ex: '20' for a 20 degree counter-clockwise rotation)" },
+                               { titleOpt, "String", "RNA drawing title" },
+                               { titleColorOpt, "Color", "Title color (Ex: #334455)" },
+                               { titleSizeOpt, "int", "Title font size" },
+                               { spaceBetweenBasesOpt, "float",
+                                               "Sets the space between consecutive bases" },
+                               { warningOpt, "boolean", "Show warnings" },
+                               { zoomOpt, "int", "Zoom coefficient" },
+                               { zoomAmountOpt, "int", "Zoom increment on user interaction" } };
+               return info;
+       }
+
+       private void retrieveParametersValues() throws ExceptionParameterError {
+
+               _numRows = 1;
+               _numColumns = 1;
+               _basesStyleList = new ArrayList<ModelBaseStyle>();
+
+               try {
+                       _numRows = Integer.parseInt(_optionProducer.getParameterValue(
+                                       numRowsOpt, "" + _numRows));
+               } catch (NumberFormatException e) {
+                       throw new ExceptionParameterError(e.getMessage(), "'"
+                                       + _optionProducer.getParameterValue(numRowsOpt, ""
+                                                       + _numRows)
+                                       + "' is not a integer value for the number of rows !");
+               }
+               try {
+                       _numColumns = Integer.parseInt(_optionProducer.getParameterValue(
+                                       numColumnsOpt, "" + _numColumns));
+               } catch (NumberFormatException e) {
+                       throw new ExceptionParameterError(e.getMessage(), "'"
+                                       + _optionProducer.getParameterValue(numColumnsOpt, ""
+                                                       + _numColumns)
+                                       + "' is not a integer value for the number of columns !");
+               }
+
+               String tmp = null;
+               for (int i = 0; i < MAXSTYLE; i++) {
+                       String opt = basesStyleOpt + i;
+                       tmp = _optionProducer.getParameterValue(opt, null);
+                       // System.out.println(opt+"->"+tmp);
+                       if (tmp != null) {
+                               ModelBaseStyle msb = new ModelBaseStyle();
+                               try {
+                                       msb.assignParameters(tmp);
+                               } catch (ExceptionModeleStyleBaseSyntaxError e) {
+                                       VARNAPanel.emitWarningStatic(e, null);
+                               }
+                               _basesStyleList.add(msb);
+                       } else {
+                               _basesStyleList.add(null);
+                       }
+               }
+
+               // _containerApplet.getLayout().
+               int x;
+               String n;
+               initValues();
+               for (int i = 0; i < _numColumns; i++) {
+                       for (int j = 0; j < _numRows; j++) {
+                               try {
+                                       // initValues();
+                                       x = 1 + j + i * _numRows;
+                                       n = "" + x;
+                                       if ((_numColumns == 1) && (_numRows == 1)) {
+                                               n = "";
+                                       }
+                                       _useGapsColor = false;
+                                       _useNonStandardColor = false;
+
+                                       tmp = _optionProducer.getParameterValue(baseNameColorOpt
+                                                       + n, "");
+                                       if (!tmp.equals("")) {
+                                               _useBaseNameColor = true;
+                                               _baseNameColor = getSafeColor(tmp, _baseNameColor);
+                                       }
+                                       tmp = _optionProducer.getParameterValue(baseNumbersColorOpt
+                                                       + n, "");
+                                       if (!tmp.equals("")) {
+                                               _useBaseNumbersColor = true;
+                                               _baseNumColor = getSafeColor(tmp, _baseNumColor);
+                                       }
+                                       tmp = _optionProducer.getParameterValue(baseOutlineColorOpt
+                                                       + n, "");
+                                       if (!tmp.equals("")) {
+                                               _useBaseOutlineColor = true;
+                                               _baseOutlineColor = getSafeColor(tmp, _baseOutlineColor);
+                                       }
+                                       tmp = _optionProducer.getParameterValue(baseInnerColorOpt
+                                                       + n, "");
+                                       if (!tmp.equals("")) {
+                                               _useInnerBaseColor = true;
+                                               _baseInnerColor = getSafeColor(tmp, _baseInnerColor);
+                                       }
+
+                                       tmp = _optionProducer.getParameterValue(nonStandardColorOpt
+                                                       + n, "");
+                                       if (!tmp.equals("")) {
+                                               _nonStandardColor = getSafeColor(tmp, _nonStandardColor);
+                                               _useNonStandardColor = true;
+                                       }
+                                       tmp = _optionProducer.getParameterValue(gapsBaseColorOpt
+                                                       + n, _gapsColor.toString());
+                                       if (!tmp.equals("")) {
+                                               _gapsColor = getSafeColor(tmp, _gapsColor);
+                                               _useGapsColor = true;
+                                       }
+                                       try {
+                                               _rotation = Double.parseDouble(_optionProducer
+                                                               .getParameterValue(rotationOpt + n,
+                                                                               Double.toString(_rotation)));
+                                       } catch (NumberFormatException e) {
+                                               throw new ExceptionParameterError(e.getMessage(), "'"
+                                                               + _optionProducer.getParameterValue(rotationOpt
+                                                                               + n, "" + _rotation)
+                                                               + "' is not a valid float value for rotation!");
+                                       }
+
+                                       try {
+                                               _colorMapMin = Double.parseDouble(_optionProducer
+                                                               .getParameterValue(colorMapMinOpt + n,
+                                                                               Double.toString(this._colorMapMin)));
+                                       } catch (NumberFormatException e) {
+                                               throw new ExceptionParameterError(
+                                                               e.getMessage(),
+                                                               "'"
+                                                                               + _optionProducer.getParameterValue(
+                                                                                               colorMapMinOpt + n, ""
+                                                                                                               + _colorMapMin)
+                                                                               + "' is not a valid double value for min color map values range!");
+                                       }
+
+                                       try {
+                                               _colorMapMax = Double.parseDouble(_optionProducer
+                                                               .getParameterValue(colorMapMaxOpt + n,
+                                                                               Double.toString(this._colorMapMax)));
+                                       } catch (NumberFormatException e) {
+                                               throw new ExceptionParameterError(
+                                                               e.getMessage(),
+                                                               "'"
+                                                                               + _optionProducer.getParameterValue(
+                                                                                               colorMapMaxOpt + n, ""
+                                                                                                               + _colorMapMax)
+                                                                               + "' is not a valid double value for max color map values range!");
+                                       }
+
+                                       try {
+                                               _bpIncrement = Double.parseDouble(_optionProducer
+                                                               .getParameterValue(bpIncrementOpt + n,
+                                                                               Double.toString(_bpIncrement)));
+                                       } catch (NumberFormatException e) {
+                                       }
+
+                                       try {
+                                               _periodResNum = Integer.parseInt(_optionProducer
+                                                               .getParameterValue(periodNumOpt + n, ""
+                                                                               + _periodResNum));
+                                       } catch (NumberFormatException e) {
+                                               throw new ExceptionParameterError(
+                                                               e.getMessage(),
+                                                               "'"
+                                                                               + _optionProducer.getParameterValue(
+                                                                                               periodNumOpt + n, ""
+                                                                                                               + _periodResNum)
+                                                                               + "' is not a valid integer value for the period of residue numbers!");
+                                       }
+                                       try {
+                                               _titleSize = Integer.parseInt(_optionProducer
+                                                               .getParameterValue(titleSizeOpt + n, ""
+                                                                               + _titleSize));
+                                       } catch (NumberFormatException e) {
+                                               throw new ExceptionParameterError(
+                                                               e.getMessage(),
+                                                               "'"
+                                                                               + _optionProducer.getParameterValue(
+                                                                                               titleSizeOpt + n, ""
+                                                                                                               + _titleSize)
+                                                                               + "' is not a valid integer value for the number of rows !");
+                                       }
+
+                                       try {
+                                               _zoom = Double.parseDouble(_optionProducer
+                                                               .getParameterValue(zoomOpt + n, "" + _zoom));
+                                       } catch (NumberFormatException e) {
+                                               throw new ExceptionParameterError(
+                                                               e.getMessage(),
+                                                               "'"
+                                                                               + _optionProducer.getParameterValue(
+                                                                                               zoomOpt + n, "" + _zoom)
+                                                                               + "' is not a valid integer value for the zoom !");
+                                       }
+
+                                       try {
+                                               _zoomAmount = Double.parseDouble(_optionProducer
+                                                               .getParameterValue(zoomAmountOpt + n, ""
+                                                                               + _zoomAmount));
+                                       } catch (NumberFormatException e) {
+                                               throw new ExceptionParameterError(
+                                                               e.getMessage(),
+                                                               "'"
+                                                                               + _optionProducer.getParameterValue(
+                                                                                               zoomAmountOpt + n, ""
+                                                                                                               + _zoomAmount)
+                                                                               + "' is not a valid integer value for the zoom amount!");
+                                       }
+
+                                       try {
+                                               _spaceBetweenBases = Double.parseDouble(_optionProducer
+                                                               .getParameterValue(spaceBetweenBasesOpt + n, ""
+                                                                               + _spaceBetweenBases));
+                                       } catch (NumberFormatException e) {
+                                               throw new ExceptionParameterError(
+                                                               e.getMessage(),
+                                                               "'"
+                                                                               + _optionProducer.getParameterValue(
+                                                                                               spaceBetweenBasesOpt + n, ""
+                                                                                                               + _spaceBetweenBases)
+                                                                               + "' is not a valid integer value for the base spacing!");
+                                       }
+
+                                       _drawBases = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(drawBasesOpt + n, ""
+                                                                       + _drawBases));
+                                       _fillBases = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(fillBasesOpt + n, ""
+                                                                       + _fillBases));
+                                       _autoHelices = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(autoHelicesOpt + n, ""
+                                                                       + _autoHelices));
+                                       _drawColorMap = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(drawColorMapOpt + n, ""
+                                                                       + _drawColorMap));
+                                       _drawBackbone = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(drawBackboneOpt + n, ""
+                                                                       + _drawBackbone));
+                                       _colorMapValues = _optionProducer.getParameterValue(
+                                                       colorMapOpt + n, _colorMapValues);
+                                       _autoTerminalLoops = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(autoTerminalLoopsOpt + n, ""
+                                                                       + _autoTerminalLoops));
+                                       _autoInteriorLoops = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(autoInteriorLoopsOpt + n, ""
+                                                                       + _autoInteriorLoops));
+                                       _drawNC = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(drawNCOpt + n, "" + _drawNC));
+                                       _flatExteriorLoop = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(flatExteriorLoopOpt + n, ""
+                                                                       + _flatExteriorLoop));
+                                       _drawTertiary = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(drawTertiaryOpt + n, ""
+                                                                       + _drawTertiary));
+                                       _warning = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(warningOpt + n, "false"));
+                                       _error = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(errorOpt + n, "true"));
+                                       _border = parseDimension(_optionProducer.getParameterValue(
+                                                       borderOpt + n, "0X0"));
+                                       _comparisonMode = Boolean.parseBoolean(_optionProducer
+                                                       .getParameterValue(comparisonModeOpt + n, "false"));
+                                       _firstSequence = _optionProducer.getParameterValue(
+                                                       firstSequenceForComparisonOpt + n, _firstSequence);
+                                       _firstStructure = _optionProducer
+                                                       .getParameterValue(firstStructureForComparisonOpt
+                                                                       + n, _firstStructure);
+                                       _secondSequence = _optionProducer
+                                                       .getParameterValue(secondSequenceForComparisonOpt
+                                                                       + n, _secondSequence);
+                                       _secondStructure = _optionProducer.getParameterValue(
+                                                       secondStructureForComparisonOpt + n,
+                                                       _secondStructure);
+                                       _annotations = _optionProducer.getParameterValue(
+                                                       annotationsOpt + n, _annotations);
+                                       _URL = _optionProducer.getParameterValue(URLOpt + n, _URL);
+                                       _algo = _optionProducer.getParameterValue(algoOpt + n,
+                                                       _algo);
+                                       _customBases = _optionProducer.getParameterValue(
+                                                       customBasesOpt + n, _customBases);
+                                       _auxBPs = _optionProducer.getParameterValue(auxBPsOpt + n,
+                                                       _auxBPs);
+                                       _highlightRegion = _optionProducer.getParameterValue(
+                                                       highlightRegionOpt + n, _highlightRegion);
+                                       _chemProbs = _optionProducer.getParameterValue(chemProbOpt
+                                                       + n, _chemProbs);
+                                       _customBPs = _optionProducer.getParameterValue(customBPsOpt
+                                                       + n, _customBPs);
+                                       _colorMapStyle = _optionProducer.getParameterValue(
+                                                       colorMapDefOpt + n, _colorMapStyle);
+                                       _colorMapCaption = _optionProducer.getParameterValue(
+                                                       colorMapCaptionOpt + n, _colorMapCaption);
+                                       _backboneColor = getSafeColor(
+                                                       _optionProducer.getParameterValue(backboneColorOpt
+                                                                       + n, _backboneColor.toString()),
+                                                       _backboneColor);
+                                       _backgroundColor = getSafeColor(
+                                                       _optionProducer.getParameterValue(
+                                                                       backgroundColorOpt + n,
+                                                                       _backgroundColor.toString()),
+                                                       _backgroundColor);
+                                       _bondColor = getSafeColor(
+                                                       _optionProducer.getParameterValue(bondColorOpt + n,
+                                                                       _bondColor.toString()), _bondColor);
+                                       _bpStyle = getSafeBPStyle(
+                                                       _optionProducer.getParameterValue(bpStyleOpt + n,
+                                                                       ""), _bpStyle);
+                                       _flip = _optionProducer.getParameterValue(
+                                                       flipOpt + n, _flip);
+                                       _orientation = _optionProducer.getParameterValue(
+                                                       orientationOpt + n, _orientation);
+                                       _titleColor = getSafeColor(
+                                                       _optionProducer.getParameterValue(
+                                                                       titleColorOpt + n, _titleColor.toString()),
+                                                       _titleColor);
+
+                                       
+                                       
+                                       if (!_URL.equals("")) {
+                                               _sstruct = "";
+                                               _sseq = "";
+                                               _title = "";
+                                       }
+                                       _title = _optionProducer.getParameterValue(titleOpt + n, _title);
+
+                                       if (_comparisonMode && _firstSequence != null
+                                                       && _firstStructure != null
+                                                       && _secondSequence != null
+                                                       && _secondStructure != null) {
+                                       } else {
+                                               _sseq = _optionProducer.getParameterValue(sequenceOpt
+                                                               + n, _sseq);
+                                               _sstruct = _optionProducer.getParameterValue(
+                                                               structureOpt + n, _sstruct);
+                                               if (!_sseq.equals("") && !_sstruct.equals("")) {
+                                                       _URL = "";
+                                               }
+                                               _comparisonMode = false;
+                                       }
+
+                                       // applique les valeurs des parametres recuperees
+                                       applyValues(n);
+                               } catch (ExceptionParameterError e) {
+                                       VARNAPanel.errorDialogStatic(e, _mainSurface);
+                               } catch (ExceptionNonEqualLength e) {
+                                       VARNAPanel.errorDialogStatic(e, _mainSurface);
+                               } catch (IOException e) {
+                                       VARNAPanel.errorDialogStatic(e, _mainSurface);
+                               } catch (ExceptionFileFormatOrSyntax e) {
+                                       VARNAPanel.errorDialogStatic(e, _mainSurface);
+                               } catch (ExceptionLoadingFailed e) {
+                                       VARNAPanel.errorDialogStatic(e, _mainSurface);
+                               }
+                       }// fin de boucle sur les lignes
+               }// fin de boucle sur les colonnes
+       }
+
+       private RNA _defaultRNA = new RNA();
+
+       public void setRNA(RNA r) {
+               _defaultRNA = r;
+       }
+
+       public static final String ALGORITHM_CIRCULAR = "circular";
+       public static final String ALGORITHM_NAVIEW = "naview";
+       public static final String ALGORITHM_LINE = "line";
+       public static final String ALGORITHM_RADIATE = "radiate";
+       public static final String ALGORITHM_VARNA_VIEW = "varnaview";
+       public static final String ALGORITHM_MOTIF_VIEW = "motifview";
+
+       private void applyValues(String n) throws ExceptionParameterError,
+                       ExceptionNonEqualLength, IOException, ExceptionFileFormatOrSyntax,
+                       ExceptionLoadingFailed {
+               boolean applyOptions = true;
+               int algoCode;
+               if (_algo.equals(ALGORITHM_CIRCULAR))
+                       algoCode = RNA.DRAW_MODE_CIRCULAR;
+               else if (_algo.equals(ALGORITHM_NAVIEW))
+                       algoCode = RNA.DRAW_MODE_NAVIEW;
+               else if (_algo.equals(ALGORITHM_LINE))
+                       algoCode = RNA.DRAW_MODE_LINEAR;
+               else if (_algo.equals(ALGORITHM_RADIATE))
+                       algoCode = RNA.DRAW_MODE_RADIATE;
+               else if (_algo.equals(ALGORITHM_VARNA_VIEW))
+                       algoCode = RNA.DRAW_MODE_VARNA_VIEW;
+               else if (_algo.equals(ALGORITHM_MOTIF_VIEW))
+                       algoCode = RNA.DRAW_MODE_MOTIFVIEW;
+               else
+                       algoCode = RNA.DRAW_MODE_RADIATE;
+
+               if (_comparisonMode) {
+                       _mainSurface = new VARNAPanel(_firstSequence, _firstStructure,
+                                       _secondSequence, _secondStructure, algoCode, "");
+               } else {
+                       _mainSurface = new VARNAPanel();
+               }
+
+               _VARNAPanelList.add(_mainSurface);
+               _mainSurface.setSpaceBetweenBases(_spaceBetweenBases);
+               _mainSurface.setTitle(_title);
+
+               if (!_URL.equals("")) {
+                       URL url = null;
+                       try {
+
+                               _mainSurface.setSpaceBetweenBases(_spaceBetweenBases);
+
+                               url = new URL(_URL);
+                               URLConnection connexion = url.openConnection();
+                               connexion.setUseCaches(false);
+                               InputStream r = connexion.getInputStream();
+                               InputStreamReader inr = new InputStreamReader(r);
+
+                               if (_URL.toLowerCase().endsWith(
+                                               VARNAPanel.VARNA_SESSION_EXTENSION)) {
+                                       FullBackup f;
+                                       f = VARNAPanel.importSession(r, _URL);
+                                       _mainSurface.setConfig(f.config);
+                                       _mainSurface.showRNA(f.rna);
+                                       applyOptions = false;
+                               } else {
+                                       Collection<RNA> rnas = RNAFactory.loadSecStr(
+                                                       new BufferedReader(inr),
+                                                       RNAFactory.guessFileTypeFromExtension(_URL));
+                                       if (rnas.isEmpty()) {
+                                               throw new ExceptionFileFormatOrSyntax(
+                                                               "No RNA in file '" + _URL + "'.");
+                                       }
+                                       RNA rna = rnas.iterator().next();
+                                       rna.drawRNA(algoCode, _mainSurface.getConfig());
+                                       _mainSurface.drawRNA(rna, algoCode);
+                               }
+                               if (!_title.isEmpty())
+                               {
+                                       _mainSurface.setTitle(_title);
+                               }
+                       } catch (ExceptionFileFormatOrSyntax e) {
+                               if (url != null)
+                                       e.setPath(url.getPath());
+                       } catch (ExceptionDrawingAlgorithm e) {
+                               _mainSurface.emitWarning(e.getMessage());
+                       }
+
+               } else {
+                       if (!_comparisonMode) {
+                               if (!_sstruct.equals("")) {
+                                       _mainSurface.drawRNA(_sseq, _sstruct, algoCode);
+                               } else {
+                                       try {
+                                               System.err.println("Printing default RNA "+_defaultRNA);
+                                               _defaultRNA.drawRNA(algoCode, _mainSurface.getConfig());
+                                       } catch (ExceptionDrawingAlgorithm e) {
+                                               e.printStackTrace();
+                                       }
+                                       _mainSurface.drawRNA(_defaultRNA);
+                               }
+                       }
+               }
+               if (applyOptions)
+               {
+                       if (_useInnerBaseColor) {
+                               _mainSurface.setBaseInnerColor(_baseInnerColor);
+                       }
+                       if (_useBaseOutlineColor) {
+                               _mainSurface.setBaseOutlineColor(_baseOutlineColor);
+                       }
+                       if (_useBaseNameColor) {
+                               _mainSurface.setBaseNameColor(_baseNameColor);
+                       }
+                       if (_useBaseNumbersColor) {
+                               _mainSurface.setBaseNumbersColor(_baseNumColor);
+                       }
+
+                       _mainSurface.setBackground(_backgroundColor);
+                       _mainSurface.setNumPeriod(_periodResNum);
+                       _mainSurface.setBackboneColor(_backboneColor);
+                       _mainSurface.setDefaultBPColor(_bondColor);
+                       _mainSurface.setBPHeightIncrement(_bpIncrement);
+                       _mainSurface.setBPStyle(_bpStyle);
+                       _mainSurface.setDrawBackbone(_drawBackbone);
+
+                       _mainSurface.setTitleFontColor(_titleColor);
+                       _mainSurface.setTitleFontSize(_titleSize);
+
+                       _mainSurface.getPopupMenu().get_itemShowWarnings()
+                                       .setState(_warning);
+                       _mainSurface.setErrorsOn(_error);
+                       _mainSurface.setFlatExteriorLoop(_flatExteriorLoop);
+                       _mainSurface.setZoom(_zoom);
+                       _mainSurface.setZoomIncrement(_zoomAmount);
+                       _mainSurface.setBorderSize(_border);
+
+                       if (_useGapsColor) {
+                               _mainSurface.setGapsBasesColor(this._gapsColor);
+                               _mainSurface.setColorGapsBases(true);
+                       }
+
+                       if (_useNonStandardColor) {
+                               _mainSurface.setNonStandardBasesColor(_nonStandardColor);
+                               _mainSurface.setColorNonStandardBases(true);
+                       }
+
+                       _mainSurface.setShowNonPlanarBP(_drawTertiary);
+                       _mainSurface.setShowNonCanonicalBP(_drawNC);
+
+                       applyBasesStyle(n);
+
+                       if (!_customBases.equals(""))
+                               applyBasesCustomStyles(_mainSurface);
+
+                       if (!_highlightRegion.equals(""))
+                               applyHighlightRegion(_mainSurface);
+
+                       if (!_auxBPs.equals(""))
+                               applyAuxBPs(_mainSurface);
+
+                       if (!_chemProbs.equals(""))
+                               applyChemProbs(_mainSurface);
+
+                       if (!_customBPs.equals(""))
+                               applyBPsCustomStyles(_mainSurface);
+
+                       _mainSurface.setDrawOutlineBases(_drawBases);
+                       _mainSurface.setFillBases(_fillBases);
+                       _mainSurface.drawRNA();
+
+                       if (!_annotations.equals(""))
+                               applyAnnotations(_mainSurface);
+                       if (_autoHelices)
+                               _mainSurface.getVARNAUI().UIAutoAnnotateHelices();
+                       if (_autoTerminalLoops)
+                               _mainSurface.getVARNAUI().UIAutoAnnotateTerminalLoops();
+                       if (_autoInteriorLoops)
+                               _mainSurface.getVARNAUI().UIAutoAnnotateInteriorLoops();
+
+                       if (!_orientation.equals("")) {
+                               try {
+                                       double d = 360 * _mainSurface.getOrientation()
+                                                       / (2. * Math.PI);
+                                       _rotation = Double.parseDouble(_orientation) - d;
+                               } catch (NumberFormatException e) {
+                                       // TODO : Add some code here...
+                               }
+
+                       }
+                       _mainSurface.globalRotation(_rotation);
+
+                       _mainSurface.setModifiable(_modifiable);
+
+                       _mainSurface.setColorMapCaption(_colorMapCaption);
+                       applyColorMapStyle(_mainSurface);
+                       applyFlips(_mainSurface);
+                       applyColorMapValues(_mainSurface);
+                       
+                       // if (!_drawColorMap)
+                       // _mainSurface.drawColorMap(_drawColorMap);
+               }
+               // ajoute le VARNAPanel au conteneur
+       }
+
+       private void applyBasesStyle(String n) throws ExceptionParameterError {
+               String tmp = null;
+               for (int numStyle = 0; numStyle < _basesStyleList.size(); numStyle++) {
+                       if (_basesStyleList.get(numStyle) != null) {
+                               tmp = _optionProducer.getParameterValue(applyBasesStyleOpt
+                                               + (numStyle) + "on" + n, null);
+
+                               ArrayList<Integer> indicesList = new ArrayList<Integer>();
+                               if (tmp != null) {
+                                       String[] basesList = tmp.split(",");
+                                       for (int k = 0; k < basesList.length; k++) {
+                                               String cand = basesList[k].trim();
+                                               try {
+                                                       String[] args = cand.split("-");
+                                                       if (args.length == 1) {
+                                                               int baseNum = Integer.parseInt(cand);
+                                                               int index = _mainSurface.getRNA()
+                                                                               .getIndexFromBaseNumber(baseNum);
+                                                               if (index != -1) {
+                                                                       indicesList.add(index);
+                                                               }
+                                                       } else if (args.length == 2) {
+                                                               int baseNumFrom = Integer.parseInt(args[0]
+                                                                               .trim());
+                                                               int indexFrom = _mainSurface.getRNA()
+                                                                               .getIndexFromBaseNumber(baseNumFrom);
+                                                               int baseNumTo = Integer
+                                                                               .parseInt(args[1].trim());
+                                                               int indexTo = _mainSurface.getRNA()
+                                                                               .getIndexFromBaseNumber(baseNumTo);
+                                                               if ((indexFrom != -1) && (indexTo != -1)) {
+                                                                       for (int l = indexFrom; l <= indexTo; l++)
+                                                                               indicesList.add(l);
+                                                               }
+                                                       }
+                                               } catch (NumberFormatException e) {
+                                                       throw new ExceptionParameterError(e.getMessage(),
+                                                                       "Bad Base Index: " + basesList[k]);
+                                               }
+                                       }
+                                       for (int k = 0; k < indicesList.size(); k++) {
+                                               int index = indicesList.get(k);
+                                               if ((index >= 0)
+                                                               && (index < _mainSurface.getRNA()
+                                                                               .get_listeBases().size())) {
+                                                       _mainSurface
+                                                                       .getRNA()
+                                                                       .get_listeBases()
+                                                                       .get(index)
+                                                                       .setStyleBase(_basesStyleList.get(numStyle));
+                                               }
+                                       }
+                               }
+                       }
+               }// fin de boucle sur les styles
+
+       }
+
+       private void applyColorMapStyle(VARNAPanel vp) {
+               if (_colorMapStyle.length() != 0) {
+                       vp.setColorMap(ModeleColorMap.parseColorMap(_colorMapStyle));
+               }
+       }
+
+       private void applyColorMapValues(VARNAPanel vp) {
+               if (!_colorMapValues.equals("")) {
+                       File f = new File(_colorMapValues);
+                       if(f.exists() && !f.isDirectory()) { 
+                               try {
+                                       vp.readValues(new FileReader(f));
+                                       vp.drawColorMap(true);
+                                       System.err.println("Loaded "+_colorMapValues);
+                               } catch (FileNotFoundException e) {
+                                       e.printStackTrace();
+                               }
+                       }
+                       else
+                       {
+                               String[] values = _colorMapValues.split("[;,]");
+                               ArrayList<Double> vals = new ArrayList<Double>();
+                               for (int i = 0; i < values.length; i++) {
+                                       try {
+                                               vals.add(Double.parseDouble(values[i]));
+                                       } catch (Exception e) {
+       
+                                       }
+                               }
+                               Double[] result = new Double[vals.size()];
+                               vals.toArray(result);
+                               vp.setColorMapValues(result);
+                       }
+                       ModeleColorMap cm = vp.getColorMap();
+                       if (_colorMapMin != Double.MIN_VALUE) {
+                               // System.out.println("[A]"+_colorMapMin);
+                               cm.setMinValue(_colorMapMin);
+                       }
+                       if (_colorMapMax != Double.MAX_VALUE) {
+                               cm.setMaxValue(_colorMapMax);
+                       }
+                       _drawColorMap = true;
+               }
+       }
+
+       private void applyBasesCustomStyles(VARNAPanel vp) {
+               String[] baseStyles = _customBases.split(";");
+               for (int i = 0; i < baseStyles.length; i++) {
+                       String thisStyle = baseStyles[i];
+                       String[] data = thisStyle.split(":");
+                       try {
+                               if (data.length == 2) {
+                                       int baseNum = Integer.parseInt(data[0]);
+                                       int index = _mainSurface.getRNA().getIndexFromBaseNumber(
+                                                       baseNum);
+                                       if (index != -1) {
+                                               String style = data[1];
+                                               ModelBaseStyle msb = vp.getRNA().get_listeBases()
+                                                               .get(index).getStyleBase().clone();
+                                               msb.assignParameters(style);
+                                               vp.getRNA().get_listeBases().get(index)
+                                                               .setStyleBase(msb);
+                                       }
+                               }
+                       } catch (Exception e) {
+                               System.err.println("ApplyBasesCustomStyle: " + e.toString());
+                       }
+               }
+       }
+
+       private void applyHighlightRegion(VARNAPanel vp) {
+               String[] regions = _highlightRegion.split(";");
+               for (int i = 0; i < regions.length; i++) {
+                       String region = regions[i];
+                       try {
+                               HighlightRegionAnnotation nt = HighlightRegionAnnotation
+                                               .parseHighlightRegionAnnotation(region, vp);
+                               if (nt != null) {
+                                       vp.addHighlightRegion(nt);
+                               }
+                       } catch (Exception e) {
+                               System.err.println("Error in applyHighlightRegion: " + e.toString());
+                       }
+               }
+       }
+
+       private Dimension parseDimension(String s) {
+               Dimension d = new Dimension(0, 0);
+               try {
+                       s = s.toLowerCase();
+                       int i = s.indexOf('x');
+                       String w = s.substring(0, i);
+                       String h = s.substring(i + 1);
+                       d.width = Integer.parseInt(w);
+                       d.height = Integer.parseInt(h);
+               } catch (NumberFormatException e) {
+               }
+               return d;
+       }
+
+       private void applyBPsCustomStyles(VARNAPanel vp) {
+               String[] baseStyles = _customBPs.split(";");
+               for (int i = 0; i < baseStyles.length; i++) {
+                       String thisStyle = baseStyles[i];
+                       String[] data = thisStyle.split(":");
+                       try {
+                               if (data.length == 2) {
+                                       String indices = data[0];
+                                       String style = data[1];
+                                       String[] data2 = indices.split(",");
+                                       if (data2.length == 2) {
+                                               String s1 = data2[0];
+                                               String s2 = data2[1];
+                                               if (s1.startsWith("(") && s2.endsWith(")")) {
+                                                       int a = Integer.parseInt(s1.substring(1));
+                                                       int b = Integer.parseInt(s2.substring(0,
+                                                                       s2.length() - 1));
+                                                       ModeleBP msbp = vp.getRNA().getBPStyle(a, b);
+                                                       if (msbp != null) {
+                                                               msbp.assignParameters(style);
+                                                       }
+                                               }
+                                       }
+                               }
+                       } catch (Exception e) {
+                               System.err.println("ApplyBPsCustomStyle: " + e.toString());
+                       }
+               }
+       }
+
+       private void applyChemProbs(VARNAPanel vp) {
+               String[] chemProbs = _chemProbs.split(";");
+               for (int i = 0; i < chemProbs.length; i++) {
+                       String thisAnn = chemProbs[i];
+                       String[] data = thisAnn.split(":");
+                       try {
+                               if (data.length == 2) {
+                                       String indices = data[0];
+                                       String style = data[1];
+                                       String[] data2 = indices.split("-");
+                                       if (data2.length == 2) {
+                                               int a = Integer.parseInt(data2[0]);
+                                               int b = Integer.parseInt(data2[1]);
+                                               int c = vp.getRNA().getIndexFromBaseNumber(a);
+                                               int d = vp.getRNA().getIndexFromBaseNumber(b);
+                                               ArrayList<ModeleBase> mbl = vp.getRNA()
+                                                               .get_listeBases();
+                                               ChemProbAnnotation cpa = new ChemProbAnnotation(
+                                                               mbl.get(c), mbl.get(d), style);
+                                               vp.getRNA().addChemProbAnnotation(cpa);
+                                       }
+                               }
+                       } catch (Exception e) {
+                               System.err.println("ChempProbs: " + e.toString());
+                       }
+               }
+       }
+
+       private void applyAuxBPs(VARNAPanel vp) {
+               String[] baseStyles = _auxBPs.split(";");
+
+               for (int i = 0; i < baseStyles.length; i++) {
+                       String thisStyle = baseStyles[i];
+                       String[] data = thisStyle.split(":");
+                       try {
+                               if (data.length >= 1) {
+                                       String indices = data[0];
+                                       String[] data2 = indices.split(",");
+                                       if (data2.length == 2) {
+                                               String s1 = data2[0];
+                                               String s2 = data2[1];
+                                               if (s1.startsWith("(") && s2.endsWith(")")) {
+                                                       int a = Integer.parseInt(s1.substring(1));
+                                                       int b = Integer.parseInt(s2.substring(0,
+                                                                       s2.length() - 1));
+                                                       int c = vp.getRNA().getIndexFromBaseNumber(a);
+                                                       int d = vp.getRNA().getIndexFromBaseNumber(b);
+
+                                                       ModeleBP msbp = new ModeleBP(vp.getRNA()
+                                                                       .get_listeBases().get(c), vp.getRNA()
+                                                                       .get_listeBases().get(d));
+                                                       if (data.length >= 2) {
+                                                               String style = data[1];
+                                                               msbp.assignParameters(style);
+                                                       }
+                                                       vp.getRNA()
+                                                                       .addBPToStructureUsingNumbers(a, b, msbp);
+                                               }
+                                       }
+                               }
+                       } catch (ExceptionModeleStyleBaseSyntaxError e1) {
+                               System.err.println("AuxApplyBPs: " + e1.toString());
+                       } catch (ExceptionParameterError e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+               }
+       }
+
+       private void applyFlips(VARNAPanel vp) {
+               String[] flips = _flip.split(";");
+               for (String s: flips)
+               {
+                       if (!s.isEmpty())
+                       {
+                               try{
+                                       String[] data = s.split("-");
+                                       int number = -1;
+                                       if (data.length==1)
+                                       {
+                                               number = Integer.parseInt(data[0]);                                     
+                                       }
+                                       else if (data.length==2)
+                                       {
+                                               number = Integer.parseInt(data[1]);
+                                       }
+                                       if (number!=-1)
+                                       {
+                                               int i = vp.getRNA().getIndexFromBaseNumber(number);
+                                               Point h = vp.getRNA().getExteriorHelix(i);
+                                               vp.getRNA().flipHelix(h);
+                                       }
+                               } catch (Exception e) {
+                                       System.err.println("Flip Helices: " + e.toString());
+                               }
+                       }
+               }
+       }
+       
+       /**
+        * Format:
+        * string:[type=[H|B|L|P]|x=double|y=double|anchor=int|size=int|color
+        * =Color];
+        * 
+        * @param vp
+        */
+       private void applyAnnotations(VARNAPanel vp) {
+               String[] annotations = _annotations.split(";");
+               for (int i = 0; i < annotations.length; i++) {
+                       String thisAnn = annotations[i];
+                       TextAnnotation ann = TextAnnotation.parse(thisAnn, vp);
+                       vp.addAnnotation(ann);
+               }
+       }
+
+
+}
+
+
diff --git a/src2/fr/orsay/lri/varna/models/VARNAEdits.java b/src2/fr/orsay/lri/varna/models/VARNAEdits.java
new file mode 100644 (file)
index 0000000..bf6823a
--- /dev/null
@@ -0,0 +1,403 @@
+package fr.orsay.lri.varna.models;
+
+import java.awt.Point;
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+
+import javax.swing.undo.AbstractUndoableEdit;
+import javax.swing.undo.CannotRedoException;
+import javax.swing.undo.CannotUndoException;
+import javax.swing.undo.UndoableEdit;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.applications.templateEditor.GraphicalTemplateElement;
+import fr.orsay.lri.varna.applications.templateEditor.TemplatePanel;
+import fr.orsay.lri.varna.applications.templateEditor.TemplateEdits.ElementEdgeMoveTemplateEdit;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VARNAEdits {
+       public static final double MAX_DISTANCE= 55.0;
+       public static  class BasesShiftEdit extends AbstractUndoableEdit
+       {
+               private ArrayList<Integer> _indices; 
+               private double _dx; 
+               private double _dy;
+               private VARNAPanel _vp;
+               public BasesShiftEdit(ArrayList<Integer> indices, double dx, double dy, VARNAPanel p)
+               {
+                       _indices = indices;
+                       _dx = dx;
+                       _dy = dy;
+                       _vp = p;
+               }
+               public void undo() throws CannotUndoException {
+                       for (int index: _indices)
+                       {
+                               ModeleBase mb = _vp.getRNA().getBaseAt(index);
+                           _vp.getRNA().setCoord(index,new Point2D.Double(mb.getCoords().x-_dx,mb.getCoords().y-_dy));
+                           _vp.getRNA().setCenter(index,new Point2D.Double(mb.getCenter().x-_dx,mb.getCenter().y-_dy));
+                       }
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       for (int index: _indices)
+                       {
+                               ModeleBase mb = _vp.getRNA().getBaseAt(index);
+                           _vp.getRNA().setCoord(index,new Point2D.Double(mb.getCoords().x+_dx,mb.getCoords().y+_dy));
+                           _vp.getRNA().setCenter(index,new Point2D.Double(mb.getCenter().x-_dx,mb.getCenter().y-_dy));
+                       }
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Base #"+_indices+" shifted"; }
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       if (anEdit instanceof BasesShiftEdit)
+                       {
+                               BasesShiftEdit e = (BasesShiftEdit) anEdit;
+                               if (e._indices.equals(_indices))
+                               {
+                                       Point2D.Double tot = new Point2D.Double(_dx+e._dx,_dy+e._dy);
+                                       if (tot.distance(0.0, 0.0)<MAX_DISTANCE)
+                                       {
+                                               _dx = _dx+e._dx;
+                                               _dy = _dy+e._dy;
+                                               return true;
+                                       }
+                               }
+                       }
+                       return false;
+               }
+       };
+
+       public static  class HelixRotateEdit extends AbstractUndoableEdit
+       {
+               private double _delta; 
+               private double _base; 
+               private double _pLimL; 
+               private double _pLimR; 
+               private Point _h; 
+               private Point _ml; 
+               private VARNAPanel _vp;
+               public HelixRotateEdit(double delta, double base, double pLimL, double pLimR, Point h, Point ml, VARNAPanel vp)
+               {
+                       _delta = delta;
+                       _base = base;
+                       _pLimL = pLimL;
+                       _pLimR = pLimR;
+                       _h = h;
+                       _ml = ml;
+                       _vp = vp;
+               }
+               public void undo() throws CannotUndoException {
+                       _vp.getVARNAUI().UIRotateEverything(-_delta, _base, _pLimL, _pLimR, _h, _ml);
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       _vp.getVARNAUI().UIRotateEverything(_delta, _base, _pLimL, _pLimR, _h, _ml);
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Helix #"+_h+" rotated angle:"+_delta; }
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       if (anEdit instanceof HelixRotateEdit)
+                       {
+                               HelixRotateEdit e = (HelixRotateEdit) anEdit;
+                               if (e._h.equals(_h))
+                               {
+                                       double totAngle = e._delta+_delta;
+                                       while (totAngle>Math.PI)
+                                       { totAngle -= 2.0*Math.PI; }
+                                       if (Math.abs(totAngle)<Math.PI/8.0)
+                                       {
+                                               _delta=totAngle;
+                                               return true;
+                                       }
+                               }
+                       }
+                       return false;
+               }
+       };
+       
+       
+       public static  class SingleBaseMoveEdit extends AbstractUndoableEdit
+       {
+               private int _index; 
+               private double _ox; 
+               private double _oy;
+               private double _nx; 
+               private double _ny;
+               private VARNAPanel _vp;
+               public SingleBaseMoveEdit(int index, double nx, double ny, VARNAPanel p)
+               {
+                       _index = index;
+                       ModeleBase mb = p.getRNA().getBaseAt(index);
+                       _ox = mb.getCoords().x;
+                       _oy = mb.getCoords().y;
+                       _nx = nx;
+                       _ny = ny;
+                       _vp = p;
+               }
+               public void undo() throws CannotUndoException {
+                       _vp.getRNA().setCoord(_index,new Point2D.Double(_ox,_oy));
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       _vp.getRNA().setCoord(_index,new Point2D.Double(_nx,_ny));
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Base #"+_index+" moved"; }
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       if (anEdit instanceof SingleBaseMoveEdit)
+                       {
+                               SingleBaseMoveEdit e = (SingleBaseMoveEdit) anEdit;
+                               if (e._index==_index)
+                               {
+                                       Point2D.Double po1 = new Point2D.Double(_ox,_oy);
+                                       Point2D.Double pn1 = new Point2D.Double(_nx,_ny);
+                                       Point2D.Double po2 = new Point2D.Double(e._ox,e._oy);
+                                       Point2D.Double pn2 = new Point2D.Double(e._nx,e._ny);
+                                       if ((pn1.equals(po2))&&(po1.distance(pn2)<MAX_DISTANCE))
+                                       {
+                                               _nx = e._nx;
+                                               _ny = e._ny;
+                                               return true;
+                                       }
+                               }
+                       }
+                       return false;
+               }
+       };
+
+       public static  class HelixFlipEdit extends AbstractUndoableEdit
+       {
+               private Point _h; 
+               private VARNAPanel _vp;
+               public HelixFlipEdit(Point h, VARNAPanel vp)
+               {
+                       _h = h;
+                       _vp = vp;
+               }
+               public void undo() throws CannotUndoException {
+                       _vp.getVARNAUI().UIFlipHelix(_h);
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       _vp.getVARNAUI().UIFlipHelix(_h);
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Helix #"+_h+" flipped";}
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       return false;
+               }
+       };
+
+       public static  class AddBPEdit extends AbstractUndoableEdit
+       {
+               private ModeleBP _msbp; 
+               private int _i;
+               private int _j;
+               private VARNAPanel _vp;
+               public AddBPEdit(int i, int j, ModeleBP msbp, VARNAPanel vp)
+               {
+                       _msbp = msbp;
+                       _i = i;
+                       _j = j;
+                       _vp = vp;
+               }
+               public void undo() throws CannotUndoException {
+                       _vp.getRNA().removeBP(_msbp);
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       _vp.getRNA().addBP(_i,_j,_msbp);
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Add BP ("+_i+","+_j+")";}
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       return false;
+               }
+       };
+
+       public static  class RemoveBPEdit extends AbstractUndoableEdit
+       {
+               private ModeleBP _msbp; 
+               private int _i;
+               private int _j;
+               private VARNAPanel _vp;
+               public RemoveBPEdit( int i, int j,ModeleBP msbp, VARNAPanel vp)
+               {
+                       _msbp = msbp;
+                       _i = i;
+                       _j = j;
+                       _vp = vp;
+               }
+               public void undo() throws CannotUndoException {
+                       _vp.getRNA().addBP(_i,_j,_msbp);
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       _vp.getRNA().removeBP(_msbp);
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Remove BP ("+_i+","+_j+")";}
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       return false;
+               }
+       };
+
+       public static  class RescaleRNAEdit extends AbstractUndoableEdit
+       {
+               private double _factor;
+               private VARNAPanel _vp;
+               public RescaleRNAEdit( double angle, VARNAPanel vp)
+               {
+                       _factor = angle;
+                       _vp = vp;
+               }
+               public void undo() throws CannotUndoException {
+                       _vp.getRNA().rescale(1.0/_factor);
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       _vp.getRNA().rescale(_factor);
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Rescale RNA factor:"+_factor+"";}
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       if (anEdit instanceof RescaleRNAEdit)
+                       {
+                               RescaleRNAEdit e = (RescaleRNAEdit) anEdit;
+                               double cumFact = _factor*e._factor;
+                               if (cumFact>.7 || cumFact<1.3)
+                               {
+                                       _factor *= e._factor;
+                                       return true;
+                               }
+                       }
+                       return false;
+               }
+       };
+
+       public static  class RotateRNAEdit extends AbstractUndoableEdit
+       {
+               private double _angle;
+               private VARNAPanel _vp;
+               public RotateRNAEdit( double angle, VARNAPanel vp)
+               {
+                       _angle = angle;
+                       _vp = vp;
+               }
+               public void undo() throws CannotUndoException {
+                       _vp.getRNA().globalRotation(-_angle);
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       _vp.getRNA().globalRotation(_angle);
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Rotate RNA angle:"+_angle+"";}
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       if (anEdit instanceof RotateRNAEdit)
+                       {
+                               RotateRNAEdit e = (RotateRNAEdit) anEdit;
+                               if (Math.abs(_angle+e._angle)<30)
+                               {
+                                       _angle += e._angle;
+                                       return true;
+                               }
+                       }
+                       return false;
+               }
+       };
+
+       public static  class RedrawEdit extends AbstractUndoableEdit
+       {
+               private int _prevMode;
+               private int _newMode;
+               private boolean _prevFlat;
+               private boolean _newFlat;
+               private ArrayList<Point2D.Double> _backupCoords = new ArrayList<Point2D.Double>();
+               private ArrayList<Point2D.Double> _backupCenters = new ArrayList<Point2D.Double>();
+               private VARNAPanel _vp;
+               
+
+               public RedrawEdit(VARNAPanel vp,boolean newFlat)
+               {
+                       this(vp.getRNA().getDrawMode(),vp,newFlat);
+               }
+
+               public RedrawEdit(int newMode, VARNAPanel vp)
+               {
+                       this(newMode,vp,vp.getFlatExteriorLoop());
+               }
+       
+               public RedrawEdit(int newMode, VARNAPanel vp, boolean newFlat)
+               {
+                       _vp = vp;
+                       _newMode = newMode;
+                       _newFlat = newFlat;
+                       _prevFlat = _vp.getFlatExteriorLoop();
+                       for (ModeleBase mb: _vp.getRNA().get_listeBases())
+                       {
+                               _backupCoords.add(new Point2D.Double(mb.getCoords().x,mb.getCoords().y));
+                               _backupCenters.add(new Point2D.Double(mb.getCenter().x,mb.getCenter().y));
+                       }
+                       _prevMode = _vp.getDrawMode();
+               }
+               public void undo() throws CannotUndoException {
+                       RNA r = _vp.getRNA();
+                       _vp.setFlatExteriorLoop(_prevFlat);
+                       r.setDrawMode(_prevMode);
+                       for (int index =0;index<_vp.getRNA().get_listeBases().size();index++)
+                       {
+                           Point2D.Double oldCoord = _backupCoords.get(index);
+                           Point2D.Double oldCenter = _backupCenters.get(index);
+                           r.setCoord(index, oldCoord);
+                           r.setCenter(index, oldCenter);
+                       }
+                       _vp.repaint();                  
+               }
+               public void redo() throws CannotRedoException {
+                       try {
+                               _vp.setFlatExteriorLoop(_newFlat);
+                               _vp.getRNA().drawRNA(_newMode,_vp.getConfig());
+                       } catch (ExceptionNAViewAlgorithm e) {
+                               e.printStackTrace();
+                       }
+                       _vp.repaint();
+               }
+               public boolean canUndo() { return true; }
+               public boolean canRedo() { return true; }
+               public String getPresentationName() { return "Redraw whole RNA";}
+               public boolean addEdit(UndoableEdit anEdit)
+               {
+                       return false;
+               }
+       };
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/annotations/ChemProbAnnotation.java b/src2/fr/orsay/lri/varna/models/annotations/ChemProbAnnotation.java
new file mode 100644 (file)
index 0000000..83c2158
--- /dev/null
@@ -0,0 +1,260 @@
+package fr.orsay.lri.varna.models.annotations;
+
+import java.awt.Color;
+import java.awt.geom.Point2D;
+import java.io.Serializable;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+
+public class ChemProbAnnotation implements Serializable {
+
+       public static final String HEADER_TEXT = "ChemProbAnnotation";
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 5833315460145031242L;
+
+
+       public enum ChemProbAnnotationType 
+       {
+               TRIANGLE,
+               ARROW,
+               PIN,
+               DOT;
+       };
+       
+       public static double DEFAULT_INTENSITY = 1.0;
+       public static ChemProbAnnotationType DEFAULT_TYPE = ChemProbAnnotationType.ARROW;
+       public static Color DEFAULT_COLOR = Color.blue.darker();
+
+       private ModeleBase _mbfst;
+       private ModeleBase _mbsnd;
+       private Color _color;
+       private double _intensity;
+       private ChemProbAnnotationType _type;
+       private boolean _outward;
+       
+       public static String XML_ELEMENT_NAME = "ChemProbAnnotation";
+       public static String XML_VAR_INDEX5_NAME = "Index5";
+       public static String XML_VAR_INDEX3_NAME = "Index3";
+       public static String XML_VAR_COLOR_NAME = "Color";
+       public static String XML_VAR_INTENSITY_NAME = "Intensity";
+       public static String XML_VAR_TYPE_NAME = "Type";
+       public static String XML_VAR_OUTWARD_NAME = "Outward";
+
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_INDEX5_NAME,"CDATA",""+_mbfst.getIndex());
+               atts.addAttribute("","",XML_VAR_INDEX3_NAME,"CDATA",""+_mbsnd.getIndex());
+               atts.addAttribute("","",XML_VAR_COLOR_NAME,"CDATA",XMLUtils.toHTMLNotation(_color));
+               atts.addAttribute("","",XML_VAR_INTENSITY_NAME,"CDATA",""+_intensity);
+               atts.addAttribute("","",XML_VAR_TYPE_NAME,"CDATA",""+_type);
+               atts.addAttribute("","",XML_VAR_OUTWARD_NAME,"CDATA",""+_outward);
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }
+
+       
+       public ChemProbAnnotation(ModeleBase mbfst, ModeleBase mbsnd, String styleDesc) {
+               this(mbfst,mbsnd);
+               applyStyle(styleDesc);
+       }
+
+       public ChemProbAnnotation(ModeleBase mbfst, ModeleBase mbsnd) {
+               this(mbfst,mbsnd,ChemProbAnnotation.DEFAULT_TYPE,ChemProbAnnotation.DEFAULT_INTENSITY);
+       }
+
+       public ChemProbAnnotation(ModeleBase mbfst, ModeleBase mbsnd, double intensity) {
+               this(mbfst,mbsnd,ChemProbAnnotation.DEFAULT_TYPE,intensity);
+       }
+
+       public ChemProbAnnotation(ModeleBase mbfst, ModeleBase mbsnd, ChemProbAnnotationType type) {
+               this(mbfst,mbsnd,type,ChemProbAnnotation.DEFAULT_INTENSITY);
+       }
+       
+       public ChemProbAnnotation(ModeleBase mbfst, ModeleBase mbsnd, ChemProbAnnotationType type, double intensity) {
+               this(mbfst,mbsnd, type, intensity, DEFAULT_COLOR, true);
+       }
+
+       public ChemProbAnnotation(ModeleBase mbfst, ModeleBase mbsnd, ChemProbAnnotationType type, double intensity, Color color, boolean out) {
+               if (mbfst.getIndex()>mbsnd.getIndex())
+               {
+                       ModeleBase tmp = mbsnd;
+                       mbsnd = mbfst;
+                       mbfst = tmp;
+               }
+               _mbfst = mbfst;
+               _mbsnd = mbsnd;
+               _type = type;
+               _intensity = intensity;
+               _color = color;
+               _outward = out;
+       }
+
+       public boolean isOut()
+       {
+               return _outward; 
+       }
+       
+       public void setOut(boolean b)
+       {
+               _outward = b;
+       }
+
+       public Color getColor()
+       {
+               return _color; 
+       }
+
+       public double getIntensity()
+       {
+               return _intensity; 
+       }
+       
+       public ChemProbAnnotationType getType()
+       {
+               return _type; 
+       }
+       
+       public void setColor(Color c){
+               _color = c;
+       }
+
+       public void setIntensity(double d){
+               _intensity = d;
+       }
+       
+       public Point2D.Double getAnchorPosition()
+       {
+               Point2D.Double result = new Point2D.Double(
+                               (_mbfst.getCoords().x+_mbsnd.getCoords().x)/2.0,
+                               (_mbfst.getCoords().y+_mbsnd.getCoords().y)/2.0);
+               return result;
+       }
+       
+       public Point2D.Double getDirVector()
+       {
+               Point2D.Double norm = getNormalVector();
+               Point2D.Double result = new Point2D.Double(-norm.y,norm.x);
+               Point2D.Double anchor = getAnchorPosition();
+               Point2D.Double center = new Point2D.Double(
+                               (_mbfst.getCenter().x+_mbsnd.getCenter().x)/2.0,
+                               (_mbfst.getCenter().y+_mbsnd.getCenter().y)/2.0);
+               Point2D.Double vradius = new Point2D.Double(
+                               (center.x-anchor.x)/2.0,
+                               (center.y-anchor.y)/2.0);
+               if (_outward)
+               {
+                 if (result.x*vradius.x+result.y*vradius.y>0)
+                 {
+                       return new Point2D.Double(-result.x,-result.y);
+                 }
+               }
+               else
+               {
+                         if (result.x*vradius.x+result.y*vradius.y<0)
+                         {
+                               return new Point2D.Double(-result.x,-result.y);
+                         }                     
+               }
+               return result;          
+       }
+       public Point2D.Double getNormalVector()
+       {
+               Point2D.Double tmp;
+               if (_mbfst==_mbsnd)
+               {
+                       tmp = new Point2D.Double(
+                                       (-(_mbsnd.getCenter().y-_mbsnd.getCoords().y)),
+                                       ((_mbsnd.getCenter().x-_mbsnd.getCoords().x)));                 
+               }
+               else
+               {
+                       tmp = new Point2D.Double(
+                               (_mbsnd.getCoords().x-_mbfst.getCoords().x)/2.0,
+                               (_mbsnd.getCoords().y-_mbfst.getCoords().y)/2.0);
+               }
+               
+               double norm = tmp.distance(0, 0);
+               Point2D.Double result = new Point2D.Double(tmp.x/norm,tmp.y/norm);
+               return result;                          
+       }
+       
+       public static ChemProbAnnotationType annotTypeFromString(String value)
+       {
+               if (value.toLowerCase().equals("arrow"))
+               {return ChemProbAnnotationType.ARROW;}
+               else if (value.toLowerCase().equals("triangle"))
+               {return ChemProbAnnotationType.TRIANGLE;}
+               else if (value.toLowerCase().equals("pin"))
+               {return ChemProbAnnotationType.PIN;}
+               else if (value.toLowerCase().equals("dot"))
+               {return ChemProbAnnotationType.DOT;}
+               else
+               {return ChemProbAnnotationType.ARROW;}
+       }
+       
+       
+       public void applyStyle(String styleDesc)
+       {
+               String[] chemProbs = styleDesc.split(",");
+               for (int i = 0; i < chemProbs.length; i++) {
+                       String thisStyle = chemProbs[i];
+                       String[] data = thisStyle.split("=");
+                       if (data.length==2)
+                       {
+                               String name = data[0];
+                               String value = data[1];
+                               if (name.toLowerCase().equals("color"))
+                               {
+                                       Color c = Color.decode(value);
+                                       if (c==null)
+                                       { c = _color; }
+                                       setColor(c);
+                               }
+                               else if (name.toLowerCase().equals("intensity"))
+                               {
+                                       _intensity = Double.parseDouble(value);
+                               }
+                               else if (name.toLowerCase().equals("dir"))
+                               {
+                                       _outward = value.toLowerCase().equals("out");
+                               }
+                               else if (name.toLowerCase().equals("glyph"))
+                               {
+                                       _type= annotTypeFromString(value);
+                               }
+                       }
+               }
+       }
+       
+       public void setType(ChemProbAnnotationType s)
+       {
+               _type = s;
+       }
+
+       public ChemProbAnnotation clone()
+       {
+               ChemProbAnnotation result = new ChemProbAnnotation(this._mbfst,this._mbsnd);
+               result._intensity = _intensity;
+               result._type = _type;
+               result._color= _color;
+               result._outward = _outward;
+               return result;
+       }
+       
+       public String toString()
+       {
+               return "Chem. prob. "+this._type+" Base#"+this._mbfst.getBaseNumber()+"-"+this._mbsnd.getBaseNumber();
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/annotations/HighlightRegionAnnotation.java b/src2/fr/orsay/lri/varna/models/annotations/HighlightRegionAnnotation.java
new file mode 100644 (file)
index 0000000..1e671bd
--- /dev/null
@@ -0,0 +1,376 @@
+package fr.orsay.lri.varna.models.annotations;
+
+import java.awt.Color;
+import java.awt.Shape;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Point2D;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurClicMovement;
+import fr.orsay.lri.varna.models.VARNAConfigLoader;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.models.rna.VARNAPoint;
+import fr.orsay.lri.varna.utils.XMLUtils;
+import fr.orsay.lri.varna.views.VueHighlightRegionEdit;
+import fr.orsay.lri.varna.views.VueUI;
+
+public class HighlightRegionAnnotation implements Serializable {
+       
+       public static final String HEADER_TEXT = "HighlightRegionAnnotation";
+
+       private static final long serialVersionUID = 7087014168028684775L;
+       public static final Color DEFAULT_OUTLINE_COLOR = Color.decode("#6ed86e");
+       public static final Color DEFAULT_FILL_COLOR = Color.decode("#bcffdd");
+       public static final double DEFAULT_RADIUS = 16.0;
+       
+       private Color _outlineColor = DEFAULT_OUTLINE_COLOR;
+       private Color _fillColor = DEFAULT_FILL_COLOR;
+       private double _radius = DEFAULT_RADIUS;
+       private ArrayList<ModeleBase> _bases;
+       
+       public static String XML_ELEMENT_NAME = "region";
+       public static String XML_VAR_OUTLINE_NAME = "outline";
+       public static String XML_VAR_FILL_NAME = "fill";
+       public static String XML_VAR_RADIUS_NAME = "radius";
+
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_OUTLINE_NAME,"CDATA",""+XMLUtils.toHTMLNotation(_outlineColor));
+               atts.addAttribute("","",XML_VAR_FILL_NAME,"CDATA",""+XMLUtils.toHTMLNotation(_fillColor));
+               atts.addAttribute("","",XML_VAR_RADIUS_NAME,"CDATA",""+_radius);
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               XMLUtils.toXML(hd, _bases);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }
+
+  public HighlightRegionAnnotation(RNA r, int startIndex, int stopIndex)
+  {
+         this(r.getBasesBetween(startIndex, stopIndex));
+  }
+
+  public HighlightRegionAnnotation()
+  {
+         this(new ArrayList<ModeleBase>());
+  }
+
+  public HighlightRegionAnnotation(ArrayList<ModeleBase> b)
+  {
+         this(b,DEFAULT_FILL_COLOR,DEFAULT_OUTLINE_COLOR,DEFAULT_RADIUS);
+  }
+  
+  public HighlightRegionAnnotation(ArrayList<ModeleBase> b,Color fill, Color outline, double radius)
+  {
+         _bases = b;
+         _fillColor = fill;
+         _outlineColor = outline;
+         _radius = radius;
+  }
+  
+       public HighlightRegionAnnotation clone()
+       {
+               return new HighlightRegionAnnotation(_bases,_fillColor,_outlineColor,_radius);
+       }
+       
+  public int getMinIndex()
+  {
+         int min = Integer.MAX_VALUE;
+         for (ModeleBase mb : _bases)
+         {
+                 min = Math.min(min, mb.getIndex());
+         }
+         return min;
+  }
+
+  public int getMaxIndex()
+  {
+         int max = Integer.MIN_VALUE;
+         for (ModeleBase mb : _bases)
+         {
+                 max = Math.max(max, mb.getIndex());
+         }
+         return max;
+  }
+
+  
+  public void setOutlineColor(Color c)
+  {
+         _outlineColor = c;  
+  }
+
+  public ArrayList<ModeleBase> getBases()
+  {
+         return _bases;
+  }
+
+  public void setBases(ArrayList<ModeleBase> b)
+  {
+         _bases = b;
+  }
+  
+  public void setFillColor(Color c)
+  {
+         _fillColor = c;  
+  }
+
+  public Color getFillColor()
+  {
+         return _fillColor;  
+  }
+  public Color getOutlineColor()
+  {
+         return _outlineColor;  
+  }
+
+  public double getRadius()
+  {
+         return _radius;  
+  }
+
+  public void setRadius(double v)
+  {
+         _radius = v;  
+  }
+  
+  public static final int NUM_STEPS_ROUNDED_CORNERS = 16;
+  
+  private Point2D.Double symImage(Point2D.Double p, Point2D.Double center)
+  {
+         return new Point2D.Double(2.*center.x-p.x, 2.*center.y-p.y);
+  }
+  
+  private LinkedList<Point2D.Double> buildRoundedCorner(Point2D.Double p1, Point2D.Double p2, Point2D.Double anotherPoint)
+  {
+               LinkedList<Point2D.Double> result = new LinkedList<Point2D.Double>();
+               Point2D.Double m = new Point2D.Double((p1.x+p2.x)/2.0,(p1.y+p2.y)/2.0);
+               double rad = p1.distance(p2)/2.;
+               double angle = Math.atan2(p1.y-m.y, p1.x-m.x);
+               
+               double incr = Math.PI/((double)NUM_STEPS_ROUNDED_CORNERS+1);
+               
+               Point2D.Double pdir = new Point2D.Double(m.x+rad*Math.cos(angle+Math.PI/2.),m.y+rad*Math.sin(angle+Math.PI/2.));
+               if (pdir.distance(anotherPoint)<p1.distance(anotherPoint))
+               { incr = -incr; }
+               
+               for(int k=1;k<=NUM_STEPS_ROUNDED_CORNERS;k++)
+               {
+                       double angle2 = angle+k*incr;
+                       Point2D.Double interForward = new Point2D.Double(m.x+rad*Math.cos(angle2),m.y+rad*Math.sin(angle2));
+                       result.addLast(interForward);
+               }
+               return result;
+  }
+  
+  
+       public GeneralPath getShape(Point2D.Double[] realCoords,Point2D.Double[] realCenters, double scaleFactor)
+       {
+               GeneralPath p = new GeneralPath();
+               LinkedList<Point2D.Double> pointList = new LinkedList<Point2D.Double>();
+               for (int i = 0;i<getBases().size();i++)
+               { 
+                       int j1 = getBases().get(i).getIndex();
+                       {
+                               int j0 = j1-1;
+                               int j2 = j1+1;
+                               Point2D.Double p0 = new Point2D.Double(0., 0.);
+                               Point2D.Double p1 = new Point2D.Double(0., 0.);                 
+                               Point2D.Double p2 = new Point2D.Double(0., 0.);
+                               if (i==0)
+                               {
+                                       // Single point
+                                       if (i==getBases().size()-1)
+                                       {
+                                               p1 = realCoords[j1];                    
+                                               p0 = new Point2D.Double(p1.x+scaleFactor *getRadius(), p1.y);
+                                               p2 = new Point2D.Double(p1.x-scaleFactor *getRadius(), p1.y);
+                                       }
+                                       else
+                                       {
+                                               p1 = realCoords[j1];                    
+                                               p2 = realCoords[j2];
+                                               p0 = symImage(p2, p1);
+                                       }
+                               }
+                               else if (i==getBases().size()-1)
+                               {
+                                       p0 = realCoords[j0];
+                                       p1 = realCoords[j1];                            
+                                       p2 = symImage(p0, p1);;                                 
+                               }
+                               else
+                               {
+                                       p0 = realCoords[j0];
+                                       p1 = realCoords[j1];                    
+                                       p2 = realCoords[j2];
+                               }
+
+                               double dist1 = p2.distance(p1);
+                               Point2D.Double v1 = new Point2D.Double((p2.x-p1.x)/dist1,(p2.y-p1.y)/dist1);
+                               Point2D.Double vn1 = new Point2D.Double(v1.y,-v1.x);
+                               double dist2 = p1.distance(p0);
+                               Point2D.Double v2 = new Point2D.Double((p1.x-p0.x)/dist2,(p1.y-p0.y)/dist2);
+                               Point2D.Double vn2 = new Point2D.Double(v2.y,-v2.x);
+                               double h = (new Point2D.Double(vn2.x-vn1.x,vn2.y-vn1.y).distance(new Point2D.Double(0,0))/2.0);
+                               Point2D.Double vn = new Point2D.Double((vn1.x+vn2.x)/2.0,(vn1.y+vn2.y)/2.0);
+                               double D = vn.distance(new Point2D.Double(0.0,0.0));
+                               vn.x/= D;
+                               vn.y/= D;
+                               double nnorm = (D+h*h/D);
+                               
+                               double nnormF = nnorm;
+                               double nnormB = nnorm;
+                               
+                               
+                               Point2D.Double interForward = new Point2D.Double(p1.x + nnormF*scaleFactor *getRadius()*vn.x, 
+                                               p1.y + nnormF*scaleFactor *getRadius()*vn.y);
+                               Point2D.Double interBackward = new Point2D.Double(p1.x - nnormB*scaleFactor *getRadius()*vn.x, 
+                                               p1.y - nnormB*scaleFactor *getRadius()*vn.y);
+
+
+                               if (pointList.size()>0)
+                               {
+                                       Point2D.Double prev1 = pointList.getLast();                     
+                                       Point2D.Double prev2 = pointList.getFirst();
+
+                                       if ((interForward.distance(prev1)+interBackward.distance(prev2))<(interForward.distance(prev2)+interBackward.distance(prev1)))
+                                       {
+                                               pointList.addLast(interForward);
+                                               pointList.addFirst(interBackward);
+                                       }
+                                       else
+                                       {
+                                               pointList.addFirst(interForward);
+                                               pointList.addLast(interBackward);
+                                       }
+                               }
+                               else
+                               {
+                                       pointList.addLast(interForward);
+                                       pointList.addFirst(interBackward);
+                               }
+                       }
+               }
+               if (getBases().size()==1)
+               {
+                       int midl = pointList.size()/2;
+                       Point2D.Double mid = pointList.get(midl);
+                       Point2D.Double apoint = new Point2D.Double(mid.x+1.,mid.y);
+                       LinkedList<Point2D.Double> pointListStart = buildRoundedCorner(pointList.get(midl-1), pointList.get(midl), apoint);
+                       pointList.addAll(midl, pointListStart);
+                       mid = pointList.get(midl);
+                       apoint = new Point2D.Double(mid.x+1.,mid.y);
+                       LinkedList<Point2D.Double> pointListEnd = buildRoundedCorner(pointList.get(pointList.size()-1),pointList.get(0), apoint);
+                       pointList.addAll(0,pointListEnd);                       
+               }
+               else if (getBases().size()>1)
+               {
+                       int midl = pointList.size()/2;
+                       Point2D.Double apoint = symImage(pointList.get(midl),pointList.get(midl-1));
+                       LinkedList<Point2D.Double> pointListStart = buildRoundedCorner(pointList.get(midl-1), pointList.get(midl), apoint);
+                       pointList.addAll(midl, pointListStart);
+                       apoint = symImage(realCoords[getBases().get(getBases().size()-1).getIndex()],
+                                       realCoords[getBases().get(getBases().size()-2).getIndex()]);
+                       LinkedList<Point2D.Double> pointListEnd = buildRoundedCorner(pointList.get(pointList.size()-1),pointList.get(0), apoint);
+                       pointList.addAll(0,pointListEnd);
+               }
+               
+
+               if (pointList.size()>0)
+               {
+                       Point2D.Double point = pointList.get(0);
+                       p.moveTo((float)point.x, (float)point.y);
+
+                       for (int i=1;i<pointList.size();i++)
+                       {
+                               point = pointList.get(i);
+                               p.lineTo((float)point.x, (float)point.y);                               
+                       }
+                       p.closePath();
+               }
+               return p;
+       }
+
+       
+       public static HighlightRegionAnnotation parseHighlightRegionAnnotation(String txt, VARNAPanel vp)
+       {
+               try
+               {
+               String[] parts = txt.split(":");
+               String[] coords = parts[0].split("-");
+               int from = Integer.parseInt(coords[0]);
+               int to = Integer.parseInt(coords[1]);
+               int  i = vp.getRNA().getIndexFromBaseNumber(from);
+               int  j = vp.getRNA().getIndexFromBaseNumber(to);
+               Color fill = HighlightRegionAnnotation.DEFAULT_FILL_COLOR;
+               Color outline = HighlightRegionAnnotation.DEFAULT_OUTLINE_COLOR;
+               double radius = HighlightRegionAnnotation.DEFAULT_RADIUS;
+               ArrayList<ModeleBase> bases = vp.getRNA().getBasesBetween(i, j);
+               if (parts.length>1)
+               {
+               try
+               {
+                       String[] options = parts[1].split(",");
+                       for (int k = 0; k < options.length; k++) 
+                       {
+                               //System.out.println(options[k]);
+                               try
+                               {
+                                       String[] data = options[k].split("=");
+                                       String lhs = data[0].toLowerCase();
+                                       String rhs = data[1];
+                                       if (lhs.equals("fill"))
+                                       {
+                                               fill = VARNAConfigLoader.getSafeColor(rhs, fill);
+                                       }
+                                       else if (lhs.equals("outline"))
+                                       {
+                                               outline = VARNAConfigLoader.getSafeColor(rhs, outline);
+                                       }
+                                       else if (lhs.equals("radius"))
+                                       {
+                                               radius = Double.parseDouble(rhs);
+                                       }       
+                               }
+                               catch(Exception e)
+                               {
+                               }                               
+                       }
+               }
+               catch(Exception e)
+               {
+                       e.printStackTrace();
+               }
+               }
+               return new HighlightRegionAnnotation(bases,fill,outline,radius);
+               }
+       catch(Exception e)
+       {
+               e.printStackTrace();
+       }
+       return null;
+       }
+       
+       public String toString()
+       {
+               //String result = "HighlightRegionAnnotation[";
+               //result += "fill:"+_fillColor.toString();
+               //result += ",outline:"+_outlineColor.toString();
+               //result += ",radius:"+_radius;
+               //return result+"]";
+               String result = "Highlighted region "+getMinIndex()+"-"+getMaxIndex();
+               return result;
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/annotations/TextAnnotation.java b/src2/fr/orsay/lri/varna/models/annotations/TextAnnotation.java
new file mode 100644 (file)
index 0000000..0db63a5
--- /dev/null
@@ -0,0 +1,537 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Universit� Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.annotations;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.geom.Point2D;
+import java.io.Serializable;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.VARNAConfigLoader;
+import fr.orsay.lri.varna.models.rna.ModelBaseStyle;
+import fr.orsay.lri.varna.models.rna.VARNAPoint;
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+
+
+/**
+ * The annotated text model
+ * 
+ * @author Darty@lri.fr
+ * 
+ */
+public class TextAnnotation implements Serializable {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 465236085501860747L;
+       
+       public enum AnchorType{
+               POSITION,
+               BASE,
+               HELIX,
+               LOOP
+       };
+       
+
+       public static final String HEADER_TEXT = "TextAnnotation";
+       
+       /**
+        * default text color
+        */
+       public static final Color DEFAULTCOLOR = Color.black;
+       /**
+        * default text font
+        */
+       public static final Font DEFAULTFONT = new Font("Arial", Font.PLAIN, 12);
+
+       private String _text;
+       private AnchorType _typeAnchor;
+       private Color _color;
+       private double _angle;
+       private Object _anchor;
+       private Font _font;
+       
+       public static String XML_ELEMENT_NAME = "textAnnotation";
+       public static String XML_VAR_TYPE_NAME = "type";
+       public static String XML_VAR_COLOR_NAME = "color";
+       public static String XML_VAR_ANGLE_NAME = "angle";
+       public static String XML_VAR_TEXT_NAME = "text";
+
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_TYPE_NAME,"CDATA",""+_typeAnchor);
+               atts.addAttribute("","",XML_VAR_COLOR_NAME,"CDATA",""+XMLUtils.toHTMLNotation(_color));
+               atts.addAttribute("","",XML_VAR_ANGLE_NAME,"CDATA",""+_angle);
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               atts.clear();
+               hd.startElement("","",XML_VAR_TEXT_NAME,atts);
+               XMLUtils.exportCDATAString(hd, _text);
+               hd.endElement("","",XML_VAR_TEXT_NAME);
+               switch (_typeAnchor)
+               {
+               case POSITION:
+                       ((VARNAPoint)_anchor).toXML(hd,"pos");
+                       break;
+               case BASE:
+                       XMLUtils.toXML(hd, (ModeleBase)_anchor);
+                       break;
+               case HELIX:
+                       XMLUtils.toXML(hd, (ArrayList<ModeleBase>)_anchor);
+                       break;
+               case LOOP:
+                       XMLUtils.toXML(hd, (ArrayList<ModeleBase>)_anchor);
+                       break;
+               }               
+               XMLUtils.toXML(hd, _font);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }
+
+       /**
+        * creates an annoted text on a VARNAPanel with the specified text
+        * 
+        * @param texte Textual content of the annotation
+        */
+       public TextAnnotation(String texte) {
+               _text = texte;
+               _color = DEFAULTCOLOR;
+               _font = DEFAULTFONT;
+               _angle = 0;
+       }
+
+       /**
+        * /** creates an annoted text on a VARNAPanel with the specified text and
+        * is static position
+        * 
+        * @param texte
+        * @param x
+        * @param y
+        */
+       public TextAnnotation(String texte, double x, double y) {
+               this(texte);
+               _anchor = new VARNAPoint(x, y);
+               _typeAnchor = AnchorType.POSITION;
+       }
+
+       /**
+        * creates an annoted text on a VARNAPanel with the specified text fixed to
+        * a base
+        * 
+        * @param texte
+        * @param mb
+        */
+       public TextAnnotation(String texte, ModeleBase mb) {
+               this(texte);
+               _anchor = mb;
+               _typeAnchor = AnchorType.BASE;
+       }
+
+       /**
+        * creates an annoted text on a VARNAPanel with the specified text fixed to
+        * a helix (if type is HELIX) or to a loop (if type is LOOP)
+        * 
+        * @param texte
+        * @param listeBase
+        * @param type
+        * @throws Exception
+        */
+       public TextAnnotation(String texte, ArrayList<ModeleBase> listeBase,
+                       AnchorType type) throws Exception {
+               this(texte);
+               _anchor = listeBase;
+
+               if (type == AnchorType.HELIX)
+                       _typeAnchor = AnchorType.HELIX;
+               else if (type == AnchorType.LOOP)
+                       _typeAnchor = AnchorType.LOOP;
+               else
+                       throw new Exception("Bad argument");
+       }
+
+       /**
+        * creates an annoted text from another one
+        * 
+        * @param textAnnotation
+        */
+       public TextAnnotation(TextAnnotation textAnnotation) {
+               _anchor = textAnnotation.getAncrage();
+               _font = textAnnotation.getFont();
+               _text = textAnnotation.getTexte();
+               _typeAnchor = textAnnotation.getType();
+       }
+
+       /**
+        * 
+        * @return the text
+        */
+       public String getTexte() {
+               return _text;
+       }
+
+       public void setText(String _texte) {
+               this._text = _texte;
+       }
+
+       /**
+        * 
+        * @return the font
+        */
+       public Font getFont() {
+               return _font;
+       }
+
+       public void setFont(Font _font) {
+               this._font = _font;
+       }
+
+       public Object getAncrage() {
+               return _anchor;
+       }
+
+       public void setAncrage(ModeleBase mb) {
+               _anchor = mb;
+               _typeAnchor = AnchorType.BASE;
+       }
+
+       public void setAncrage(double x, double y) {
+               _anchor = new VARNAPoint(x, y);
+               _typeAnchor = AnchorType.POSITION;
+       }
+
+       public void setAncrage(ArrayList<ModeleBase> list, AnchorType type)
+                       throws Exception {
+               _anchor = list;
+               if (type == AnchorType.HELIX)
+                       _typeAnchor = AnchorType.HELIX;
+               else if (type == AnchorType.LOOP)
+                       _typeAnchor = AnchorType.LOOP;
+               else
+                       throw new Exception("Bad argument");
+       }
+
+       public AnchorType getType() {
+               return _typeAnchor;
+       }
+
+       public void setType(AnchorType t) {
+               _typeAnchor = t;
+       }
+
+
+       public Color getColor() {
+               return _color;
+       }
+
+       public void setColor(Color color) {
+               this._color = color;
+       }
+
+       
+       public String getHelixDescription()
+       {
+               ArrayList<ModeleBase> listeBase =  ((ArrayList<ModeleBase>)_anchor);
+               int minA = Integer.MAX_VALUE,maxA = Integer.MIN_VALUE;
+               int minB = Integer.MAX_VALUE,maxB = Integer.MIN_VALUE;
+               for(ModeleBase mb : listeBase)
+               {
+                       int i = mb.getBaseNumber();
+                       if (mb.getElementStructure()>i)
+                       {
+                               minA = Math.min(minA, i);
+                               maxA = Math.max(maxA, i);
+                       }
+                       else
+                       {
+                               minB = Math.min(minB, i);
+                               maxB = Math.max(maxB, i);                               
+                       }
+               }
+               return "["+minA+","+maxA+"] ["+minB+","+maxB+"]";
+       }
+       
+       public String getLoopDescription()
+       {
+               ArrayList<ModeleBase> listeBase =  ((ArrayList<ModeleBase>)_anchor);
+               int min = Integer.MAX_VALUE,max = Integer.MIN_VALUE;
+               for(ModeleBase mb : listeBase)
+               {
+                       int i = mb.getBaseNumber();
+                               min = Math.min(min, i);
+                               max = Math.max(max, i);
+               }
+               return "["+min+","+max+"]";
+       }
+       
+       public String toString() {
+               String tmp = "["+_text+"] ";
+               switch (_typeAnchor) {
+               case POSITION:
+                       NumberFormat formatter = new DecimalFormat(".00"); 
+                       return tmp+" at ("+formatter.format(getCenterPosition().x)+","+formatter.format(getCenterPosition().y)+")";
+               case BASE:
+                       return tmp+" on base "+((ModeleBase) _anchor).getBaseNumber();
+               case HELIX:
+                       return tmp+" on helix "+getHelixDescription();
+               case LOOP:
+                       return tmp+" on loop "+getLoopDescription();
+               default:
+                       return tmp;
+               }               
+       }
+
+       /**
+        * 
+        * @return the text position center
+        */
+       public Point2D.Double getCenterPosition() {
+               switch (_typeAnchor) {
+               case POSITION:
+                       return ((VARNAPoint) _anchor).toPoint2D();
+               case BASE:
+                       return ((ModeleBase) _anchor).getCoords();
+               case HELIX:
+                       return calculLoopHelix();
+               case LOOP:
+                       return calculLoop();
+               default:
+                       return new Point2D.Double(0., 0.);
+               }
+       }
+
+       private Point2D.Double calculLoop() {
+               ArrayList<ModeleBase> liste = extractedArrayListModeleBaseFromAncrage();
+               double totalX = 0., totalY = 0.;
+               for (ModeleBase base : liste) {
+                       totalX += base.getCoords().x;
+                       totalY += base.getCoords().y;
+               }
+               return new Point2D.Double(totalX / liste.size(), totalY / liste.size());
+       }
+
+       private Point2D.Double calculLoopHelix() {
+               ArrayList<ModeleBase> liste = extractedArrayListModeleBaseFromAncrage();
+               Collections.sort(liste);
+               double totalX = 0., totalY = 0.;
+               double num=0.0;
+               for (int i=0;i<liste.size(); i++) {
+                       ModeleBase base =liste.get(i);
+                       if ((i>0 && (i<liste.size()-1)) || ((liste.size()/2)%2==0))
+                       {
+                               totalX += base.getCoords().x;
+                               totalY += base.getCoords().y;
+                               num += 1;
+                       }
+               }
+               return new Point2D.Double(totalX / num, totalY / num);
+       }
+
+       
+       private ArrayList<ModeleBase> extractedArrayListModeleBaseFromAncrage() {
+               return (ArrayList<ModeleBase>) _anchor;
+       }
+
+       /**
+        * clone a TextAnnotation
+        */
+       public TextAnnotation clone() {
+               TextAnnotation textAnnot = null;
+               try {
+                       switch (_typeAnchor) {
+                       case BASE:
+                               textAnnot = new TextAnnotation(_text, (ModeleBase) _anchor);
+                               break;
+                       case POSITION:
+                               textAnnot = new TextAnnotation(_text,
+                                               ((VARNAPoint) _anchor).x,
+                                               ((VARNAPoint) _anchor).y);
+                               break;
+                       case LOOP:
+                               textAnnot = new TextAnnotation(_text,
+                                               extractedArrayListModeleBaseFromAncrage(), AnchorType.LOOP);
+                               break;
+                       case HELIX:
+                               textAnnot = new TextAnnotation(_text,
+                                               extractedArrayListModeleBaseFromAncrage(), AnchorType.HELIX);
+                               break;
+                       default:
+                               break;
+                       }
+               } catch (Exception e) {
+                       e.printStackTrace();
+               }
+               textAnnot.setFont(_font);
+               textAnnot.setColor(_color);
+               return textAnnot;
+
+       }
+
+       /**
+        * copy a textAnnotation
+        * 
+        * @param textAnnotation
+        */
+       public void copy(TextAnnotation textAnnotation) {
+               _anchor = textAnnotation.getAncrage();
+               _font = textAnnotation.getFont();
+               _text = textAnnotation.getTexte();
+               _typeAnchor = textAnnotation.getType();
+               _color = textAnnotation.getColor();
+               _angle = textAnnotation.getAngleInDegres();
+       }
+
+
+       /**
+        * 
+        * @return the angle in degrees
+        */
+       public double getAngleInDegres() {
+               // if (_typeAncrage == TextAnnotation.HELIX)
+               // _angle = calculAngleDegres();
+               return _angle;
+       }
+
+       /**
+        * 
+        * @return the angle in radians
+        */
+       public double getAngleInRadians() {
+               return (getAngleInDegres() * Math.PI) / 180.;
+       }
+
+       public void setAngleInDegres(double _angle) {
+               this._angle = _angle;
+       }
+
+       public void setAngleInRadians(double _angle) {
+               this._angle = _angle * 180 / Math.PI;
+       }
+       
+       
+       public static TextAnnotation parse(String thisAnn, VARNAPanel vp)
+       {
+               String[] data = thisAnn.split(":");
+
+               String text = "";
+               int anchor = -1;
+               int x = -1;
+               int y = -1;
+               TextAnnotation.AnchorType type = TextAnnotation.AnchorType.LOOP;
+               Font font = TextAnnotation.DEFAULTFONT;
+               Color color = TextAnnotation.DEFAULTCOLOR;
+               TextAnnotation ann = null;
+               try {
+                       if (data.length == 2) {
+                               text = data[0];
+                               String[] data2 = data[1].split(",");
+                               for (int j = 0; j < data2.length; j++) {
+                                       String opt = data2[j];
+                                       String[] data3 = opt.split("=");
+                                       if (data3.length == 2) {
+                                               String name = data3[0].toLowerCase();
+                                               String value = data3[1];
+                                               if (name.equals("type")) {
+                                                       if (value.toUpperCase().equals("H")) {
+                                                               type = TextAnnotation.AnchorType.HELIX;
+                                                       } else if (value.toUpperCase().equals("L")) {
+                                                               type = TextAnnotation.AnchorType.LOOP;
+                                                       } else if (value.toUpperCase().equals("P")) {
+                                                               type = TextAnnotation.AnchorType.POSITION;
+                                                       } else if (value.toUpperCase().equals("B")) {
+                                                               type = TextAnnotation.AnchorType.BASE;
+                                                       }
+                                               } else if (name.equals("x")) {
+                                                       x = Integer.parseInt(value);
+                                               } else if (name.equals("y")) {
+                                                       y = Integer.parseInt(value);
+                                               } else if (name.equals("anchor")) {
+                                                       anchor = Integer.parseInt(value);
+                                               } else if (name.equals("size")) {
+                                                       font = font.deriveFont((float) Integer
+                                                                       .parseInt(value));
+                                               } else if (name.equals("color")) {
+                                                       color = VARNAConfigLoader.getSafeColor(value, color);
+                                               }
+                                       }
+                               }
+                               switch (type) {
+                               case POSITION:
+                                       if ((x != -1) && (y != -1)) {
+                                               Point2D.Double p = vp
+                                                               .panelToLogicPoint(new Point2D.Double(x, y));
+                                               ann = new TextAnnotation(text, p.x, p.y);
+                                       }
+                                       break;
+                               case BASE:
+                                       if (anchor != -1) {
+                                               int index = vp.getRNA().getIndexFromBaseNumber(
+                                                               anchor);
+                                               ModeleBase mb = vp.getRNA().get_listeBases()
+                                                               .get(index);
+                                               ann = new TextAnnotation(text, mb);
+                                       }
+                                       break;
+                               case HELIX:
+                                       if (anchor != -1) {
+                                               ArrayList<ModeleBase> mbl = new ArrayList<ModeleBase>();
+                                               int index = vp.getRNA().getIndexFromBaseNumber(
+                                                               anchor);
+                                               ArrayList<Integer> il = vp.getRNA()
+                                                               .findHelix(index);
+                                               for (int k : il) {
+                                                       mbl.add(vp.getRNA().get_listeBases().get(k));
+                                               }
+                                               ann = new TextAnnotation(text, mbl, type);
+                                       }
+                                       break;
+                               case LOOP:
+                                       if (anchor != -1) {
+                                               ArrayList<ModeleBase> mbl = new ArrayList<ModeleBase>();
+                                               int index = vp.getRNA().getIndexFromBaseNumber(
+                                                               anchor);
+                                               ArrayList<Integer> il = vp.getRNA().findLoop(index);
+                                               for (int k : il) {
+                                                       mbl.add(vp.getRNA().get_listeBases().get(k));
+                                               }
+                                               ann = new TextAnnotation(text, mbl, type);
+                                       }
+                                       break;
+                               }
+                               if (ann != null) {
+                                       ann.setColor(color);
+                                       ann.setFont(font);
+                               }
+                       }
+               } catch (Exception e) {
+                       System.err.println("Apply Annotations: " + e.toString());
+               }
+               return ann;
+               }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/ArcCommand.java b/src2/fr/orsay/lri/varna/models/export/ArcCommand.java
new file mode 100644 (file)
index 0000000..aeb1466
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.geom.Point2D;
+
+public class ArcCommand extends GraphicElement {
+
+       private Point2D.Double center;
+       private double width, height;
+       private double startAngle, endAngle;
+
+       public ArcCommand(Point2D.Double origine, double width, double height,
+                       double startAngle, double endAngle) {
+               this.center = origine;
+               this.width = width;
+               this.height = height;
+               this.startAngle = startAngle;
+               this.endAngle = endAngle;
+       }
+
+       public Point2D.Double getCenter() {
+               return center;
+       }
+
+       public double getWidth() {
+               return width;
+       }
+
+       public double getHeight() {
+               return height;
+       }
+
+       public double getStartAngle() {
+               return startAngle;
+       }
+
+       public double getEndAngle() {
+               return endAngle;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/CircleCommand.java b/src2/fr/orsay/lri/varna/models/export/CircleCommand.java
new file mode 100644 (file)
index 0000000..bc6c286
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.geom.Point2D;
+
+public class CircleCommand extends GraphicElement {
+
+       private Point2D.Double _base;
+       private double _radius;
+       private double _thickness;
+
+       public CircleCommand(Point2D.Double base, double radius, double thickness) {
+               _base = base;
+               _radius = radius;
+               _thickness = thickness;
+       }
+
+       public Point2D.Double get_base() {
+               return _base;
+       }
+
+       public double get_radius() {
+               return _radius;
+       }
+
+       public double get_thickness() {
+               return _thickness;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/ColorCommand.java b/src2/fr/orsay/lri/varna/models/export/ColorCommand.java
new file mode 100644 (file)
index 0000000..fd1bea9
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+
+public class ColorCommand extends GraphicElement {
+       Color _color;
+
+       public ColorCommand(Color c) {
+               _color = c;
+       }
+
+       public Color getColor() {
+               return _color;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/FillCircleCommand.java b/src2/fr/orsay/lri/varna/models/export/FillCircleCommand.java
new file mode 100644 (file)
index 0000000..8c971e8
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.geom.Point2D;
+
+public class FillCircleCommand extends GraphicElement {
+
+       private Point2D.Double _base;
+       private double _radius;
+       private double _thickness;
+       private Color _color;
+
+       public FillCircleCommand(Point2D.Double base, double radius,
+                       double thickness, Color color) {
+               _base = base;
+               _radius = radius;
+               _thickness = thickness;
+               _color = color;
+       }
+
+       public Point2D.Double get_base() {
+               return _base;
+       }
+
+       public double get_radius() {
+               return _radius;
+       }
+
+       public double get_thickness() {
+               return _thickness;
+       }
+
+       public Color get_color() {
+               return _color;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/FillPolygonCommand.java b/src2/fr/orsay/lri/varna/models/export/FillPolygonCommand.java
new file mode 100644 (file)
index 0000000..d4266ae
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.geom.Point2D;
+
+public class FillPolygonCommand extends GraphicElement {
+
+       private Point2D.Double[] _points;
+       //private double _thickness;
+       private Color _color;
+
+       public FillPolygonCommand(Point2D.Double[] points, 
+                       Color color) {
+               _points = points;
+               _color = color;
+       }
+
+       public Point2D.Double[] get_points() {
+               return _points;
+       }
+
+
+       public Color get_color() {
+               return _color;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/FontCommand.java b/src2/fr/orsay/lri/varna/models/export/FontCommand.java
new file mode 100644 (file)
index 0000000..bf93264
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+public class FontCommand extends GraphicElement {
+       private int _font;
+       private double _size;
+
+       public FontCommand(int font, double size) {
+               _font = font;
+               _size = size;
+       }
+
+       public int get_font() {
+               return _font;
+       }
+
+       public double get_size() {
+               return _size;
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/GraphicElement.java b/src2/fr/orsay/lri/varna/models/export/GraphicElement.java
new file mode 100644 (file)
index 0000000..459308c
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+public abstract class GraphicElement {
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/LineCommand.java b/src2/fr/orsay/lri/varna/models/export/LineCommand.java
new file mode 100644 (file)
index 0000000..476abe9
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.geom.Point2D;
+
+public class LineCommand extends GraphicElement {
+       private Point2D.Double _orig;
+       private Point2D.Double _dest;
+       private double _thickness;
+
+       public LineCommand(Point2D.Double orig, Point2D.Double dest,
+                       double thickness) {
+               _orig = orig;
+               _dest = dest;
+               _thickness = thickness;
+       }
+
+       public Point2D.Double get_orig() {
+               return _orig;
+       }
+
+       public Point2D.Double get_dest() {
+               return _dest;
+       }
+
+       public double get_thickness() {
+               return _thickness;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/PSExport.java b/src2/fr/orsay/lri/varna/models/export/PSExport.java
new file mode 100644 (file)
index 0000000..7907150
--- /dev/null
@@ -0,0 +1,333 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.geom.Point2D.Double;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+/**
+ * @author ponty
+ * 
+ */
+public class PSExport extends SecStrDrawingProducer {
+
+       public PSExport()
+       {
+               super();
+               super.setScale(0.4);
+       }
+       
+       private String PSMacros() {
+               String setFontSize =
+               // Params [fontsize|...]
+               "/setbasefont \n" + "{ /Helvetica-Bold findfont\n" + // =>
+                               // [font|scale|...]
+                               "  exch scalefont\n" + // => [scaled_font|...]
+                               "  setfont \n" + // => [...]
+                               "  } def\n\n";
+
+               String writeTextCentered =
+               // Params [txt|size|...]
+               "/txtcenter \n" + "{ dup \n" + // => [txt|txt|size|...]
+                               "  stringwidth pop\n" + // => [wtxt|txt|size|...]
+                               "  2 div neg \n" + // => [-wtxt/2|txt|size|...]
+                               "  3 -1 roll \n" + // => [size|-wtxt/2|txt...]
+                               "  2 div neg\n" + // => [-size/2|-wtxt/2|txt|...]
+                               "  rmoveto\n" + // => [txt|...]
+                               "  show\n" + // => [...]
+                               "  } def\n\n";
+
+               String drawEllipse = "/ellipse {\n" + "  /endangle exch def\n"
+                               + "  /startangle exch def\n" + "  /yrad exch def\n"
+                               + "  /xrad exch def\n" + "  /y exch def\n" + "  /x exch def\n"
+                               + "  /savematrix matrix currentmatrix def\n"
+                               + "  x y translate\n" + "  xrad yrad scale\n"
+                               + "  0 0 1 startangle endangle arc\n"
+                               + "  savematrix setmatrix\n" + "  } def\n\n";
+               return setFontSize + writeTextCentered + drawEllipse;
+       }
+
+       private String EPSHeader(double minX, double maxX, double minY, double maxY) {
+               String bbox = PSBBox(minX, minY, maxX, maxY);
+               String init = "%!PS-Adobe-3.0\n" + "%%Pages: 1\n" + bbox
+                               + "%%EndComments\n" + "%%Page: 1 1\n";
+               String macros = PSMacros();
+               return init + macros;
+       }
+
+       private String EPSFooter() {
+               return "showpage\n" + "%%EndPage: 1\n" + "%%EOF";
+       }
+
+       private String PSNewPath() {
+               return ("newpath\n");
+       }
+
+       private String PSMoveTo(double x, double y) {
+               return ("" + x + " " + y + " moveto\n");
+       }
+
+       private String PSLineTo(double dx, double dy) {
+               return ("" + dx + " " + dy + " lineto\n");
+       }
+
+       private String PSRLineTo(double dx, double dy) {
+               return ("" + dx + " " + dy + " rlineto\n");
+       }
+
+       private String PSSetLineWidth(double thickness) {
+               thickness /= 2;
+               return ("" + thickness + " setlinewidth\n");
+       }
+
+       private String PSStroke() {
+               return ("stroke\n");
+       }
+
+       private String PSArc(double x, double y, double radiusX, double radiusY,
+                       double angleFrom, double angleTo) {
+
+               double centerX = x;
+               double centerY = y;
+
+               // return (centerX + " " + centerY + " "+ radiusX/2.0+" " + angleFrom +
+               // " " + angleTo + "  arc\n");
+
+               return (centerX + " " + centerY + " " + radiusX / 2.0 + " " + radiusY
+                               / 2.0 + " " + angleTo + " " + angleFrom + " ellipse\n");
+
+       }
+
+       private String PSArc(double x, double y, double radius, double angleFrom,
+                       double angleTo) {
+
+               return ("" + x + " " + y + " " + radius + " " + angleFrom + " "
+                               + angleTo + "  arc\n");
+       }
+
+       private String PSBBox(double minX, double maxX, double minY, double maxY) {
+               String norm = ("%%BoundingBox: " + (long) Math.floor(minX) + " "
+                               + (long) Math.floor(minY) + " " + (long) Math.ceil(maxX) + " "
+                               + (long) Math.ceil(maxY) + "\n");
+               String high = ("%%HighResBoundingBox: " + (long) Math.floor(minX) + " "
+                               + (long) Math.floor(minY) + " " + (long) Math.ceil(maxX) + " "
+                               + (long) Math.ceil(maxY) + "\n");
+               return norm + high;
+       }
+
+       private String PSText(String txt) {
+               return ("(" + txt + ") ");
+       }
+
+       @SuppressWarnings("unused")
+       private String PSShow() {
+               return ("show\n");
+       }
+
+       private String PSClosePath() {
+               return ("closepath\n");
+       }
+
+       private String PSFill() {
+               return ("fill\n");
+       }
+
+       private String PSSetColor(Color col) {
+               return ("" + (((double) col.getRed()) / 255.0) + " "
+                               + (((double) col.getGreen()) / 255.0) + " "
+                               + (((double) col.getBlue()) / 255.0) + " setrgbcolor\n");
+       }
+
+       private String fontName(int font) {
+               switch (font) {
+               case (FONT_TIMES_ROMAN):
+                       return "/Times-Roman";
+               case (FONT_TIMES_BOLD):
+                       return "/Times-Bold";
+               case (FONT_TIMES_ITALIC):
+                       return "/Times-Italic";
+               case (FONT_TIMES_BOLD_ITALIC):
+                       return "/Times-BoldItalic";
+               case (FONT_HELVETICA):
+                       return "/Helvetica";
+               case (FONT_HELVETICA_BOLD):
+                       return "/Helvetica-Bold";
+               case (FONT_HELVETICA_OBLIQUE):
+                       return "/Helvetica-Oblique";
+               case (FONT_HELVETICA_BOLD_OBLIQUE):
+                       return "/Helvetica-BoldOblique";
+               case (FONT_COURIER):
+                       return "/Courier";
+               case (FONT_COURIER_BOLD):
+                       return "/Courier-Bold";
+               case (FONT_COURIER_OBLIQUE):
+                       return "/Courier-Oblique";
+               case (FONT_COURIER_BOLD_OBLIQUE):
+                       return "/Courier-BoldOblique";
+               }
+               return "/Helvetica";
+       }
+
+       private String PSSetFont(int font, double size) {
+               return (fontName(font) + " findfont " + size + " scalefont setfont\n");
+       }
+
+       public String setFontS(int font, double size) {
+               _fontsize = (long) (0.4 * size);
+               return PSSetFont(font, _fontsize);
+       }
+
+       public String setColorS(Color col) {
+               super.setColorS(col);
+               String result = PSSetColor(col);
+               return result;
+       }
+
+       public String drawLineS(Point2D.Double p0, Point2D.Double p1,
+                       double thickness) {
+               String tmp = "";
+               tmp += PSMoveTo(p0.x, p0.y);
+               tmp += PSLineTo(p1.x, p1.y);
+               tmp += PSSetLineWidth(thickness);
+               tmp += PSStroke();
+               return tmp;
+       }
+
+       public String drawTextS(Point2D.Double p, String txt) {
+               String tmp = "";
+               tmp += PSMoveTo(p.x, p.y);
+               tmp += ("" + (_fontsize / 2.0 + 1) + " \n");
+               tmp += PSText(txt);
+               tmp += (" txtcenter\n");
+               return tmp;
+       }
+
+       public String drawRectangleS(Point2D.Double orig, Point2D.Double dims,
+                       double thickness) {
+               String tmp = PSNewPath();
+               tmp += PSMoveTo(orig.x, orig.y);
+               tmp += PSRLineTo(0, dims.y);
+               tmp += PSRLineTo(dims.x, 0);
+               tmp += PSRLineTo(0, -dims.y);
+               tmp += PSClosePath();
+               tmp += PSSetLineWidth(thickness);
+               tmp += PSStroke();
+               return tmp;
+       }
+
+       public String drawCircleS(Point2D.Double p, double radius, double thickness) {
+               String tmp = PSNewPath();
+               tmp += PSArc(p.x, p.y, radius, 0, 360);
+               tmp += PSSetLineWidth(thickness);
+               tmp += PSStroke();
+               return tmp;
+       }
+
+       public String fillCircleS(Point2D.Double p, double radius,
+                       double thickness, Color color) {
+               String tmp = PSNewPath();
+               tmp += PSArc(p.x, p.y, radius, 0, 360);
+               tmp += PSSetLineWidth(thickness);
+               tmp += PSSetColor(color);
+               tmp += PSFill();
+               return tmp;
+       }
+
+       public String footerS() {
+               return EPSFooter();
+       }
+
+       public String headerS(Rectangle2D.Double bb) {
+               return EPSHeader(bb.x, bb.y, bb.x + bb.width, bb.y + bb.height);
+       }
+
+       @Override
+       public String drawArcS(Point2D.Double origine, double width, double height,
+                       double startAngle, double endAngle) {
+               return PSArc(origine.x, origine.y, width, height, startAngle, endAngle)
+                               + PSStroke();
+       }
+
+       @Override
+       public String drawPolygonS(Double[] points, double thickness) {
+               String tmp = PSNewPath();
+               tmp += PSSetLineWidth(thickness);
+               for (int i = 0; i < points.length; i++) {
+                       if (i == 0) {
+                               tmp += PSMoveTo(points[i].x, points[i].y);
+                       } else {
+                               tmp += PSLineTo(points[i].x, points[i].y);
+                       }
+               }
+               tmp += PSClosePath();
+               tmp += PSStroke();
+               return tmp;
+       }
+
+       @Override
+       public String fillPolygonS(Double[] points, Color color) {
+               Color bck = _curColor;
+               String tmp = PSNewPath();
+               for (int i = 0; i < points.length; i++) {
+                       if (i == 0) {
+                               tmp += PSMoveTo(points[i].x, points[i].y);
+                       } else {
+                               tmp += PSLineTo(points[i].x, points[i].y);
+                       }
+               }
+               tmp += PSClosePath();
+               tmp += PSSetColor(color);
+               tmp += PSFill();
+               tmp += PSSetColor(bck);
+               return tmp;
+       }
+
+       @Override
+       public String drawBaseStartS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBaseEndS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBasePairStartS(int i, int j, ModeleBP bps) {
+               return "";
+       }
+
+       @Override
+       public String drawBasePairEndS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBackboneStartS(int i, int j) {
+               return "";
+       }
+
+       @Override
+       public String drawBackboneEndS(int index) {
+               return "";
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/export/PolygonCommand.java b/src2/fr/orsay/lri/varna/models/export/PolygonCommand.java
new file mode 100644 (file)
index 0000000..cfcf0bd
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.geom.Point2D;
+
+public class PolygonCommand extends GraphicElement {
+
+       private Point2D.Double[] _points;
+       private double _thickness;
+
+       public PolygonCommand(Point2D.Double[] points, double thickness) {
+               _points = points;
+               _thickness = thickness;
+       }
+
+       public Point2D.Double[] get_points() {
+               return _points;
+       }
+
+       public double get_thickness() {
+               return _thickness;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/RectangleCommand.java b/src2/fr/orsay/lri/varna/models/export/RectangleCommand.java
new file mode 100644 (file)
index 0000000..8e0f080
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.geom.Point2D;
+
+public class RectangleCommand extends GraphicElement {
+       private Point2D.Double _orig;
+       private Point2D.Double _dims;
+       private double _thickness;
+
+       public RectangleCommand(Point2D.Double orig, Point2D.Double dims,
+                       double thickness) {
+               _orig = orig;
+               _dims = dims;
+               _thickness = thickness;
+       }
+
+       public Point2D.Double get_orig() {
+               return _orig;
+       }
+
+       public Point2D.Double get_dims() {
+               return _dims;
+       }
+
+       public double get_thickness() {
+               return _thickness;
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/export/SVGExport.java b/src2/fr/orsay/lri/varna/models/export/SVGExport.java
new file mode 100644 (file)
index 0000000..0ddd711
--- /dev/null
@@ -0,0 +1,197 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.geom.Point2D.Double;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+public class SVGExport extends SecStrDrawingProducer {
+
+       private double _fontsize = 10.0;
+       private Rectangle2D.Double _bb = new Rectangle2D.Double(0, 0, 10, 10);
+       double _thickness = 2.0;
+       
+       
+       public SVGExport()
+       {
+               super();
+               super.setScale(0.5);
+       }
+
+       private String getRGBString(Color col) {
+               int rpc = (int) ((((double) col.getRed()) / 255.0) * 100);
+               int gpc = (int) ((((double) col.getGreen()) / 255.0) * 100);
+               int bpc = (int) ((((double) col.getBlue()) / 255.0) * 100);
+               return "rgb(" + rpc + "%, " + gpc + "%, " + bpc + "%)";
+       }
+
+       public String drawCircleS(Point2D.Double base, double radius,
+                       double thickness) {
+               _thickness = thickness;
+               return "<circle cx=\"" + base.x + "\" cy=\"" + (_bb.height - base.y)
+                               + "\" r=\"" + radius + "\" stroke=\"" + getRGBString(_curColor)
+                               + "\" stroke-width=\"" + thickness + "\" fill=\"none\"/>\n";
+       }
+
+       public String drawLineS(Point2D.Double orig, Point2D.Double dest,
+                       double thickness) {
+               _thickness = thickness;
+               return "<line x1=\"" + orig.x + "\" y1=\"" + (_bb.height - orig.y)
+                               + "\" x2=\"" + dest.x + "\" y2=\"" + (_bb.height - dest.y)
+                               + "\" stroke=\"" + getRGBString(_curColor)
+                               + "\" stroke-width=\"" + thickness + "\" />\n";
+       }
+
+       public String drawRectangleS(Point2D.Double orig, Point2D.Double dims,
+                       double thickness) {
+               _thickness = thickness;
+               return "<rect x=\""+ orig.x+"\" y=\""+(_bb.height - orig.y - dims.y)+"\" width=\""+dims.x
+                 +"\" height=\""+dims.y+
+                 "\" fill=\"none\" style=\"stroke-width:"+thickness+";stroke:"+getRGBString(_curColor)+"\"/>";
+       }
+
+       public String drawTextS(Point2D.Double base, String txt) {
+               //System.out.println(txt);
+               return "<text x=\""
+                               + (base.x)
+                               + "\" y=\""
+                               + (_bb.height - base.y + 0.4 * _fontsize)
+                               + "\" text-anchor=\"middle\" font-family=\"Verdana\" font-size=\""
+                               + _fontsize + "\" fill=\"" + getRGBString(_curColor) + "\" >"
+                               + txt + "</text>\n";
+       }
+
+       public String fillCircleS(Point2D.Double base, double radius,
+                       double thickness, Color col) {
+               _thickness = thickness;
+
+               return "<circle cx=\"" + base.x + "\" cy=\"" + (_bb.height - base.y)
+                               + "\" r=\"" + radius + "\" stroke=\"none\" stroke-width=\""
+                               + thickness + "\" fill=\"" + getRGBString(col) + "\"/>\n";
+       }
+
+       public String footerS() {
+               return "</svg>\n";
+       }
+
+       public String headerS(Rectangle2D.Double bb) {
+               _bb = bb;
+               return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+                               + "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n"
+                               + "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"
+                               + "\n"
+                               + "<svg width=\"100%\" height=\"100%\" version=\"1.1\"\n"
+                               + "xmlns=\"http://www.w3.org/2000/svg\">\n";
+       }
+
+       public String setFontS(int font, double size) {
+               _fontsize = 0.5 * size;
+               return "";
+       }
+
+       
+       private Point2D.Double polarToCartesian(Point2D.Double center, double radiusX, double radiusY, double angleInDegrees) {
+                 double angleInRadians = (angleInDegrees) * Math.PI / 180.0;
+
+                 return new Point2D.Double(center.x + (radiusX * Math.cos(angleInRadians)),
+                                 _bb.height - (center.y + (radiusY * Math.sin(angleInRadians))));
+               }
+
+       
+       public String drawArcS(Point2D.Double o, double width, double height,
+                       double startAngle, double endAngle) {
+               double rx = width / 2.0;
+               double ry = height / 2.0;
+               
+               Point2D.Double ps = polarToCartesian(o,rx,ry,startAngle);
+               Point2D.Double pe = polarToCartesian(o,rx,ry,endAngle);
+               
+               String d = "<path d=\"M " + ps.x + "," +  ps.y + " A " + rx + "," + ry
+                               + " 0 1,1 " +  pe.x + "," + pe.y + "\" style=\"fill:none; stroke:"
+                               + getRGBString(_curColor) + "; stroke-width:" + _thickness
+                               + "\"/>\n";             
+               return d;
+       }
+
+       public String drawPolygonS(Double[] points, double thickness) {
+               String result = "<path d=\"";
+               for (int i = 0; i < points.length; i++) {
+                       if (i == 0) {
+                               result += "M " + points[i].x + " " + (_bb.height - points[i].y)
+                                               + " ";
+                       } else {
+                               result += "L " + points[i].x + " " + (_bb.height - points[i].y)
+                                               + " ";
+                       }
+               }
+               result += "z\" style=\"fill:none; stroke:" + getRGBString(_curColor)
+                               + "; stroke-width:" + thickness + ";\"/>\n";
+               return result;
+       }
+
+       @Override
+       public String fillPolygonS(Double[] points, Color col) {
+               String result = "<path d=\"";
+               for (int i = 0; i < points.length; i++) {
+                       if (i == 0) {
+                               result += "M " + points[i].x + " " + (_bb.height - points[i].y)
+                                               + " ";
+                       } else {
+                               result += "L " + points[i].x + " " + (_bb.height - points[i].y)
+                                               + " ";
+                       }
+               }
+               result += "z\" fill=\""+getRGBString(col)+"\" style=\"stroke:none;\"/>\n";
+               return result;
+       }
+       
+       @Override
+       public String drawBaseStartS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBaseEndS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBasePairStartS(int i, int j, ModeleBP bps) {
+               return "";
+       }
+
+       @Override
+       public String drawBasePairEndS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBackboneStartS(int i, int j) {
+               return "";
+       }
+
+       @Override
+       public String drawBackboneEndS(int index) {
+               return "";
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/SecStrDrawingProducer.java b/src2/fr/orsay/lri/varna/models/export/SecStrDrawingProducer.java
new file mode 100644 (file)
index 0000000..a80e8e2
--- /dev/null
@@ -0,0 +1,400 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.PathIterator;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.util.Vector;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+public abstract class SecStrDrawingProducer {
+       public static final int FONT_TIMES_ROMAN = 0;
+       public static final int FONT_TIMES_BOLD = 1;
+       public static final int FONT_TIMES_ITALIC = 2;
+       public static final int FONT_TIMES_BOLD_ITALIC = 3;
+       public static final int FONT_HELVETICA = 16;
+       public static final int FONT_HELVETICA_OBLIQUE = 17;
+       public static final int FONT_HELVETICA_BOLD = 18;
+       public static final int FONT_HELVETICA_BOLD_OBLIQUE = 19;
+       public static final int FONT_COURIER = 12;
+       public static final int FONT_COURIER_BOLD = 13;
+       public static final int FONT_COURIER_OBLIQUE = 14;
+       public static final int FONT_COURIER_BOLD_OBLIQUE = 15;
+
+       private Vector<GraphicElement> _commands = new Vector<GraphicElement>();
+
+       private double _scale = 1.0;
+       private double _xmin = Double.MAX_VALUE;
+       private double _ymin = Double.MAX_VALUE;
+       private double _xmax = -Double.MAX_VALUE;
+       private double _ymax = -Double.MAX_VALUE;
+
+       protected Color _curColor = Color.black;
+       protected Color _backgroundColor = null;
+       
+       protected double _fontsize = 10.0;
+       protected int _font = FONT_HELVETICA_BOLD;
+
+       
+       public Color getCurrentColor() {
+               return _curColor;
+       }
+
+       public double getCurFontSize() {
+               return _fontsize;
+       }
+
+       public int getCurrentFont() {
+               return _font;
+       }
+       
+
+       public abstract String drawBaseStartS(int index);
+       public abstract String drawBaseEndS(int index);
+       public abstract String drawBasePairStartS(int i, int j, ModeleBP bps);
+       public abstract String drawBasePairEndS(int index);
+       public abstract String drawBackboneStartS(int i, int j);
+       public abstract String drawBackboneEndS(int index);
+
+       public abstract String drawLineS(Point2D.Double orig,
+                       Point2D.Double dest, double thickness);
+
+       
+       public abstract String drawArcS(Point2D.Double origine, double width,
+                       double height, double startAngle, double endAngle);
+
+       public abstract String drawTextS(Point2D.Double base, String txt);
+
+       public abstract String drawRectangleS(Point2D.Double orig,
+                       Point2D.Double dims, double thickness);
+       
+       public abstract String drawCircleS(Point2D.Double base, double radius,
+                       double thickness);
+
+       public abstract String fillCircleS(Point2D.Double base, double radius,
+                       double thickness, Color color);
+
+       public abstract String drawPolygonS(Point2D.Double[] points,
+                       double thickness);
+
+       public abstract String fillPolygonS(Point2D.Double[] points,
+                Color color);
+
+       public abstract String setFontS(int font, double size);
+
+       public String setColorS(Color col) {
+               _curColor = col;
+               return "";
+       }
+
+       public abstract String headerS(Rectangle2D.Double bb);
+
+       public abstract String footerS();
+
+       @SuppressWarnings("unused")
+       private void resetBoundingBox() {
+               _xmin = Double.MAX_VALUE;
+               _ymin = Double.MAX_VALUE;
+               _xmax = -Double.MAX_VALUE;
+               _ymax = -Double.MAX_VALUE;
+       }
+
+       private void updateBoundingBox(double x, double y) {
+               _xmin = Math.min(_xmin, x - 10);
+               _ymin = Math.min(_ymin, y - 10);
+               _xmax = Math.max(_xmax, x + 10);
+               _ymax = Math.max(_ymax, y + 10);
+       }
+
+       public void drawLine(double x0, double y0, double x1, double y1,
+                       double thickness) {
+               updateBoundingBox(x0, y0);
+               updateBoundingBox(x1, y1);
+               _commands.add(new LineCommand(new Point2D.Double(x0, y0),
+                               new Point2D.Double(x1, y1), thickness));
+       }
+
+       public void drawArc(Point2D.Double origine, double width, double height,
+                       double startAngle, double endAngle) {
+               updateBoundingBox(origine.x + width/2., origine.y + height/2.);
+               updateBoundingBox(origine.x - width/2., origine.y - height/2.);
+               _commands.add(new ArcCommand(origine, width, height, startAngle,
+                               endAngle));
+       }
+
+       public void drawText(double x, double y, String txt) {
+               updateBoundingBox(x, y);
+
+               _commands.add(new TextCommand(new Point2D.Double(x, y), new String(txt)));
+       }
+
+       public void drawRectangle(double x, double y, double w, double h,
+                       double thickness) {
+               updateBoundingBox(x, y);
+               updateBoundingBox(x + w, y + h);
+
+               _commands.add(new RectangleCommand(new Point2D.Double(x, y),
+                               new Point2D.Double(w, h), thickness));
+       }
+       
+       public void fillRectangle(double x, double y, double w, double h, Color color) {
+               double [] xtab = new double[4];
+               double [] ytab = new double[4];
+               xtab[0] = x;
+               xtab[1] = x+w;
+               xtab[2] = x+w;
+               xtab[3] = x;
+               ytab[0] = y;
+               ytab[1] = y;
+               ytab[2] = y+h;
+               ytab[3] = y+h;
+               fillPolygon(xtab, ytab, color);
+       }
+
+       public void drawCircle(double x, double y, double radius, double thickness) {
+               updateBoundingBox(x - radius, y - radius);
+               updateBoundingBox(x + radius, y + radius);
+
+               _commands.add(new CircleCommand(new Point2D.Double(x, y), radius,
+                               thickness));
+
+       }
+
+       public void setColor(Color col) {
+               _curColor = col;
+               _commands.add(new ColorCommand(col));
+       }
+       
+       public void setBackgroundColor(Color col){
+               _backgroundColor = col;
+       }
+
+       public void removeBackgroundColor(){
+               _backgroundColor = null;
+       }
+
+       public void fillCircle(double x, double y, double radius, double thickness,
+                       Color color) {
+               updateBoundingBox(x - radius, y - radius);
+               updateBoundingBox(x + radius, y + radius);
+
+               _commands.add(new FillCircleCommand(new Point2D.Double(x, y), radius,
+                               thickness, color));
+       }
+
+       public void drawPolygon(double[] xtab, double[] ytab, double thickness) {
+               if (xtab.length == ytab.length) {
+                       Point2D.Double points[] = new Point2D.Double[xtab.length];
+                       for (int i = 0; i < xtab.length; i++) {
+                               points[i] = new Point2D.Double(xtab[i], ytab[i]);
+                               updateBoundingBox(xtab[i], ytab[i]);
+                       }
+                       _commands.add(new PolygonCommand(points, thickness));
+               }
+       }
+
+       public void drawPolygon(GeneralPath p, 
+                       double thickness) {
+               PathIterator pi = p.getPathIterator(null);
+               Vector<Point2D.Double> v = new Vector<Point2D.Double>();  
+               double[] coords = new double[6];
+               while (!pi.isDone())
+               {
+                       int code = pi.currentSegment(coords);
+                       if (code == PathIterator.SEG_MOVETO)
+                       { v.add(new Point2D.Double(coords[0],coords[1])); }
+                       if (code == PathIterator.SEG_LINETO)
+                       { v.add(new Point2D.Double(coords[0],coords[1])); }                     
+                       pi.next();
+               }
+               double[] xtab = new double[v.size()];
+               double[] ytab = new double[v.size()];
+               for(int i=0;i<v.size();i++)
+               {
+                       xtab[i] = v.get(i).x;
+                       ytab[i] = v.get(i).y;
+               }
+               drawPolygon(xtab,ytab, thickness);
+       }
+
+               
+       public void fillPolygon(GeneralPath p, 
+                       Color color) {
+               PathIterator pi = p.getPathIterator(null);
+               Vector<Point2D.Double> v = new Vector<Point2D.Double>();  
+               double[] coords = new double[6];
+               while (!pi.isDone())
+               {
+                       int code = pi.currentSegment(coords);
+                       if (code == PathIterator.SEG_MOVETO)
+                       { v.add(new Point2D.Double(coords[0],coords[1])); }
+                       if (code == PathIterator.SEG_LINETO)
+                       { v.add(new Point2D.Double(coords[0],coords[1])); }                     
+                       pi.next();
+               }
+               double[] xtab = new double[v.size()];
+               double[] ytab = new double[v.size()];
+               for(int i=0;i<v.size();i++)
+               {
+                       xtab[i] = v.get(i).x;
+                       ytab[i] = v.get(i).y;
+               }
+               fillPolygon(xtab,ytab, color);
+       }
+
+       
+       public void fillPolygon(double[] xtab, double[] ytab, 
+                       Color color) {
+               if (xtab.length == ytab.length) {
+                       Point2D.Double points[] = new Point2D.Double[xtab.length];
+                       for (int i = 0; i < xtab.length; i++) {
+                               points[i] = new Point2D.Double(xtab[i], ytab[i]);
+                               updateBoundingBox(xtab[i], ytab[i]);
+                       }
+                       _commands.add(new FillPolygonCommand(points, color));
+               }
+       }
+
+       public void setFont(int font, double size) {
+               _fontsize = size;
+               _font = font;
+               _commands.add(new FontCommand(font, size));
+       }
+
+       public void setScale(double sc) {
+               _scale = sc;
+       }
+
+       public double getScale() {
+               return _scale;
+       }
+
+       public Rectangle2D.Double getBoundingBox() {
+               return (new Rectangle2D.Double(_xmin, _ymin, _xmax - _xmin, _ymax
+                               - _ymin));
+       }
+
+       private Point2D.Double transform(Point2D.Double p, double factor,
+                       double dx, double dy) {
+               return transform(p.x, p.y, factor, dx, dy);
+       }
+
+       private Point2D.Double transform(double x, double y, double factor,
+                       double dx, double dy) {
+
+               return new Point2D.Double((x + dx) * factor, (y + dy) * factor);
+       }
+
+       public String export() {
+               Rectangle2D.Double oldbb = getBoundingBox();
+               double dx = -oldbb.x;
+               double dy = -oldbb.y;
+               Rectangle2D.Double nbb = new Rectangle2D.Double(0, 0, oldbb.width* _scale, oldbb.height * _scale);
+               StringBuffer buf = new StringBuffer();
+               buf.append(headerS(nbb));
+               if (_backgroundColor!= null)
+               {
+                       double w = oldbb.width* _scale;
+                       double h = oldbb.height* _scale;
+                       Point2D.Double[] tab = new      Point2D.Double[4];
+                       tab[0] = new Point2D.Double(0,0);
+                       tab[1] = new Point2D.Double(w,0);
+                       tab[2] = new Point2D.Double(w,h);
+                       tab[3] = new Point2D.Double(0,h);
+                   buf.append(this.fillPolygonS(tab, _backgroundColor));
+               }
+               for (int i = 0; i < _commands.size(); i++) {
+                       GraphicElement ge = _commands.elementAt(i);
+                       if (ge instanceof LineCommand) {
+                               LineCommand c = (LineCommand) ge;
+                               String tmp = drawLineS(transform(c.get_orig(), _scale, dx, dy),
+                                               transform(c.get_dest(), _scale, dx, dy), c
+                                                               .get_thickness());
+                               buf.append(tmp);
+                       } else if (ge instanceof TextCommand) {
+                               TextCommand c = (TextCommand) ge;
+                               String tmp = drawTextS(transform(c.get_base(), _scale, dx, dy),
+                                               c.get_txt());
+                               buf.append(tmp);
+                       } else if (ge instanceof RectangleCommand) {
+                               RectangleCommand c = (RectangleCommand) ge;
+                               String tmp = drawRectangleS(transform(c.get_orig(), _scale, dx,
+                                               dy), transform(c.get_dims(), _scale, 0.0, 0.0), c
+                                               .get_thickness());
+                               buf.append(tmp);
+                       } else if (ge instanceof CircleCommand) {
+                               CircleCommand c = (CircleCommand) ge;
+                               String tmp = drawCircleS(
+                                               transform(c.get_base(), _scale, dx, dy), c.get_radius()
+                                                               * _scale, c.get_thickness());
+                               buf.append(tmp);
+                       } else if (ge instanceof FillCircleCommand) {
+                               FillCircleCommand c = (FillCircleCommand) ge;
+                               String tmp = fillCircleS(
+                                               transform(c.get_base(), _scale, dx, dy), c.get_radius()
+                                                               * _scale, c.get_thickness(), c.get_color());
+                               buf.append(tmp);
+                       } else if (ge instanceof FontCommand) {
+                               FontCommand c = (FontCommand) ge;
+                               String tmp = setFontS(c.get_font(), c.get_size());
+                               buf.append(tmp);
+                       } else if (ge instanceof ColorCommand) {
+                               ColorCommand c = (ColorCommand) ge;
+                               String tmp = setColorS(c.getColor());
+                               buf.append(tmp);
+                       } else if (ge instanceof ArcCommand) {                          
+                               ArcCommand c = (ArcCommand) ge;
+                               String tmp = drawArcS(
+                                               transform(c.getCenter(), _scale, dx, dy), c.getWidth()
+                                                               * _scale, c.getHeight() * _scale, c
+                                                               .getStartAngle(), c.getEndAngle());
+                               buf.append(tmp);
+                       } else if (ge instanceof PolygonCommand) {
+                               PolygonCommand c = (PolygonCommand) ge;
+                               Point2D.Double[] points = c.get_points();
+                               for (int j = 0; j < points.length; j++) {
+                                       points[j] = transform(points[j], _scale, dx, dy);
+                               }
+                               String tmp = drawPolygonS(points, c.get_thickness());
+                               buf.append(tmp);
+                       } else if (ge instanceof FillPolygonCommand) {
+                               FillPolygonCommand c = (FillPolygonCommand) ge;
+                               Point2D.Double[] points = c.get_points();
+                               for (int j = 0; j < points.length; j++) {
+                                       points[j] = transform(points[j], _scale, dx, dy);
+                               }
+                               String tmp = fillPolygonS(points, c
+                                               .get_color());
+                               buf.append(tmp);
+                       }
+               }
+               buf.append(footerS());
+               return buf.toString();
+       }
+
+       public void reset() {
+
+       }
+       
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/SecStrProducerGraphics.java b/src2/fr/orsay/lri/varna/models/export/SecStrProducerGraphics.java
new file mode 100644 (file)
index 0000000..6f61ffc
--- /dev/null
@@ -0,0 +1,119 @@
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Shape;
+import java.awt.geom.Ellipse2D;
+import java.awt.geom.GeneralPath;
+import java.io.FileWriter;
+import java.io.IOException;
+
+import fr.orsay.lri.varna.exceptions.ExceptionWritingForbidden;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class SecStrProducerGraphics implements VueVARNAGraphics{
+       SecStrDrawingProducer _ss;
+       double _thickness;
+       Color _color;
+       
+       public SecStrProducerGraphics(SecStrDrawingProducer ss)
+       {
+               _ss = ss;
+       }
+
+       public void draw(GeneralPath s) {
+                       _ss.fillPolygon(s, getColor());
+       }
+       
+       public void drawArc(double x, double y, double rx, double ry,
+                       double angleStart, double angleEnd) {
+               // TODO Auto-generated method stub
+               
+       }
+       
+       public void drawLine(double x1, double y1, double x2, double y2) {
+               _ss.drawLine(x1, -y1, x2, -y2, _thickness);
+       }
+       
+       public void drawCircle(double x, double y, double r) {
+               _ss.drawCircle(x+0.5*r, -y-0.5*r, 0.5*r, _thickness);
+       }
+
+       public void drawRect(double x, double y, double w, double h) {
+               // TODO Auto-generated method stub
+               
+       }
+       
+       public void drawRoundRect(double x, double y, double w, double h,
+                       double rx, double ry) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void drawStringCentered(String res, double x, double y) {
+               _ss.drawText(x, -y, res);
+       }
+
+       public void fill(GeneralPath s) {
+               _ss.fillPolygon(s, getColor());
+       }
+       
+       public void fillCircle(double x, double y, double r) {
+               _ss.fillCircle(x+0.5*r, -y-0.5*r, 0.5*r,  _thickness, _ss.getCurrentColor());
+       }
+
+       public void fillRect(double x, double y, double w, double h) {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void fillRoundRect(double x, double y, double w, double h,
+                       double rx, double ry) {
+               // TODO Auto-generated method stub
+               
+       }
+       public Color getColor() {
+               return _ss.getCurrentColor();
+       }
+       
+       public Dimension getStringDimension(String s) {
+               // TODO Auto-generated method stub
+               return null;
+       }
+
+       public void setColor(Color c) {
+               _ss.setColor(c);
+       }
+       
+       public void setSelectionStroke() {
+               // TODO Auto-generated method stub
+               
+       }
+       
+       public void setFont(Font f) {
+               //System.out.println("Font "+f.getSize2D());
+               _ss.setFont(_ss.FONT_HELVETICA_BOLD,f.getSize2D());
+       }
+
+       public void setPlainStroke() {
+               // TODO Auto-generated method stub
+               
+       }
+
+       public void setStrokeThickness(double t) {
+               _thickness = t;
+       }
+       
+       public void saveToDisk(String path) throws ExceptionWritingForbidden
+       {
+               FileWriter fout;
+               try {
+                       fout = new FileWriter(path);
+                       fout.write(_ss.export());
+                       fout.close();
+               } catch (IOException e) {
+                       throw new ExceptionWritingForbidden(e.getMessage());
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/SwingGraphics.java b/src2/fr/orsay/lri/varna/models/export/SwingGraphics.java
new file mode 100644 (file)
index 0000000..a4bba5c
--- /dev/null
@@ -0,0 +1,135 @@
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics2D;
+import java.awt.Shape;
+import java.awt.Stroke;
+import java.awt.geom.Arc2D.Double;
+import java.awt.geom.Ellipse2D;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Rectangle2D;
+
+public class SwingGraphics implements VueVARNAGraphics {
+       private BasicStroke _dashedStroke;
+       private BasicStroke _plainStroke;
+       Graphics2D _g2d;
+       private boolean _debug = false;
+
+       
+       public SwingGraphics(Graphics2D g2d)
+       {
+               _g2d = g2d;
+               float[] dash = { 5.0f, 5.0f };
+               _dashedStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND,    BasicStroke.JOIN_ROUND, 3.0f, dash, 0);
+               _plainStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND,     BasicStroke.JOIN_ROUND, 3.0f);
+       }
+       
+       public Dimension getStringDimension(String s) {
+               FontMetrics fm = _g2d.getFontMetrics();
+               Rectangle2D r = fm.getStringBounds(s, _g2d);
+               return (new Dimension((int) r.getWidth(), (int) fm.getAscent()
+                               - fm.getDescent()));
+       }
+
+       public void drawStringCentered(String res, double x,
+                       double y) {
+               Dimension d = getStringDimension(res);
+               x -= (double) d.width / 2.0;
+               y += (double) d.height / 2.0;
+               if (_debug)
+               {
+                   Stroke bck = _g2d.getStroke();
+                   _g2d.setStroke(_plainStroke);
+                   _g2d.draw(new Rectangle2D.Double(x, y - d.height, d.width, d.height));
+                   _g2d.setStroke(bck);
+               }
+               _g2d.drawString(res, (float) (x), (float) (y));
+       }
+
+       public void draw(GeneralPath s) {
+               _g2d.draw(s);
+       }
+
+       public void drawArc(double x, double y, double rx, double ry,
+                       double angleStart, double angleEnd) {
+               _g2d.drawArc((int) (x-rx/2.), (int) (y-ry/2.), (int) rx, (int) ry, (int) angleStart, (int) angleEnd);   
+       }
+
+       public void drawLine(double x1, double y1, double x2, double y2) {
+               _g2d.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
+       }
+
+       public void drawCircle(double x, double y, double r) {
+               _g2d.draw(new Ellipse2D.Double(x, y, r, r));
+       }
+
+       public void drawRect(double x, double y, double w, double h) {
+               _g2d.drawRect((int)x, (int)y, (int)w, (int)h);
+       }
+
+       public void drawRoundRect(double x, double y, double w, double h,
+                       double rx, double ry) {
+               _g2d.drawRoundRect((int)x, (int)y, (int)w, (int)h, (int)rx, (int)ry);
+       }
+
+       public void drawString(String s, double x, double y) {
+               _g2d.drawString(s, (float)x, (float)y);
+       }
+
+       public void fill(GeneralPath s) {
+               _g2d.fill(s);
+       }
+
+       public void fillCircle(double x, double y, double r) {
+               _g2d.fill(new Ellipse2D.Double(x, y, r, r));
+       }
+
+       public void fillRect(double x, double y, double w, double h) {
+               _g2d.fill(new Rectangle2D.Double(x, y, w, h));
+       }
+
+       public void fillRoundRect(double x, double y, double w, double h,
+                       double rx, double ry) {
+               _g2d.fillRoundRect((int)x, (int)y, (int)w, (int)h, (int)rx, (int)ry);
+       }
+
+       public Color getColor() {
+               return _g2d.getColor();
+       }
+
+       public void setColor(Color c) {
+               _g2d.setColor(c);
+       }
+
+       public void setSelectionStroke() {
+               _g2d.setStroke(_dashedStroke);
+       }
+
+       public void setFont(Font f) {
+               _g2d.setFont(f);
+       }
+
+       public void setPlainStroke() {
+               _g2d.setStroke(_plainStroke);
+       }
+       
+       private BasicStroke deriveStroke(BasicStroke s, double t)
+       {
+               return new BasicStroke((float)t, s.getEndCap(), s.getLineJoin(), s.getMiterLimit(), s.getDashArray(), s.getDashPhase()) ;
+       }
+
+       public void setStrokeThickness(double t) {
+               boolean dashed = (_g2d.getStroke()==_dashedStroke); 
+               _plainStroke = deriveStroke(_plainStroke, t);
+               //_dashedStroke = deriveStroke(_dashedStroke, t);
+               if(dashed)
+               {  _g2d.setStroke(_dashedStroke); }
+               else
+               { _g2d.setStroke(_plainStroke); }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/TextCommand.java b/src2/fr/orsay/lri/varna/models/export/TextCommand.java
new file mode 100644 (file)
index 0000000..daf05e8
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.geom.Point2D;
+
+public class TextCommand extends GraphicElement {
+       private Point2D.Double _base;
+       private String _txt;
+
+       public TextCommand(Point2D.Double base, String txt) {
+               _base = base;
+               _txt = txt;
+       }
+
+       public Point2D.Double get_base() {
+               return _base;
+       }
+
+       public String get_txt() {
+               return _txt;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/TikzExport.java b/src2/fr/orsay/lri/varna/models/export/TikzExport.java
new file mode 100644 (file)
index 0000000..d98f316
--- /dev/null
@@ -0,0 +1,168 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.geom.Point2D.Double;
+import java.util.Hashtable;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+public class TikzExport extends SecStrDrawingProducer {
+
+
+       public TikzExport()
+       {
+               super();
+               super.setScale(0.2);
+       }
+       
+
+       private String TikzHeader() {
+               return   "\\documentclass[tikz,border=10pt]{standalone}\n"
+                               +"\\usepackage{tikz,relsize}\n"
+                               +"\\usetikzlibrary{positioning}\n"
+                               +"\\begin{document}\n"
+                               +"\\begin{tikzpicture}[inner sep=0, fill=none,draw=none,text=none,font={\\sf}]\n";
+       }
+
+       private String formatPoint(Point2D.Double p)
+       {
+               return formatPoint(p.x,p.y);
+       }
+
+       private String formatPoint(double x, double y)
+       {
+               return "("+(super.getScale()*x)+","+(super.getScale()*y)+")";
+       }
+
+       public String drawCircleS(Point2D.Double p, double radius, double thickness) {
+               return "  \\draw[draw=currColor] "+formatPoint(p)+" circle ("+(radius*super.getScale())+");\n";
+       }
+
+       public String fillCircleS(Point2D.Double p, double radius,
+                       double thickness, Color col) {
+               return setColorS(col)
+                       +"  \\fill[fill=currColor] "+formatPoint(p)+" circle ("+(radius*super.getScale())+");\n";
+       }
+
+
+       public String drawLineS(Point2D.Double p0, Point2D.Double p1,
+                       double thickness) {
+               return "  \\draw[draw=currColor] "+formatPoint(p0)+" -- "+formatPoint(p1)+";\n";
+       }
+
+       public String drawRectangleS(Point2D.Double p, Point2D.Double dims,
+                       double thickness) {
+               return "  \\draw[draw=currColor] "+formatPoint(p)+" -- "+formatPoint(p.x+dims.x,p.y)+" -- "+formatPoint(p.x+dims.x,p.y+dims.y)+" -- "+formatPoint(p.x,p.y+dims.y)+" -- "+formatPoint(p)+";\n";
+       }
+
+       public String drawTextS(Point2D.Double p, String txt) {
+               return "  \\node[text=currColor] at "+formatPoint(p)+" {"+txt+"};\n";
+       }
+
+       public String setFontS(int font, double size) {
+               _font = font;
+               _fontsize = 1.2 * size;
+               return "";
+       }
+
+       public String setColorS(Color col) {
+               super.setColorS(col);
+               return "\\definecolor{currColor}{rgb}{"+(((double)col.getRed())/255.)+","+(((double)col.getGreen())/255.)+","+(((double)col.getBlue())/255.)+"}\n";
+       }
+
+       public String footerS() {
+               return "\\end{tikzpicture}\n"
+                       +  "\\end{document}";
+       }
+
+       public String headerS(Rectangle2D.Double bb) {
+               return TikzHeader();
+       }
+
+       @Override
+       public String drawArcS(Point2D.Double origine, double width, double height,
+                       double startAngle, double endAngle) {
+               return "";
+
+       }
+
+       @Override
+       public String drawPolygonS(Double[] points, double thickness) {
+               if (points.length > 0) {
+                       String result = "\\draw[draw=currColor] ";
+                       for (int i = 0; i < points.length; i++) {
+                               result += ""+formatPoint(points[i])+" -- ";
+                       }
+                       result += ""+formatPoint(points[0])+";";
+                       return result;
+               } else {
+                       return "";
+               }
+       }
+
+       @Override
+       public String fillPolygonS(Double[] points,  Color col) {
+               if (points.length > 0) {
+                       String result = "\\fill[fill=currColor] ";
+                       for (int i = 0; i < points.length; i++) {
+                               result += ""+formatPoint(points[i])+" -- ";
+                       }
+                       result += ""+formatPoint(points[0])+";";
+                       return setColorS(col)
+                                       +result;
+               } else {
+                       return setColorS(col);
+               }
+       }
+       
+       @Override
+       public String drawBaseStartS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBaseEndS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBasePairStartS(int i, int j, ModeleBP bps) {
+               return "";
+       }
+
+       @Override
+       public String drawBasePairEndS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBackboneStartS(int i, int j) {
+               return "";
+       }
+
+       @Override
+       public String drawBackboneEndS(int index) {
+               return "";
+       }
+
+
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/export/VueVARNAGraphics.java b/src2/fr/orsay/lri/varna/models/export/VueVARNAGraphics.java
new file mode 100644 (file)
index 0000000..7737abf
--- /dev/null
@@ -0,0 +1,31 @@
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Shape;
+import java.awt.Stroke;
+import java.awt.geom.GeneralPath;
+
+public interface VueVARNAGraphics {
+       public Dimension getStringDimension(String s);
+       public void drawStringCentered(String res, double x, double y);
+       public void setColor(Color c);
+       public Color getColor();
+       public void drawLine(double x1, double y1, double x2, double y2);
+       public void drawRect(double x, double y, double w, double h);
+       public void fillRect(double x, double y, double w, double h);
+       public void drawCircle(double x, double y, double r);
+       public void fillCircle(double x, double y, double r);
+       public void drawRoundRect(double x, double y, double w, double h, double rx, double ry); 
+       public void fillRoundRect(double x, double y, double w, double h, double rx, double ry); 
+       public void drawArc(double x, double y, double rx, double ry, double angleStart, double angleEnd);
+       //public void drawString(String s, double x, double y);
+       public void draw(GeneralPath s);
+       public void fill(GeneralPath s);
+       public void setFont(Font f);
+       public void setSelectionStroke();
+       public void setPlainStroke();
+       public void setStrokeThickness(double t);
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/export/XFIGExport.java b/src2/fr/orsay/lri/varna/models/export/XFIGExport.java
new file mode 100644 (file)
index 0000000..179a3ac
--- /dev/null
@@ -0,0 +1,237 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.export;
+
+import java.awt.Color;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.geom.Point2D.Double;
+import java.util.Hashtable;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+public class XFIGExport extends SecStrDrawingProducer {
+
+       private int _font = SecStrDrawingProducer.FONT_TIMES_ROMAN;
+       @SuppressWarnings("unused")
+       private StringBuffer buf = new StringBuffer();
+
+       private Hashtable<Color, Integer> _definedCols = new Hashtable<Color, Integer>();
+
+       // From XFig 3.2 file format, indexed RGB colors are in the range [32,543]
+       private int _nextColCode = 32;
+       private final static int UPPER_BOUND_COLOR_CODE = 543;
+
+       public XFIGExport()
+       {
+               super();
+               super.setScale(20.0);
+       }
+       
+       
+       private String ensureColorDefinition(Color col) {
+               if (!_definedCols.containsKey(col)) {
+                       if (_nextColCode < UPPER_BOUND_COLOR_CODE) {
+                               int curColorCode = _nextColCode;
+                               _definedCols.put(col, curColorCode);
+                               _nextColCode++;
+
+                               String RGBR = Integer.toHexString(col.getRed());
+                               if (RGBR.length() < 2) {
+                                       RGBR = "0" + RGBR;
+                               }
+                               String RGBG = Integer.toHexString(col.getGreen());
+                               if (RGBG.length() < 2) {
+                                       RGBG = "0" + RGBG;
+                               }
+                               String RGBB = Integer.toHexString(col.getBlue());
+                               if (RGBB.length() < 2) {
+                                       RGBB = "0" + RGBB;
+                               }
+                               String RGBHex = "#" + RGBR + RGBG + RGBB;
+                               RGBHex = RGBHex.toUpperCase();
+                               return "0 " + curColorCode + " " + RGBHex + "\n";
+                       }
+               }
+               return "";
+       }
+
+       private int getColorCode(Color col) {
+               if (_definedCols.containsKey(col)) {
+                       return _definedCols.get(col);
+               }
+               return 0;
+       }
+
+       private int getCurColorCode() {
+               if (_definedCols.containsKey(_curColor)) {
+                       return _definedCols.get(_curColor);
+               }
+               return 0;
+       }
+
+       private String XFIGHeader() {
+               return "#FIG 3.2\n" + "Landscape\n" + "Center\n" + "Inches\n"
+                               + "Letter  \n" + "100.00\n" + "Single\n" + "-2\n" + "1200 2\n";
+       }
+
+       public String drawCircleS(Point2D.Double p, double radius, double thickness) {
+               return ("1 3 0 " + (long) thickness + " " + getCurColorCode()
+                               + " 7 50 -1 -1 0.000 1 0.0000 " + (long) p.x + " "
+                               + (long) -p.y + " " + (long) radius + " " + (long) radius + " 1 1 1 1\n");
+       }
+
+       public String drawLineS(Point2D.Double p0, Point2D.Double p1,
+                       double thickness) {
+               return ("2 1 0 " + (long) thickness + " " + getCurColorCode()
+                               + " 7 60 -1 -1 0.000 0 0 -1 0 0 2\n" + " " + (long) p0.x + " "
+                               + (long) -p0.y + " " + (long) p1.x + " " + (long) -p1.y + "\n");
+       }
+
+       public String drawRectangleS(Point2D.Double p, Point2D.Double dims,
+                       double thickness) {
+               return ("2 2 0 " + (long) thickness + " " + getCurColorCode()
+                               + " 7 50 -1 -1 0.000 0 0 -1 0 0 5\n" + "\t " + (long) (p.x)
+                               + " " + (long) (-p.y) + " " + (long) (p.x + dims.x) + " "
+                               + (long) (-p.y) + " " + (long) (p.x + dims.x) + " "
+                               + (long) -(p.y + dims.y) + " " + (long) (p.x) + " "
+                               + (long) -(p.y + dims.y) + " " + (long) (p.x) + " "
+                               + (long) -(p.y) + "\n");
+       }
+
+       public String drawTextS(Point2D.Double p, String txt) {
+               return ("4 1 " + getCurColorCode() + " 40 -1 " + _font + " "
+                               + (long) _fontsize + " 0.0000 6 " + (long) 4 * _fontsize + " "
+                               + (long) (2 * _fontsize) + " " + (long) (p.x) + " "
+                               + (long) -(p.y - 6 * _fontsize) + " " + txt + "\\001\n");
+       }
+
+       public String fillCircleS(Point2D.Double p, double radius,
+                       double thickness, Color col) {
+               String coldef = ensureColorDefinition(col);
+               return (coldef + "1 3 0 " + (long) thickness + " 0 "
+                               + getColorCode(col) + " 50 0 20 0.000 1 0.0000 " + (long) p.x
+                               + " " + (long) -p.y + " " + (long) radius + " " + (long) radius + " 1 1 1 1\n");
+       }
+
+       public String setFontS(int font, double size) {
+               _font = font;
+               _fontsize = 1.2 * size;
+               return "";
+       }
+
+       public String setColorS(Color col) {
+               super.setColorS(col);
+               return (ensureColorDefinition(col));
+       }
+
+       public String footerS() {
+               return "";
+       }
+
+       public String headerS(Rectangle2D.Double bb) {
+               return XFIGHeader();
+       }
+
+       @Override
+       public String drawArcS(Point2D.Double origine, double width, double height,
+                       double startAngle, double endAngle) {
+               double p1x = origine.x;
+               double p1y = -origine.y;
+               double p2x = origine.x + width / 2.0;
+               double p2y = -origine.y - height / 2.0;
+               double p3x = origine.x + width;
+               double p3y = p1y;
+               double cx = (p1x + p3x) / 2.0;
+               double cy = p3y + height / 2.0;
+               return ("5 1 0 1 " + getCurColorCode() + " 7 50 0 -1 4.000 0 0 0 0 "
+                               + cx + " " + cy + " " + (int) p1x + " " + (int) p1y + " "
+                               + (int) p2x + " " + (int) p2y + " " + (int) p3x + " "
+                               + (int) p3y + "\n");
+
+       }
+
+       @Override
+       public String drawPolygonS(Double[] points, double thickness) {
+               if (points.length > 0) {
+                       String result = "2 3 0 1 " + getCurColorCode()
+                                       + " 7 40 0 -1 4.000 0 0 0 0 0 " + (points.length + 1)
+                                       + "\n";
+                       for (int i = 0; i < points.length; i++) {
+                               result += (int) Math.round(points[i].x) + " "
+                                               + (int) Math.round(-points[i].y) + " ";
+                       }
+                       result += (int) Math.round(points[0].x) + " "
+                                       + (int) Math.round(-points[0].y) + " ";
+                       result += "\n";
+                       return result;
+               } else {
+                       return "";
+               }
+       }
+
+       @Override
+       public String fillPolygonS(Double[] points,  Color col) {
+               if (points.length > 0) {
+                       String coldef = ensureColorDefinition(col);
+                       String result = "2 3 0 1 0 " + getColorCode(col)
+                                       + " 35 0 0 4.000 0 0 0 0 0 " + (points.length + 1) + "\n";
+                       for (int i = 0; i < points.length; i++) {
+                               result += (int) Math.round(points[i].x) + " "
+                                               + (int) Math.round(-points[i].y) + " ";
+                       }
+                       result += (int) Math.round(points[0].x) + " "
+                                       + (int) Math.round(-points[0].y) + " ";
+                       result += "\n";
+                       return coldef + result;
+               } else {
+                       return "";
+               }
+       }
+
+       @Override
+       public String drawBaseStartS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBaseEndS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBasePairStartS(int i, int j, ModeleBP bps) {
+               return "";
+       }
+
+       @Override
+       public String drawBasePairEndS(int index) {
+               return "";
+       }
+
+       @Override
+       public String drawBackboneStartS(int i, int j) {
+               return "";
+       }
+
+       @Override
+       public String drawBackboneEndS(int index) {
+               return "";
+       }
+
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/geom/ComputeArcCenter.java b/src2/fr/orsay/lri/varna/models/geom/ComputeArcCenter.java
new file mode 100644 (file)
index 0000000..0aa8ebf
--- /dev/null
@@ -0,0 +1,54 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.geom;
+
+public class ComputeArcCenter {
+       
+       /**
+        * Given an arc length (l) and segment length (delta) of the arc,
+        * find where to put the center, returned as a position of the perpendicular
+        * bisector of the segment. The positive side is the one where the arc is drawn.
+        * It works using Newton's method.
+        */
+       public static double computeArcCenter(double delta, double l) {
+               double x_n = 0;
+               double x_n_plus_1, f_x_n, f_x_n_plus_1;
+               f_x_n = f(x_n,delta);
+               while (true) {
+                       x_n_plus_1 = x_n - (f_x_n - l)/fprime(x_n,delta);
+                       f_x_n_plus_1 = f(x_n_plus_1,delta);
+                       // We want a precision of 0.1 on arc length
+                       if (x_n_plus_1 == Double.NEGATIVE_INFINITY || Math.abs(f_x_n_plus_1 - f_x_n) < 0.1) {
+                               //System.out.println("computeArcCenter: steps = " + steps + "    result = " + x_n_plus_1);
+                               return x_n_plus_1;
+                       }
+                       x_n = x_n_plus_1;
+                       f_x_n = f_x_n_plus_1;
+               }
+       }
+       
+       private static double f(double c, double delta) {
+               if (c < 0) {
+                       return 2*Math.atan(delta/(-2*c)) * Math.sqrt(delta*delta/4 + c*c);
+               } else if (c != 0) { // c > 0
+                       return (2*Math.PI - 2*Math.atan(delta/(2*c))) * Math.sqrt(delta*delta/4 + c*c);
+               } else { // c == 0
+                       return Math.PI * Math.sqrt(delta*delta/4 + c*c);
+               }
+       }
+       
+       /**
+        * d/dc f(c,delta)
+        */
+       private static double fprime(double c, double delta) {
+               if (c < 0) {
+                       return delta/(c*c + delta/4)*Math.sqrt(delta*delta/4 + c*c) + 2*Math.atan(delta/(-2*c))*c/Math.sqrt(delta*delta/4 + c*c);
+               } else if (c != 0) { // c > 0
+                       return delta/(c*c + delta/4)*Math.sqrt(delta*delta/4 + c*c) + (2*Math.PI - 2*Math.atan(delta/(-2*c)))*c/Math.sqrt(delta*delta/4 + c*c);
+               } else { // c == 0
+                       return 2;
+               }
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/geom/ComputeEllipseAxis.java b/src2/fr/orsay/lri/varna/models/geom/ComputeEllipseAxis.java
new file mode 100644 (file)
index 0000000..b8d699b
--- /dev/null
@@ -0,0 +1,92 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.geom;
+
+public class ComputeEllipseAxis {
+       public static boolean debug = false;
+       
+       /**
+        * Given one axis half-length b and the circumference l,
+        * find the other axis half-length a.
+        * Returns 0 if there is no solution.
+        * Implemented with Newton's method.
+        */
+       public static double computeEllipseAxis(double b, double l) {
+               if (l/4 <= b || b <= 0 || l <= 0) {
+                       // No such ellipse can exist.
+                       return 0;
+               } else {
+                       int steps = 0;
+                       double x_n = 10;
+                       double x_n_plus_1, f_x_n, f_x_n_plus_1;
+                       f_x_n = f(x_n,b) - l;
+                       while (true) {
+                               //System.out.println("x_n = " + x_n + "  f(x_n)=" + f_x_n);
+                               x_n_plus_1 = x_n - f_x_n/fprime(x_n,b);
+                               f_x_n_plus_1 = f(x_n_plus_1,b) - l;
+                               if (x_n_plus_1 < 0) {
+                                       System.out.println("ComputeEllipseAxis: x_n < 0 => returning 0");
+                                       return 0;
+                               }
+                               // We want a precision of 0.01 on arc length
+                               if (Math.abs(f_x_n_plus_1 - f_x_n) < 0.01) {
+                                       if (debug) System.out.println("#steps = " + steps);
+                                       return x_n_plus_1;
+                               }
+                               x_n = x_n_plus_1;
+                               f_x_n = f_x_n_plus_1;
+                               steps++;
+                       }
+               }
+       }
+       
+       
+       
+       private static double f(double a, double b) {
+               // This is Ramanujan's approximation of an ellipse circumference
+               // Nice because it is fast to compute (no need to compute an integral)
+               // and the derivative is also simple (and fast to compute).
+               return Math.PI*(3*(a+b) - Math.sqrt(10*a*b + 3*(a*a + b*b)));
+       }
+       
+       private static double fprime(double a, double b) {
+               return Math.PI*(3 - (5*b + 3*a)/Math.sqrt(10*a*b + 3*(a*a + b*b)));
+       }
+       
+       
+       /*
+       private static void test(double a, double b, double l) {
+               double a2 = computeEllipseAxis(b, l);
+               System.out.println("true a=" + a + " l=" + l + "   estimated a=" + a2 + " l(from true a)=" + f(a,b));
+       }
+       
+       private static void test(double b, double l) {
+               double a2 = computeEllipseAxis(b, l);
+               System.out.println("true l=" + l + "   estimated a=" + a2);
+       }
+       
+       
+       public static void main(String[] args) {
+               double b = 4;
+               test(100, b, 401.3143);
+               test(7, b, 35.20316);
+               test(4, b, 25.13274);
+               test(1, b, 17.15684);
+               test(0.5, b, 16.37248);
+               test(0.25, b, 16.11448);
+               test(0.1, b, 16.02288);
+               test(0.01, b, 16.00034);
+               test(0, b, 16);
+               test(10000, b, 40000.03);
+       }
+       */
+       
+       /*
+       public static void main(String[] args) {
+               test(222.89291150684895, 2240);
+       }
+       */
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/geom/CubicBezierCurve.java b/src2/fr/orsay/lri/varna/models/geom/CubicBezierCurve.java
new file mode 100644 (file)
index 0000000..7ff9aaf
--- /dev/null
@@ -0,0 +1,205 @@
+package fr.orsay.lri.varna.models.geom;
+
+
+import java.awt.geom.Point2D;
+
+/**
+ * This class implements a cubic Bezier curve
+ * with a constant speed parametrization.
+ * The Bezier curve is approximated by a sequence of n straight lines,
+ * where the n+1 points between the lines are
+ * { B(k/n), k=0,1,...,n } where B is the standard
+ * parametrization given here:
+ * http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
+ * You can then use the constant speed parametrization over this sequence
+ * of straight lines.
+ * 
+ * @author Raphael Champeimont
+ */
+public class CubicBezierCurve {
+       
+       /**
+        * The four points defining the curve.
+        */
+       private Point2D.Double P0, P1, P2, P3;
+       
+
+       
+       private int n;
+       /**
+        * The number of lines approximating the Bezier curve.
+        */
+       public int getN() {
+               return n;
+       }
+       
+       
+       /**
+        * Get the (exact) length of the approximation curve.
+        */
+       public double getApproxCurveLength() {
+               return lengths[n-1];
+       }
+       
+       
+       
+       /**
+        * The n+1 points between the n lines.
+        */
+       private Point2D.Double[] points;
+       
+       
+       
+       /**
+        * Array of length n.
+        * lengths[i] is the sum of lengths of lines up to and including the
+        * line starting at point points[i]. 
+        */
+       private double[] lengths;
+       
+       
+       /**
+        * Array of length n.
+        * The vectors along each line, with a norm of 1.
+        */
+       private Point2D.Double[] unitVectors; 
+       
+       
+       
+       /**
+        * The standard exact cubic Bezier curve parametrization.
+        * Argument t must be in [0,1].
+        */
+       public Point2D.Double standardParam(double t) {
+               double x = Math.pow(1-t,3) * P0.x
+                 + 3 * Math.pow(1-t,2) * t * P1.x
+                 + 3 * (1-t) * t * t * P2.x
+                 + t * t * t * P3.x;
+               double y = Math.pow(1-t,3) * P0.y
+                 + 3 * Math.pow(1-t,2) * t * P1.y
+                 + 3 * (1-t) * t * t * P2.y
+                 + t * t * t * P3.y;
+               return new Point2D.Double(x, y);
+       }
+       
+       
+       
+
+       
+       /**
+        * Uniform approximated parameterization.
+        * A value in t must be in [0, getApproxCurveLength()].
+        * We have built a function f such that f(t) is the position of
+        * the point on the approximation curve (n straight lines).
+        * The interesting property is that the length of the curve
+        * { f(t), t in [0,l] } is exactly l.
+        * The java function is simply the application of f over each element
+        * of a sorted array, ie. uniformParam(t)[k] = f(t[k]).
+        * Computation time is O(n+m) where n is the number of lines in which
+        * the curve is divided and m is the length of the array given as an
+        * argument. The use of a sorted array instead of m calls to the
+        * function enables us to have a complexity of O(n+m) instead of O(n*m)
+        * because we don't need to search in all the n possible lines for
+        * each value in t (as we know their are in increasing order).
+        */
+       public Point2D.Double[] uniformParam(double[] t) {
+               int m = t.length;
+               Point2D.Double[] result = new Point2D.Double[m];
+               int line = 0;
+               for (int i=0; i<m; i++) {
+                       while ((line<n) && (lengths[line] < t[i])) {
+                               line++;
+                       }
+                       if (line >= n) {
+                               // In theory should not happen, but float computation != math.
+                               line = n-1;
+                       }
+                       if (t[i] < 0) {
+                               throw (new IllegalArgumentException("t[" + i + "] < 0"));
+                       }
+                       // So now we know on which line we are
+                       double lengthOnLine = t[i] - (line != 0 ? lengths[line-1] : 0);
+                       double x = points[line].x + unitVectors[line].x * lengthOnLine;
+                       double y = points[line].y + unitVectors[line].y * lengthOnLine;
+                       result[i] = new Point2D.Double(x, y);
+               }
+               return result;
+       }
+       
+       
+       
+       /**
+        * A Bezier curve can be defined by four points,
+        * see http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
+        * Here we give this four points and a integer to say in how many
+        * line segments we want to cut the Bezier curve (if n is bigger 
+        * the computation takes longer but the precision is better).
+        * The number of lines must be at least 1.
+        */
+       public CubicBezierCurve(
+                       Point2D.Double P0,
+                       Point2D.Double P1,
+                       Point2D.Double P2,
+                       Point2D.Double P3,
+                       int n) {
+               this.P0 = P0;
+               this.P1 = P1;
+               this.P2 = P2;
+               this.P3 = P3;
+               this.n = n;
+               if (n < 1) {
+                       throw (new IllegalArgumentException("n must be at least 1"));
+               }
+               computeData();
+       }
+
+       
+       private void computeData() {
+               points = new Point2D.Double[n+1];
+               for (int k=0; k<=n; k++) {
+                       points[k] = standardParam(((double) k) / n);
+               }
+               
+               lengths = new double[n];
+               unitVectors = new Point2D.Double[n];
+               double sum = 0;
+               for (int i=0; i<n; i++) {
+                       double l = lineLength(points[i], points[i+1]);
+                       double dx = (points[i+1].x - points[i].x) / l;
+                       double dy = (points[i+1].y - points[i].y) / l;
+                       unitVectors[i] = new Point2D.Double(dx, dy);
+                       sum += l;
+                       lengths[i] = sum;
+               }
+               
+
+               
+       }
+       
+       
+       private double lineLength(Point2D.Double P1, Point2D.Double P2) {
+               return P2.distance(P1);
+       }
+       
+       
+       public Point2D.Double getP0() {
+               return P0;
+       }
+
+       public Point2D.Double getP1() {
+               return P1;
+       }
+
+       public Point2D.Double getP2() {
+               return P2;
+       }
+
+       public Point2D.Double getP3() {
+               return P3;
+       }
+
+
+
+
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/geom/HalfEllipse.java b/src2/fr/orsay/lri/varna/models/geom/HalfEllipse.java
new file mode 100644 (file)
index 0000000..d4155df
--- /dev/null
@@ -0,0 +1,192 @@
+package fr.orsay.lri.varna.models.geom;
+
+
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Point2D;
+
+
+/**
+ * Ellipse, with axis = X and Y.
+ * This class is useful for constant speed parameterization
+ * (just like CubicBezierCurve).
+ * The ellipse drawn is in fact an half-ellipse, from 0 to PI.
+ * 
+ * @author Raphael Champeimont
+ */
+public class HalfEllipse {
+       
+       /**
+        * The four points defining the curve.
+        */
+       private double a, b;
+       
+
+       
+       private int n;
+       /**
+        * The number of lines approximating the curve.
+        */
+       public int getN() {
+               return n;
+       }
+       
+       
+       /**
+        * Get the (exact) length of the approximation curve.
+        */
+       public double getApproxCurveLength() {
+               return lengths[n-1];
+       }
+       
+       
+       
+       /**
+        * The n+1 points between the n lines.
+        */
+       private Point2D.Double[] points;
+       
+       
+       
+       /**
+        * Array of length n.
+        * lengths[i] is the sum of lengths of lines up to and including the
+        * line starting at point points[i]. 
+        */
+       private double[] lengths;
+       
+       
+       /**
+        * Array of length n.
+        * The vectors along each line, with a norm of 1.
+        */
+       private Point2D.Double[] unitVectors; 
+       
+       
+       
+       /**
+        * The standard ellipse parameterization.
+        * Argument t must be in [0,1].
+        */
+       public Point2D.Double standardParam(double t) {
+               double x = a*Math.cos(t*Math.PI);
+               double y = b*Math.sin(t*Math.PI);
+               return new Point2D.Double(x, y);
+       }
+       
+       
+       
+
+       
+       /**
+        * Uniform approximated parameterization.
+        * A value in t must be in [0, getApproxCurveLength()].
+        * We have built a function f such that f(t) is the position of
+        * the point on the approximation curve (n straight lines).
+        * The interesting property is that the length of the curve
+        * { f(t), t in [0,l] } is exactly l.
+        * The java function is simply the application of f over each element
+        * of a sorted array, ie. uniformParam(t)[k] = f(t[k]).
+        * Computation time is O(n+m) where n is the number of lines in which
+        * the curve is divided and m is the length of the array given as an
+        * argument. The use of a sorted array instead of m calls to the
+        * function enables us to have a complexity of O(n+m) instead of O(n*m)
+        * because we don't need to search in all the n possible lines for
+        * each value in t (as we know their are in increasing order).
+        */
+       public Point2D.Double[] uniformParam(double[] t) {
+               int m = t.length;
+               Point2D.Double[] result = new Point2D.Double[m];
+               int line = 0;
+               for (int i=0; i<m; i++) {
+                       while ((line<n) && (lengths[line] < t[i])) {
+                               line++;
+                       }
+                       if (line >= n) {
+                               // In theory should not happen, but float computation != math.
+                               line = n-1;
+                       }
+                       if (t[i] < 0) {
+                               throw (new IllegalArgumentException("t[" + i + "] < 0"));
+                       }
+                       // So now we know on which line we are
+                       double lengthOnLine = t[i] - (line != 0 ? lengths[line-1] : 0);
+                       double x = points[line].x + unitVectors[line].x * lengthOnLine;
+                       double y = points[line].y + unitVectors[line].y * lengthOnLine;
+                       result[i] = new Point2D.Double(x, y);
+               }
+               return result;
+       }
+       
+       
+       
+       /**
+        * An ellipse that has axis equal to X and Y axis needs only
+        * two numbers (half-axis lengths) to be defined.
+        * They are resp. a for X axis and b for Y axis.
+        * n = how many line segments we want to cut the curve
+        * (if n is bigger the computation takes longer but the precision is better).
+        * The number of lines must be at least 1.
+        */
+       public HalfEllipse(double a, double b, int n) {
+               this.a = a;
+               this.b = b;
+               this.n = n;
+               if (n < 1) {
+                       throw (new IllegalArgumentException("n must be at least 1"));
+               }
+               computeData();
+       }
+       
+       
+       /**
+        * Returns that affine transform that moves the ellipse
+        * given by this class such that its 0/pi axis matches P0-P1.
+        */
+       public static AffineTransform matchAxisA(Point2D.Double P0, Point2D.Double P1) {
+               double theta = MiscGeom.angleFromVector(P0.x-P1.x, P0.y-P1.y);
+               Point2D.Double mid = new Point2D.Double((P0.x+P1.x)/2, (P0.y+P1.y)/2);
+               AffineTransform transform = new AffineTransform();
+               transform.translate(mid.x, mid.y);
+               transform.rotate(theta);
+               return transform;
+       }
+
+       
+       private void computeData() {
+               points = new Point2D.Double[n+1];
+               for (int k=0; k<=n; k++) {
+                       points[k] = standardParam(((double) k) / n);
+               }
+               
+               lengths = new double[n];
+               unitVectors = new Point2D.Double[n];
+               double sum = 0;
+               for (int i=0; i<n; i++) {
+                       double l = lineLength(points[i], points[i+1]);
+                       double dx = (points[i+1].x - points[i].x) / l;
+                       double dy = (points[i+1].y - points[i].y) / l;
+                       unitVectors[i] = new Point2D.Double(dx, dy);
+                       sum += l;
+                       lengths[i] = sum;
+               }
+               
+
+               
+       }
+       
+       
+       private double lineLength(Point2D.Double P1, Point2D.Double P2) {
+               return P2.distance(P1);
+       }
+       
+       public double getA() {
+               return a;
+       }
+       
+       public double getB() {
+               return b;
+       }
+
+
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/geom/LinesIntersect.java b/src2/fr/orsay/lri/varna/models/geom/LinesIntersect.java
new file mode 100644 (file)
index 0000000..fa238fe
--- /dev/null
@@ -0,0 +1,88 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.geom;
+
+import java.awt.geom.Line2D;
+import java.awt.geom.Point2D;
+
+/**
+ * Like Line2D.Double.linesIntersect() of the standard library, but without the bug!
+ * See this: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6457965
+ * This result is incorrect with, for example:
+ * System.out.println(Line2D.Double.linesIntersect(179.2690296114372, 1527.2309703885628, 150.9847583639753, 1498.946699141101, 94.4162158690515, 1442.378156646177, 66.1319446215896, 1414.0938853987152));
+ * (real example observed on an RNA with no intersection at all)
+ * This lines obviously don't intersect (both X and Y ranges are clearly disjoint!)
+ * but linesIntersect() returns true.
+ * Here we provide a bug-free function.
+ */
+public class LinesIntersect {
+       /**
+        * Returns whether segment from (x1,y1) to (x2,y2)
+        * intersect with segment from (x3,y3) to (x4,y4).
+        */
+       public static boolean linesIntersect(
+                       double x1,
+            double y1,
+            double x2,
+            double y2,
+            double x3,
+            double y3,
+            double x4,
+            double y4) {
+               
+             double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
+             if (denom == 0.0) { // Lines are parallel.
+                return false;
+             }
+             double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
+             double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom;
+             return (ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0);
+       }
+       
+       /**
+        * Returns whether segment from p1 to p2 intersects segment from p3 to p4.
+        */
+       public static boolean linesIntersect(
+                       Point2D.Double p1,
+                       Point2D.Double p2,
+                       Point2D.Double p3,
+                       Point2D.Double p4) {
+               return linesIntersect(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);
+       }
+       
+       /**
+        * Returns whether the two segment intersect.
+        */
+       public static boolean linesIntersect(Line2D.Double line1, Line2D.Double line2) {
+               return linesIntersect(
+                               line1.x1, line1.y1, line1.x2, line1.y2,
+                               line2.x1, line2.y1, line2.x2, line2.y2);
+       }
+       
+       
+       private static void test(
+                       double x1,
+            double y1,
+            double x2,
+            double y2,
+            double x3,
+            double y3,
+            double x4,
+            double y4,
+            boolean expectedResult) {
+               boolean a = linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4);
+               boolean b = Line2D.Double.linesIntersect(x1, y1, x2, y2, x3, y3, x4, y4);
+               System.out.println("ours says " + a + " which is " + (a == expectedResult ? "correct" : "INCORRECT") +
+                               " / Line2D.Double says " + b + " which is " + (b == expectedResult ? "correct" : "INCORRECT"));
+       }
+       
+       public static void main(String[] args) {
+               test(179.2690296114372, 1527.2309703885628, 150.9847583639753, 1498.946699141101, 94.4162158690515, 1442.378156646177, 66.1319446215896, 1414.0938853987152, false);
+               test(0, 0, 0, 0, 1, 1, 1, 1, false);
+               test(0, 0, 0.5, 0.5, 1, 1, 2, 2, false);
+               test(0, 0, 2, 2, 0, 2, 2, 0, true);
+               test(0, 0, 2, 2, 4, 0, 3, 2, false);
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/geom/MiscGeom.java b/src2/fr/orsay/lri/varna/models/geom/MiscGeom.java
new file mode 100644 (file)
index 0000000..ce3bc7d
--- /dev/null
@@ -0,0 +1,34 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.geom;
+
+import java.awt.geom.Point2D;
+
+
+/**
+ * @author Raphael Champeimont
+ * Misc geometry functions.
+ */
+public class MiscGeom {
+
+       /**
+        * Compute the angle made by a vector.
+        */
+       public static double angleFromVector(Point2D.Double v) {
+               return MiscGeom.angleFromVector(v.x, v.y);
+       }
+
+       public static double angleFromVector(double x, double y) {
+               double l = Math.hypot(x, y);
+               if (y > 0) {
+                       return Math.acos(x / l);
+               } else if (y < 0) {
+                       return - Math.acos(x / l);
+               } else {
+                       return x > 0 ? 0 : Math.PI;
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/naView/Base.java b/src2/fr/orsay/lri/varna/models/naView/Base.java
new file mode 100644 (file)
index 0000000..bb8e0f8
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.naView;
+
+public class Base {
+       private int mate;
+       private double x, y;
+       private boolean extracted;
+       private Region region = new Region();
+
+       public int getMate() {
+               return mate;
+       }
+
+       public void setMate(int mate) {
+               this.mate = mate;
+       }
+
+       public double getX() {
+               return x;
+       }
+
+       public void setX(double x) {
+               //System.out.println("  Base.setX()");
+               this.x = x;
+       }
+
+       public double getY() {
+               return y;
+       }
+
+       public void setY(double y) {
+               this.y = y;
+       }
+
+       public boolean isExtracted() {
+               return extracted;
+       }
+
+       public void setExtracted(boolean extracted) {
+               this.extracted = extracted;
+       }
+
+       public Region getRegion() {
+               return region;
+       }
+
+       public void setRegion(Region region) {
+               this.region = region;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/naView/Connection.java b/src2/fr/orsay/lri/varna/models/naView/Connection.java
new file mode 100644 (file)
index 0000000..bca820b
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.naView;
+
+public class Connection {
+       private Loop loop = new Loop();
+       private Region region = new Region();
+       // Start and end form the 1st base pair of the region.
+       private int start, end;
+       private double xrad, yrad, angle;
+       // True if segment between this connection and the
+       // next must be extruded out of the circle
+       private boolean extruded;
+       // True if the extruded segment must be drawn long.
+       private boolean broken;
+       
+       private boolean _isNull=false;
+
+       public boolean isNull() {
+               return _isNull;
+       }
+
+       public void setNull(boolean isNull) {
+               _isNull = isNull;
+       }
+
+       
+       public Loop getLoop() {
+               return loop;
+       }
+
+       public void setLoop(Loop loop) {
+               this.loop = loop;
+       }
+
+       public Region getRegion() {
+               return region;
+       }
+
+       public void setRegion(Region region) {
+               this.region = region;
+       }
+
+       public int getStart() {
+               return start;
+       }
+
+       public void setStart(int start) {
+               this.start = start;
+       }
+
+       public int getEnd() {
+               return end;
+       }
+
+       public void setEnd(int end) {
+               this.end = end;
+       }
+
+       public double getXrad() {
+               return xrad;
+       }
+
+       public void setXrad(double xrad) {
+               this.xrad = xrad;
+       }
+
+       public double getYrad() {
+               return yrad;
+       }
+
+       public void setYrad(double yrad) {
+               this.yrad = yrad;
+       }
+
+       public double getAngle() {
+               return angle;
+       }
+
+       public void setAngle(double angle) {
+               this.angle = angle;
+       }
+
+       public boolean isExtruded() {
+               return extruded;
+       }
+
+       public void setExtruded(boolean extruded) {
+               this.extruded = extruded;
+       }
+
+       public boolean isBroken() {
+               return broken;
+       }
+
+       public void setBroken(boolean broken) {
+               this.broken = broken;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/naView/Loop.java b/src2/fr/orsay/lri/varna/models/naView/Loop.java
new file mode 100644 (file)
index 0000000..ae08bbd
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.naView;
+
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+public class Loop {
+       private int nconnection;
+       private ArrayList<Connection> connections = new ArrayList<Connection>();
+       private Hashtable<Integer,Connection> _connections = new Hashtable<Integer,Connection>();
+       private int number;
+       private int depth;
+       private boolean mark;
+       private double x, y, radius;
+
+       public int getNconnection() {
+               return nconnection;
+       }
+
+       public void setNconnection(int nconnection) {
+               this.nconnection = nconnection;
+       }
+
+       public void setConnection(int i, Connection c)
+       {
+               Integer n = new Integer(i);
+               if (c != null)
+               _connections.put(n, c);
+               else
+               {
+                       if (!_connections.containsKey(n))
+                       {
+                               _connections.put(n, new Connection());
+                       }
+                       _connections.get(i).setNull(true);
+               }
+       }
+
+       public Connection getConnection(int i)
+       {
+               Integer n = new Integer(i);
+               if (!_connections.containsKey(n))
+               { _connections.put(n, new Connection()); }
+               Connection c = _connections.get(n);
+               if (c.isNull())
+                       return null;
+               else
+                       return c;
+       }
+       
+       public void addConnection(int i, Connection c)
+       {
+               _connections.put(_connections.size(),c);
+       }
+       
+
+       public int getNumber() {
+               return number;
+       }
+
+       public void setNumber(int number) {
+               this.number = number;
+       }
+
+       public int getDepth() {
+               return depth;
+       }
+
+       public void setDepth(int depth) {
+               this.depth = depth;
+       }
+
+       public boolean isMark() {
+               return mark;
+       }
+
+       public void setMark(boolean mark) {
+               this.mark = mark;
+       }
+
+       public double getX() {
+               return x;
+       }
+
+       public void setX(double x) {
+               this.x = x;
+       }
+
+       public double getY() {
+               return y;
+       }
+
+       public void setY(double y) {
+               this.y = y;
+       }
+
+       public double getRadius() {
+               return radius;
+       }
+
+       public void setRadius(double radius) {
+               this.radius = radius;
+       }
+       
+       public String toString()
+       {
+               String result = "Loop:";
+               result += " nconnection "+nconnection;
+               result += " depth "+depth;
+               return result;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/naView/NAView.java b/src2/fr/orsay/lri/varna/models/naView/NAView.java
new file mode 100644 (file)
index 0000000..5b7d023
--- /dev/null
@@ -0,0 +1,1302 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.naView;
+
+
+import java.util.ArrayList;
+
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAObservable;
+
+public class NAView {
+       private final double ANUM = 9999.0;
+       private final int MAXITER = 500;
+
+       private ArrayList<Base> bases;
+       private int nbase, nregion, loop_count;
+
+       private Loop root = new Loop();
+       private ArrayList<Loop> loops;
+
+       private ArrayList<Region> regions;
+
+       private Radloop rlphead = new Radloop();
+
+       private double lencut=0.8;
+       private final double RADIUS_REDUCTION_FACTOR = 1.4;
+
+       // show algorithm step by step
+       private boolean debug = false;
+
+       private double angleinc;
+
+       private double _h;
+
+       private ArrayList<InterfaceVARNAListener> _listeVARNAListener = new ArrayList<InterfaceVARNAListener>();
+
+       private boolean noIterationFailureYet = true;
+
+       double HELIX_FACTOR = 0.6;
+       double BACKBONE_DISTANCE = 27;
+
+       public int naview_xy_coordinates(ArrayList<Short> pair_table2,
+                       ArrayList<Double> x, ArrayList<Double> y)
+                       throws ExceptionNAViewAlgorithm {
+               if (debug)
+                       System.out.println("naview_xy_coordinates");
+               if (pair_table2.size() == 0)
+                       return 0;
+               int i;
+               ArrayList<Integer> pair_table = new ArrayList<Integer>(pair_table2
+                               .size() + 1);
+               pair_table.add(pair_table2.size());
+
+               for (int j = 0; j < pair_table2.size(); j++) {
+                       pair_table.add(pair_table2.get(j) + 1);
+               }
+
+               if (debug) {
+                       infoStructure(pair_table);
+               }
+               // length
+               nbase = pair_table.get(0);
+               bases = new ArrayList<Base>(nbase + 1);
+
+               for (int index = 0; index < bases.size(); index++) {
+                       bases.add(new Base());
+               }
+
+               regions = new ArrayList<Region>();
+               for (int index = 0; index < nbase + 1; index++) {
+                       regions.add(new Region());
+               }
+
+               read_in_bases(pair_table);
+
+               if (debug)
+                       infoBasesMate();
+
+               rlphead = null;
+
+               find_regions();
+
+               if (debug)
+                       infoRegions();
+
+               loop_count = 0;
+               loops = new ArrayList<Loop>(nbase + 1);
+               for (int index = 0; index < nbase + 1; index++) {
+                       loops.add(new Loop());
+               }
+
+               construct_loop(0);
+
+               if (debug)
+                       infoBasesExtracted();
+
+               find_central_loop();
+
+               if (debug)
+                       infoRoot();
+
+               if (debug)
+                       dump_loops();
+
+               traverse_loop(root, null);
+
+               for (i = 0; i < nbase; i++) {
+                       x.add(100 + BACKBONE_DISTANCE * bases.get(i + 1).getX());
+                       y.add(100 + BACKBONE_DISTANCE * bases.get(i + 1).getY());
+               }
+
+               return nbase;
+       }
+
+       private void infoStructure(ArrayList<Integer> pair_table) {
+               System.out.println("structure:");
+               for (int j = 0; j < pair_table.size(); j++) {
+                       System.out.print("#" + j + ":" + pair_table.get(j) + "\t");
+                       if (j % 10 == 0)
+                               System.out.println();
+               }
+               System.out.println();
+       }
+
+       private void infoBasesMate() {
+               System.out.println("Bases mate:");
+               for (int index = 0; index < bases.size(); index++) {
+                       System.out.print("#" + index + ":" + bases.get(index).getMate()
+                                       + "\t");
+                       if (index % 10 == 0)
+                               System.out.println();
+               }
+               System.out.println();
+       }
+
+       private void infoRegions() {
+               System.out.println("regions:");
+               for (int index = 0; index < regions.size(); index++) {
+                       System.out.print("(" + regions.get(index).getStart1() + ","
+                                       + regions.get(index).getStart2() + ";"
+                                       + regions.get(index).getEnd1() + ","
+                                       + regions.get(index).getEnd2() + ")\t\t");
+                       if (index % 5 == 0)
+                               System.out.println();
+               }
+               System.out.println();
+       }
+
+       private void infoBasesExtracted() {
+               System.out.println("Bases extracted:");
+               for (int index = 0; index < bases.size(); index++) {
+                       System.out.print("i=" + index + ":"
+                                       + bases.get(index).isExtracted() + "\t");
+                       if (index % 5 == 0)
+                               System.out.println();
+               }
+               System.out.println();
+       }
+
+       private void infoRoot() {
+               System.out.println("root" + root.getNconnection() + ";"
+                               + root.getNumber());
+               System.out.println("\troot : ");
+               System.out.println("\tdepth=" + root.getDepth());
+               System.out.println("\tmark=" + root.isMark());
+               System.out.println("\tnumber=" + root.getNumber());
+               System.out.println("\tradius=" + root.getRadius());
+               System.out.println("\tx=" + root.getX());
+               System.out.println("\ty=" + root.getY());
+               System.out.println("\tnconnection=" + root.getNconnection());
+       }
+
+       private void read_in_bases(ArrayList<Integer> pair_table) {
+               if (debug)
+                       System.out.println("read_in_bases");
+
+               int i, npairs;
+
+               // Set up an origin.
+               bases.add(new Base());
+               bases.get(0).setMate(0);
+               bases.get(0).setExtracted(false);
+               bases.get(0).setX(ANUM);
+               bases.get(0).setY(ANUM);
+
+               for (npairs = 0, i = 1; i <= nbase; i++) {
+                       bases.add(new Base());
+                       bases.get(i).setExtracted(false);
+                       bases.get(i).setX(ANUM);
+                       bases.get(i).setY(ANUM);
+                       bases.get(i).setMate(pair_table.get(i));
+                       if ((int) pair_table.get(i) > i)
+                               npairs++;
+               }
+               // must have at least 1 pair to avoid segfault
+               if (npairs == 0) {
+                       bases.get(1).setMate(nbase);
+                       bases.get(nbase).setMate(1);
+               }
+       }
+
+       /**
+        * Identifies the regions in the structure.
+        */
+       private void find_regions()
+
+       {
+               if (debug)
+                       System.out.println("find_regions");
+               int i, mate, nb1;
+               nb1 = nbase + 1;
+               ArrayList<Boolean> mark = new ArrayList<Boolean>(nb1);
+               for (i = 0; i < nb1; i++)
+                       mark.add(false);
+               nregion = 0;
+               for (i = 0; i <= nbase; i++) {
+                       if ((mate = bases.get(i).getMate()) != 0 && !mark.get(i)) {
+                               regions.get(nregion).setStart1(i);
+                               regions.get(nregion).setEnd2(mate);
+                               mark.set(i, true);
+                               mark.set(mate, true);
+                               bases.get(i).setRegion(regions.get(nregion));
+                               bases.get(mate).setRegion(regions.get(nregion));
+                               for (i++, mate--; i < mate && bases.get(i).getMate() == mate; i++, mate--) {
+                                       mark.set(mate, true);
+                                       mark.set(i, true);
+                                       bases.get(i).setRegion(regions.get(nregion));
+                                       bases.get(mate).setRegion(regions.get(nregion));
+                               }
+                               regions.get(nregion).setEnd1(--i);
+                               regions.get(nregion).setStart2(mate + 1);
+                               if (debug) {
+                                       if (nregion == 0)
+                                               System.out.printf("\nRegions are:\n");
+                                       System.out.printf(
+                                                       "Region %d is %d-%d and %d-%d with gap of %d.\n",
+                                                       nregion + 1, regions.get(nregion).getStart1(),
+                                                       regions.get(nregion).getEnd1(), regions
+                                                                       .get(nregion).getStart2(), regions.get(
+                                                                       nregion).getEnd2(), regions.get(nregion)
+                                                                       .getStart2()
+                                                                       - regions.get(nregion).getEnd1() + 1);
+                               }
+                               nregion++;
+                       }
+               }
+       }
+
+       /**
+        * Starting at residue ibase, recursively constructs the loop containing
+        * said base and all deeper bases.
+        * 
+        * @throws ExceptionNAViewAlgorithm
+        */
+       private Loop construct_loop(int ibase) throws ExceptionNAViewAlgorithm {
+               if (debug)
+                       System.out.println("construct_loop");
+               int i, mate;
+               Loop retloop = new Loop(), lp = new Loop();
+               Connection cp = new Connection();
+               Region rp = new Region();
+               Radloop rlp = new Radloop();
+               retloop = loops.get(loop_count++);
+               retloop.setNconnection(0);
+               //System.out.println(""+ibase+" "+nbase);
+               //ArrayList<Connection> a = new ArrayList<Connection>(nbase + 1); 
+               //retloop.setConnections(a);
+//             for (int index = 0; index < nbase + 1; index++)
+//                     retloop.getConnections().add(new Connection());
+               //for (int index = 0; index < nbase + 1; index++)
+               //      retloop.addConnection(index,new Connection());
+               retloop.setDepth(0);
+               retloop.setNumber(loop_count);
+               retloop.setRadius(0.0);
+               for (rlp = rlphead; rlp != null; rlp = rlp.getNext())
+                       if (rlp.getLoopnumber() == loop_count)
+                               retloop.setRadius(rlp.getRadius());
+               i = ibase;
+               do {
+                       if ((mate = bases.get(i).getMate()) != 0) {
+                               rp = bases.get(i).getRegion();
+                               if (!bases.get(rp.getStart1()).isExtracted()) {
+                                       if (i == rp.getStart1()) {
+                                               bases.get(rp.getStart1()).setExtracted(true);
+                                               bases.get(rp.getEnd1()).setExtracted(true);
+                                               bases.get(rp.getStart2()).setExtracted(true);
+                                               bases.get(rp.getEnd2()).setExtracted(true);
+                                               lp = construct_loop(rp.getEnd1() < nbase ? rp.getEnd1() + 1
+                                                               : 0);
+                                       } else if (i == rp.getStart2()) {
+                                               bases.get(rp.getStart2()).setExtracted(true);
+                                               bases.get(rp.getEnd2()).setExtracted(true);
+                                               bases.get(rp.getStart1()).setExtracted(true);
+                                               bases.get(rp.getEnd1()).setExtracted(true);
+                                               lp = construct_loop(rp.getEnd2() < nbase ? rp.getEnd2() + 1
+                                                               : 0);
+                                       } else {
+                                               throw new ExceptionNAViewAlgorithm(
+                                                               "naview:Error detected in construct_loop. i = "
+                                                                               + i + " not found in region table.\n");
+                                       }
+                                       retloop.setNconnection(retloop.getNconnection() + 1);
+                                       cp = new Connection();
+                                       retloop.setConnection(retloop.getNconnection() - 1,     cp);
+                                       retloop.setConnection(retloop.getNconnection(), null);
+                                       cp.setLoop(lp);
+                                       cp.setRegion(rp);
+                                       if (i == rp.getStart1()) {
+                                               cp.setStart(rp.getStart1());
+                                               cp.setEnd(rp.getEnd2());
+                                       } else {
+                                               cp.setStart(rp.getStart2());
+                                               cp.setEnd(rp.getEnd1());
+                                       }
+                                       cp.setExtruded(false);
+                                       cp.setBroken(false);
+                                       lp.setNconnection(lp.getNconnection() + 1);
+                                       cp = new Connection();
+                                       lp.setConnection(lp.getNconnection() - 1, cp);
+                                       lp.setConnection(lp.getNconnection(), null);
+                                       cp.setLoop(retloop);
+                                       cp.setRegion(rp);
+                                       if (i == rp.getStart1()) {
+                                               cp.setStart(rp.getStart2());
+                                               cp.setEnd(rp.getEnd1());
+                                       } else {
+                                               cp.setStart(rp.getStart1());
+                                               cp.setEnd(rp.getEnd2());
+                                       }
+                                       cp.setExtruded(false);
+                                       cp.setBroken(false);
+                               }
+                               i = mate;
+                       }
+                       if (++i > nbase)
+                               i = 0;
+               } while (i != ibase);
+               return retloop;
+       }
+
+       /**
+        * Displays all the loops.
+        */
+       private void dump_loops() {
+               System.out.println("dump_loops");
+               int il, ilp, irp;
+               Loop lp;
+               Connection cp;
+
+               System.out.printf("\nRoot loop is #%d\n", loops.indexOf(root) + 1);
+               for (il = 0; il < loop_count; il++) {
+                       lp = loops.get(il);
+                       System.out.printf("Loop %d has %d connections:\n", il + 1, lp
+                                       .getNconnection());
+                       for (int i = 0; (cp = lp.getConnection(i)) != null; i++) {
+                               ilp = (loops.indexOf(cp.getLoop())) + 1;
+                               irp = (regions.indexOf(cp.getRegion())) + 1;
+                               System.out.printf("  Loop %d Region %d (%d-%d)\n", ilp, irp, cp
+                                               .getStart(), cp.getEnd());
+                       }
+               }
+       }
+
+       /**
+        * Find node of greatest branching that is deepest.
+        */
+       private void find_central_loop() {
+               if (debug)
+                       System.out.println("find_central_loop");
+               Loop lp = new Loop();
+               int maxconn, maxdepth, i;
+
+               determine_depths();
+               maxconn = 0;
+               maxdepth = -1;
+               for (i = 0; i < loop_count; i++) {
+                       lp = loops.get(i);
+                       if (lp.getNconnection() > maxconn) {
+                               maxdepth = lp.getDepth();
+                               maxconn = lp.getNconnection();
+                               root = lp;
+                       } else if (lp.getDepth() > maxdepth
+                                       && lp.getNconnection() == maxconn) {
+                               maxdepth = lp.getDepth();
+                               root = lp;
+                       }
+               }
+       }
+
+       /**
+        * Determine the depth of all loops.
+        */
+       private void determine_depths() {
+               if (debug)
+                       System.out.println("determine_depths");
+               Loop lp = new Loop();
+               int i, j;
+
+               for (i = 0; i < loop_count; i++) {
+                       lp = loops.get(i);
+                       for (j = 0; j < loop_count; j++)
+                               loops.get(j).setMark(false);
+                       lp.setDepth(depth(lp));
+               }
+       }
+
+       /**
+        * Determines the depth of loop, lp. Depth is defined as the minimum
+        * distance to a leaf loop where a leaf loop is one that has only one or no
+        * connections.
+        */
+       private int depth(Loop lp) {
+               if (debug)
+                       System.out.println("depth");
+               int count, ret, d;
+
+               if (lp.getNconnection() <= 1)
+                       return 0;
+               if (lp.isMark())
+                       return -1;
+               lp.setMark(true);
+               count = 0;
+               ret = 0;
+               for (int i = 0; lp.getConnection(i) != null; i++) {
+                       d = depth(lp.getConnection(i).getLoop());
+                       if (d >= 0) {
+                               if (++count == 1)
+                                       ret = d;
+                               else if (ret > d)
+                                       ret = d;
+                       }
+               }
+               lp.setMark(false);
+               return ret + 1;
+       }
+
+       /**
+        * This is the workhorse of the display program. The algorithm is recursive
+        * based on processing individual loops. Each base pairing region is
+        * displayed using the direction given by the circle diagram, and the
+        * connections between the regions is drawn by equally spaced points. The
+        * radius of the loop is set to minimize the square error for lengths
+        * between sequential bases in the loops. The "correct" length for base
+        * links is 1. If the least squares fitting of the radius results in loops
+        * being less than 1/2 unit apart, then that segment is extruded.
+        * 
+        * The variable, anchor_connection, gives the connection to the loop
+        * processed in an previous level of recursion.
+        * 
+        * @throws ExceptionNAViewAlgorithm
+        */
+       private void traverse_loop(Loop lp, Connection anchor_connection)
+                       throws ExceptionNAViewAlgorithm {
+               if (debug)
+                       System.out.println("  traverse_loop");
+               double xs, ys, xe, ye, xn, yn, angleinc, r;
+               double radius, xc, yc, xo, yo, astart, aend, a;
+               Connection cp, cpnext, acp, cpprev;
+               int i, j, n, ic;
+               double da, maxang;
+               int count, icstart, icend, icmiddle, icroot;
+               boolean done, done_all_connections, rooted;
+               int sign;
+               double midx, midy, nrx, nry, mx, my, vx, vy, dotmv, nmidx, nmidy;
+               int icstart1, icup, icdown, icnext, direction;
+               double dan, dx, dy, rr;
+               double cpx, cpy, cpnextx, cpnexty, cnx, cny, rcn, rc, lnx, lny, rl, ac, acn, sx, sy, dcp;
+               int imaxloop = 0;
+
+               angleinc = 2 * Math.PI / (nbase + 1);
+               acp = null;
+               icroot = -1;
+               int indice = 0;
+               
+               for (ic = 0; (cp = lp.getConnection(indice)) != null; indice++, ic++) {
+                       // xs = cos(angleinc*cp.setStart(); ys = sin(angleinc*cp.setStart();
+                       // xe =
+                       // cos(angleinc*cp.setEnd()); ye = sin(angleinc*cp.setEnd());
+                       xs = -Math.sin(angleinc * cp.getStart());
+                       ys = Math.cos(angleinc * cp.getStart());
+                       xe = -Math.sin(angleinc * cp.getEnd());
+                       ye = Math.cos(angleinc * cp.getEnd());
+                       xn = ye - ys;
+                       yn = xs - xe;
+                       r = Math.sqrt(xn * xn + yn * yn);
+                       cp.setXrad(xn / r);
+                       cp.setYrad(yn / r);
+                       cp.setAngle(Math.atan2(yn, xn));
+                       if (cp.getAngle() < 0.0)
+                               cp.setAngle(cp.getAngle() + 2 * Math.PI);
+                       if (anchor_connection != null
+                                       && anchor_connection.getRegion() == cp.getRegion()) {
+                               acp = cp;
+                               icroot = ic;
+                       }
+               }
+               // remplacement d'une etiquette de goto
+               set_radius: while (true) {
+                       determine_radius(lp, lencut);
+                       radius = lp.getRadius()/RADIUS_REDUCTION_FACTOR;
+                       if (anchor_connection == null)
+                               xc = yc = 0.0;
+                       else {
+                               xo = (bases.get(acp.getStart()).getX() + bases
+                                               .get(acp.getEnd()).getX()) / 2.0;
+                               yo = (bases.get(acp.getStart()).getY() + bases
+                                               .get(acp.getEnd()).getY()) / 2.0;
+                               xc = xo - radius * acp.getXrad();
+                               yc = yo - radius * acp.getYrad();
+                       }
+
+                       // The construction of the connectors will proceed in blocks of
+                       // connected connectors, where a connected connector pairs means two
+                       // connectors that are forced out of the drawn circle because they
+                       // are too close together in angle.
+
+                       // First, find the start of a block of connected connectors
+
+                       if (icroot == -1)
+                               icstart = 0;
+                       else
+                               icstart = icroot;
+                       cp = lp.getConnection(icstart);
+                       count = 0;
+                       if (debug)
+                       {
+                               System.out.printf("Now processing loop %d\n", lp.getNumber());
+                               System.out.println("  "+lp);
+                       }
+                       done = false;
+                       do {
+                               j = icstart - 1;
+                               if (j < 0)
+                                       j = lp.getNconnection() - 1;
+                               cpprev = lp.getConnection(j);
+                               if (!connected_connection(cpprev, cp)) {
+                                       done = true;
+                               } else {
+                                       icstart = j;
+                                       cp = cpprev;
+                               }
+                               if (++count > lp.getNconnection()) {
+                                       // Here everything is connected. Break on maximum angular
+                                       // separation between connections.
+
+                                       maxang = -1.0;
+                                       for (ic = 0; ic < lp.getNconnection(); ic++) {
+                                               j = ic + 1;
+                                               if (j >= lp.getNconnection())
+                                                       j = 0;
+                                               cp = lp.getConnection(ic);
+                                               cpnext = lp.getConnection(j);
+                                               ac = cpnext.getAngle() - cp.getAngle();
+                                               if (ac < 0.0)
+                                                       ac += 2 * Math.PI;
+                                               if (ac > maxang) {
+                                                       maxang = ac;
+                                                       imaxloop = ic;
+                                               }
+                                       }
+                                       icend = imaxloop;
+                                       icstart = imaxloop + 1;
+                                       if (icstart >= lp.getNconnection())
+                                               icstart = 0;
+                                       cp = lp.getConnection(icend);
+                                       cp.setBroken(true);
+                                       done = true;
+                               }
+                       } while (!done);
+                       done_all_connections = false;
+                       icstart1 = icstart;
+                       if (debug)
+                               System.out.printf("  Icstart1 = %d\n", icstart1);
+                       while (!done_all_connections) {
+                               count = 0;
+                               done = false;
+                               icend = icstart;
+                               rooted = false;
+                               while (!done) {
+                                       cp = lp.getConnection(icend);
+                                       if (icend == icroot)
+                                               rooted = true;
+                                       j = icend + 1;
+                                       if (j >= lp.getNconnection()) {
+                                               j = 0;
+                                       }
+                                       cpnext = lp.getConnection(j);
+                                       if (connected_connection(cp, cpnext)) {
+                                               if (++count >= lp.getNconnection())
+                                                       break;
+                                               icend = j;
+                                       } else {
+                                               done = true;
+                                       }
+                               }
+                               icmiddle = find_ic_middle(icstart, icend, anchor_connection,
+                                               acp, lp);
+                               ic = icup = icdown = icmiddle;
+                               if (debug)
+                                       System.out.printf("  IC start = %d  middle = %d  end = %d\n",
+                                                       icstart, icmiddle, icend);
+                               done = false;
+                               direction = 0;
+                               while (!done) {
+                                       if (direction < 0) {
+                                               ic = icup;
+                                       } else if (direction == 0) {
+                                               ic = icmiddle;
+                                       } else {
+                                               ic = icdown;
+                                       }
+                                       if (ic >= 0) {
+                                               cp = lp.getConnection(ic);
+                                               if (anchor_connection == null || acp != cp) {
+                                                       if (direction == 0) {
+                                                               astart = cp.getAngle()
+                                                                               - Math.asin(1.0 / 2.0 / radius);
+                                                               aend = cp.getAngle()
+                                                                               + Math.asin(1.0 / 2.0 / radius);
+                                                               bases.get(cp.getStart()).setX(
+                                                                               xc + radius * Math.cos(astart));
+                                                               bases.get(cp.getStart()).setY(
+                                                                               yc + radius * Math.sin(astart));
+                                                               bases.get(cp.getEnd()).setX(
+                                                                               xc + radius * Math.cos(aend));
+                                                               bases.get(cp.getEnd()).setY(
+                                                                               yc + radius * Math.sin(aend));
+                                                       } else if (direction < 0) {
+                                                               j = ic + 1;
+                                                               if (j >= lp.getNconnection())
+                                                                       j = 0;
+                                                               cp = lp.getConnection(ic);
+                                                               cpnext = lp.getConnection(j);
+                                                               cpx = cp.getXrad();
+                                                               cpy = cp.getYrad();
+                                                               ac = (cp.getAngle() + cpnext.getAngle()) / 2.0;
+                                                               if (cp.getAngle() > cpnext.getAngle())
+                                                                       ac -= Math.PI;
+                                                               cnx = Math.cos(ac);
+                                                               cny = Math.sin(ac);
+                                                               lnx = cny;
+                                                               lny = -cnx;
+                                                               da = cpnext.getAngle() - cp.getAngle();
+                                                               if (da < 0.0)
+                                                                       da += 2 * Math.PI;
+                                                               if (cp.isExtruded()) {
+                                                                       if (da <= Math.PI / 2)
+                                                                               rl = 2.0;
+                                                                       else
+                                                                               rl = 1.5;
+                                                               } else {
+                                                                       rl = 1.0;
+                                                               }
+                                                               bases.get(cp.getEnd()).setX(
+                                                                               bases.get(cpnext.getStart()).getX()
+                                                                                               + rl * lnx);
+                                                               bases.get(cp.getEnd()).setY(
+                                                                               bases.get(cpnext.getStart()).getY()
+                                                                                               + rl * lny);
+                                                               bases.get(cp.getStart()).setX(
+                                                                               bases.get(cp.getEnd()).getX() + cpy);
+                                                               bases.get(cp.getStart()).setY(
+                                                                               bases.get(cp.getEnd()).getY() - cpx);
+                                                       } else {
+                                                               j = ic - 1;
+                                                               if (j < 0)
+                                                                       j = lp.getNconnection() - 1;
+                                                               cp = lp.getConnection(j);
+                                                               cpnext = lp.getConnection(ic);
+                                                               cpnextx = cpnext.getXrad();
+                                                               cpnexty = cpnext.getYrad();
+                                                               ac = (cp.getAngle() + cpnext.getAngle()) / 2.0;
+                                                               if (cp.getAngle() > cpnext.getAngle())
+                                                                       ac -= Math.PI;
+                                                               cnx = Math.cos(ac);
+                                                               cny = Math.sin(ac);
+                                                               lnx = -cny;
+                                                               lny = cnx;
+                                                               da = cpnext.getAngle() - cp.getAngle();
+                                                               if (da < 0.0)
+                                                                       da += 2 * Math.PI;
+                                                               if (cp.isExtruded()) {
+                                                                       if (da <= Math.PI / 2)
+                                                                               rl = 2.0;
+                                                                       else
+                                                                               rl = 1.5;
+                                                               } else {
+                                                                       rl = 1.0;
+                                                               }
+                                                               bases.get(cpnext.getStart()).setX(
+                                                                               bases.get(cp.getEnd()).getX() + rl
+                                                                                               * lnx);
+                                                               bases.get(cpnext.getStart()).setY(
+                                                                               bases.get(cp.getEnd()).getY() + rl
+                                                                                               * lny);
+                                                               bases.get(cpnext.getEnd()).setX(
+                                                                               bases.get(cpnext.getStart()).getX()
+                                                                                               - cpnexty);
+                                                               bases.get(cpnext.getEnd()).setY(
+                                                                               bases.get(cpnext.getStart()).getY()
+                                                                                               + cpnextx);
+                                                       }
+                                               }
+                                       }
+                                       if (direction < 0) {
+                                               if (icdown == icend) {
+                                                       icdown = -1;
+                                               } else if (icdown >= 0) {
+                                                       if (++icdown >= lp.getNconnection()) {
+                                                               icdown = 0;
+                                                       }
+                                               }
+                                               direction = 1;
+                                       } else {
+                                               if (icup == icstart)
+                                                       icup = -1;
+                                               else if (icup >= 0) {
+                                                       if (--icup < 0) {
+                                                               icup = lp.getNconnection() - 1;
+                                                       }
+                                               }
+                                               direction = -1;
+                                       }
+                                       done = icup == -1 && icdown == -1;
+                               }
+                               icnext = icend + 1;
+                               if (icnext >= lp.getNconnection())
+                                       icnext = 0;
+                               if (icend != icstart
+                                               && (!(icstart == icstart1 && icnext == icstart1))) {
+
+                                       // Move the bases just constructed (or the radius) so that
+                                       // the bisector of the end points is radius distance away
+                                       // from the loop center.
+
+                                       cp = lp.getConnection(icstart);
+                                       cpnext = lp.getConnection(icend);
+                                       dx = bases.get(cpnext.getEnd()).getX()
+                                                       - bases.get(cp.getStart()).getX();
+                                       dy = bases.get(cpnext.getEnd()).getY()
+                                                       - bases.get(cp.getStart()).getY();
+                                       midx = bases.get(cp.getStart()).getX() + dx / 2.0;
+                                       midy = bases.get(cp.getStart()).getY() + dy / 2.0;
+                                       rr = Math.sqrt(dx * dx + dy * dy);
+                                       mx = dx / rr;
+                                       my = dy / rr;
+                                       vx = xc - midx;
+                                       vy = yc - midy;
+                                       rr = Math.sqrt(dx * dx + dy * dy);
+                                       vx /= rr;
+                                       vy /= rr;
+                                       dotmv = vx * mx + vy * my;
+                                       nrx = dotmv * mx - vx;
+                                       nry = dotmv * my - vy;
+                                       rr = Math.sqrt(nrx * nrx + nry * nry);
+                                       nrx /= rr;
+                                       nry /= rr;
+
+                                       // Determine which side of the bisector the center should
+                                       // be.
+
+                                       dx = bases.get(cp.getStart()).getX() - xc;
+                                       dy = bases.get(cp.getStart()).getY() - yc;
+                                       ac = Math.atan2(dy, dx);
+                                       if (ac < 0.0)
+                                               ac += 2 * Math.PI;
+                                       dx = bases.get(cpnext.getEnd()).getX() - xc;
+                                       dy = bases.get(cpnext.getEnd()).getY() - yc;
+                                       acn = Math.atan2(dy, dx);
+                                       if (acn < 0.0)
+                                               acn += 2 * Math.PI;
+                                       if (acn < ac)
+                                               acn += 2 * Math.PI;
+                                       if (acn - ac > Math.PI)
+                                               sign = -1;
+                                       else
+                                               sign = 1;
+                                       nmidx = xc + sign * radius * nrx;
+                                       nmidy = yc + sign * radius * nry;
+                                       if (rooted) {
+                                               xc -= nmidx - midx;
+                                               yc -= nmidy - midy;
+                                       } else {
+                                               for (ic = icstart;;) {
+                                                       cp = lp.getConnection(ic);
+                                                       i = cp.getStart();
+                                                       bases.get(i).setX(
+                                                                       bases.get(i).getX() + nmidx - midx);
+                                                       bases.get(i).setY(
+                                                                       bases.get(i).getY() + nmidy - midy);
+                                                       i = cp.getEnd();
+                                                       bases.get(i).setX(
+                                                                       bases.get(i).getX() + nmidx - midx);
+                                                       bases.get(i).setY(
+                                                                       bases.get(i).getY() + nmidy - midy);
+                                                       if (ic == icend)
+                                                               break;
+                                                       if (++ic >= lp.getNconnection())
+                                                               ic = 0;
+                                               }
+                                       }
+                               }
+                               icstart = icnext;
+                               done_all_connections = icstart == icstart1;
+                       }
+                       for (ic = 0; ic < lp.getNconnection(); ic++) {
+                               cp = lp.getConnection(ic);
+                               j = ic + 1;
+                               if (j >= lp.getNconnection())
+                                       j = 0;
+                               cpnext = lp.getConnection(j);
+                               dx = bases.get(cp.getEnd()).getX() - xc;
+                               dy = bases.get(cp.getEnd()).getY() - yc;
+                               rc = Math.sqrt(dx * dx + dy * dy);
+                               ac = Math.atan2(dy, dx);
+                               if (ac < 0.0)
+                                       ac += 2 * Math.PI;
+                               dx = bases.get(cpnext.getStart()).getX() - xc;
+                               dy = bases.get(cpnext.getStart()).getY() - yc;
+                               rcn = Math.sqrt(dx * dx + dy * dy);
+                               acn = Math.atan2(dy, dx);
+                               if (acn < 0.0)
+                                       acn += 2 * Math.PI;
+                               if (acn < ac)
+                                       acn += 2 * Math.PI;
+                               dan = acn - ac;
+                               dcp = cpnext.getAngle() - cp.getAngle();
+                               if (dcp <= 0.0)
+                                       dcp += 2 * Math.PI;
+                               if (Math.abs(dan - dcp) > Math.PI) {
+                                       if (cp.isExtruded()) {
+                                               warningEmition("Warning from traverse_loop. Loop "
+                                                               + lp.getNumber() + " has crossed regions\n");
+                                       } else if ((cpnext.getStart() - cp.getEnd()) != 1) {
+                                               cp.setExtruded(true);
+                                               continue set_radius; // remplacement du goto
+                                       }
+                               }
+                               if (cp.isExtruded()) {
+                                       construct_extruded_segment(cp, cpnext);
+                               } else {
+                                       n = cpnext.getStart() - cp.getEnd();
+                                       if (n < 0)
+                                               n += nbase + 1;
+                                       angleinc = dan / n;
+                                       for (j = 1; j < n; j++) {
+                                               i = cp.getEnd() + j;
+                                               if (i > nbase)
+                                                       i -= nbase + 1;
+                                               a = ac + j * angleinc;
+                                               rr = rc + (rcn - rc) * (a - ac) / dan;
+                                               bases.get(i).setX(xc + rr * Math.cos(a));
+                                               bases.get(i).setY(yc + rr * Math.sin(a));
+                                       }
+                               }
+                       }
+                       break;
+               }
+               for (ic = 0; ic < lp.getNconnection(); ic++) {
+                       if (icroot != ic) {
+                               cp = lp.getConnection(ic);
+                               generate_region(cp);
+                               traverse_loop(cp.getLoop(), cp);
+                       }
+               }
+               n = 0;
+               sx = 0.0;
+               sy = 0.0;
+               for (ic = 0; ic < lp.getNconnection(); ic++) {
+                       j = ic + 1;
+                       if (j >= lp.getNconnection())
+                               j = 0;
+                       cp = lp.getConnection(ic);
+                       cpnext = lp.getConnection(j);
+                       n += 2;
+                       sx += bases.get(cp.getStart()).getX()
+                                       + bases.get(cp.getEnd()).getX();
+                       sy += bases.get(cp.getStart()).getY()
+                                       + bases.get(cp.getEnd()).getY();
+                       if (!cp.isExtruded()) {
+                               for (j = cp.getEnd() + 1; j != cpnext.getStart(); j++) {
+                                       if (j > nbase)
+                                               j -= nbase + 1;
+                                       n++;
+                                       sx += bases.get(j).getX();
+                                       sy += bases.get(j).getY();
+                               }
+                       }
+               }
+               lp.setX(sx / n);
+               lp.setY(sy / n);
+       }
+
+       /**
+        * For the loop pointed to by lp, determine the radius of the loop that will
+        * ensure that each base around the loop will have a separation of at least
+        * lencut around the circle. If a segment joining two connectors will not
+        * support this separation, then the flag, extruded, will be set in the
+        * first of these two indicators. The radius is set in lp.
+        * 
+        * The radius is selected by a least squares procedure where the sum of the
+        * squares of the deviations of length from the ideal value of 1 is used as
+        * the error function.
+        */
+       private void determine_radius(Loop lp, double lencut) {
+               if (debug)
+                       System.out.println("  Determine_radius");
+               double mindit, ci, dt, sumn, sumd, radius, dit;
+               int i, j, end, start, imindit = 0;
+               Connection cp = new Connection(), cpnext = new Connection();
+               double rt2_2 = 0.7071068;
+
+               do {
+                       mindit = 1.0e10;
+                       for (sumd = 0.0, sumn = 0.0, i = 0; i < lp.getNconnection(); i++) {
+                               cp = lp.getConnection(i);
+                               j = i + 1;
+                               if (j >= lp.getNconnection())
+                                       j = 0;
+                               cpnext = lp.getConnection(j);
+                               end = cp.getEnd();
+                               start = cpnext.getStart();
+                               if (start < end)
+                                       start += nbase + 1;
+                               dt = cpnext.getAngle() - cp.getAngle();
+                               if (dt <= 0.0)
+                                       dt += 2 * Math.PI;
+                               if (!cp.isExtruded())
+                                       ci = start - end;
+                               else {
+                                       if (dt <= Math.PI / 2)
+                                               ci = 2.0;
+                                       else
+                                               ci = 1.5;
+                               }
+                               sumn += dt * (1.0 / ci + 1.0);
+                               sumd += dt * dt / ci;
+                               dit = dt / ci;
+                               if (dit < mindit && !cp.isExtruded() && ci > 1.0) {
+                                       mindit = dit;
+                                       imindit = i;
+                               }
+                       }
+                       radius = sumn / sumd;
+                       if (radius < rt2_2)
+                               radius = rt2_2;
+                       if (mindit * radius < lencut) {
+                               lp.getConnection(imindit).setExtruded(true);
+                       }
+               } while (mindit * radius < lencut);
+               if (lp.getRadius() > 0.0)
+                       radius = lp.getRadius();
+               else
+                       lp.setRadius(radius);
+       }
+
+       /**
+        * Determines if the connections cp and cpnext are connected
+        */
+       private boolean connected_connection(Connection cp, Connection cpnext) {
+               if (debug)
+                       System.out.println("  Connected_connection");
+               if (cp.isExtruded()) {
+                       return true;
+               } else if (cp.getEnd() + 1 == cpnext.getStart()) {
+                       return true;
+               } else {
+                       return false;
+               }
+       }
+
+       /**
+        * Finds the middle of a set of connected connectors. This is normally the
+        * middle connection in the sequence except if one of the connections is the
+        * anchor, in which case that connection will be used.
+        * 
+        * @throws ExceptionNAViewAlgorithm
+        */
+       private int find_ic_middle(int icstart, int icend,
+                       Connection anchor_connection, Connection acp, Loop lp)
+                       throws ExceptionNAViewAlgorithm {
+               if (debug)
+                       System.out.println("  Find_ic_middle");
+               int count, ret, ic, i;
+               boolean done;
+
+               count = 0;
+               ret = -1;
+               ic = icstart;
+               done = false;
+               while (!done) {
+                       if (count++ > lp.getNconnection() * 2) {
+                               throw new ExceptionNAViewAlgorithm(
+                                               "Infinite loop detected in find_ic_middle");
+                       }
+                       if (anchor_connection != null && lp.getConnection(ic) == acp) {
+                               ret = ic;
+                       }
+                       done = ic == icend;
+                       if (++ic >= lp.getNconnection()) {
+                               ic = 0;
+                       }
+               }
+               if (ret == -1) {
+                       for (i = 1, ic = icstart; i < (count + 1) / 2; i++) {
+                               if (++ic >= lp.getNconnection())
+                                       ic = 0;
+                       }
+                       ret = ic;
+               }
+               return ret;
+       }
+
+       /**
+        * Generates the coordinates for the base pairing region of a connection
+        * given the position of the starting base pair.
+        * 
+        * @throws ExceptionNAViewAlgorithm
+        */
+       private void generate_region(Connection cp) throws ExceptionNAViewAlgorithm {
+               if (debug)
+                       System.out.println("  Generate_region");
+               int l, start, end, i, mate;
+               Region rp;
+
+               rp = cp.getRegion();
+               l = 0;
+               if (cp.getStart() == rp.getStart1()) {
+                       start = rp.getStart1();
+                       end = rp.getEnd1();
+               } else {
+                       start = rp.getStart2();
+                       end = rp.getEnd2();
+               }
+               if (bases.get(cp.getStart()).getX() > ANUM - 100.0
+                               || bases.get(cp.getEnd()).getX() > ANUM - 100.0) {
+                       throw new ExceptionNAViewAlgorithm(
+                                       "Bad region passed to generate_region. Coordinates not defined.");
+               }
+               for (i = start + 1; i <= end; i++) {
+                       l++;
+                       bases.get(i).setX(
+                                       bases.get(cp.getStart()).getX() + HELIX_FACTOR * l
+                                                       * cp.getXrad());
+                       bases.get(i).setY(
+                                       bases.get(cp.getStart()).getY() + HELIX_FACTOR * l
+                                                       * cp.getYrad());
+                       mate = bases.get(i).getMate();
+                       bases.get(mate).setX(
+                                       bases.get(cp.getEnd()).getX() + HELIX_FACTOR * l
+                                                       * cp.getXrad());
+                       bases.get(mate).setY(
+                                       bases.get(cp.getEnd()).getY() + HELIX_FACTOR * l
+                                                       * cp.getYrad());
+                       
+               }
+       }
+
+       /**
+        * Draws the segment of residue between the bases numbered start through
+        * end, where start and end are presumed to be part of a base pairing
+        * region. They are drawn as a circle which has a chord given by the ends of
+        * two base pairing regions defined by the connections.
+        * 
+        * @throws ExceptionNAViewAlgorithm
+        */
+       private void construct_circle_segment(int start, int end)
+                       throws ExceptionNAViewAlgorithm {
+               if (debug)
+                       System.out.println("  Construct_circle_segment");
+               double dx, dy, rr, midx, midy, xn, yn, nrx, nry, mx, my, a;
+               int l, j, i;
+
+               dx = bases.get(end).getX() - bases.get(start).getX();
+               dy = bases.get(end).getY() - bases.get(start).getY();
+               rr = Math.sqrt(dx * dx + dy * dy);
+               l = end - start;
+               if (l < 0)
+                       l += nbase + 1;
+               if (rr >= l) {
+                       dx /= rr;
+                       dy /= rr;
+                       for (j = 1; j < l; j++) {
+                               i = start + j;
+                               if (i > nbase)
+                                       i -= nbase + 1;
+                               bases.get(i).setX(
+                                               bases.get(start).getX() + dx * (double) j / (double) l);
+                               bases.get(i).setY(
+                                               bases.get(start).getY() + dy * (double) j / (double) l);
+                       }
+               } else {
+                       find_center_for_arc((l - 1), rr);
+                       dx /= rr;
+                       dy /= rr;
+                       midx = bases.get(start).getX() + dx * rr / 2.0;
+                       midy = bases.get(start).getY() + dy * rr / 2.0;
+                       xn = dy;
+                       yn = -dx;
+                       nrx = midx + _h * xn;
+                       nry = midy + _h * yn;
+                       mx = bases.get(start).getX() - nrx;
+                       my = bases.get(start).getY() - nry;
+                       rr = Math.sqrt(mx * mx + my * my);
+                       a = Math.atan2(my, mx);
+                       for (j = 1; j < l; j++) {
+                               i = start + j;
+                               if (i > nbase)
+                                       i -= nbase + 1;
+                               bases.get(i).setX(nrx + rr * Math.cos(a + j * angleinc));
+                               bases.get(i).setY(nry + rr * Math.sin(a + j * angleinc));
+                       }
+               }
+       }
+
+       /**
+        * Constructs the segment between cp and cpnext as a circle if possible.
+        * However, if the segment is too large, the lines are drawn between the two
+        * connecting regions, and bases are placed there until the connecting
+        * circle will fit.
+        * 
+        * @throws ExceptionNAViewAlgorithm
+        */
+       private void construct_extruded_segment(Connection cp, Connection cpnext)
+                       throws ExceptionNAViewAlgorithm {
+               if (debug)
+                       System.out.println("  Construct_extruded_segment");
+               double astart, aend1, aend2, aave, dx, dy, a1, a2, ac, rr, da, dac;
+               int start, end, n, nstart, nend;
+               boolean collision;
+
+               astart = cp.getAngle();
+               aend2 = aend1 = cpnext.getAngle();
+               if (aend2 < astart)
+                       aend2 += 2 * Math.PI;
+               aave = (astart + aend2) / 2.0;
+               start = cp.getEnd();
+               end = cpnext.getStart();
+               n = end - start;
+               if (n < 0)
+                       n += nbase + 1;
+               da = cpnext.getAngle() - cp.getAngle();
+               if (da < 0.0) {
+                       da += 2 * Math.PI;
+               }
+               if (n == 2)
+                       construct_circle_segment(start, end);
+               else {
+                       dx = bases.get(end).getX() - bases.get(start).getX();
+                       dy = bases.get(end).getY() - bases.get(start).getY();
+                       rr = Math.sqrt(dx * dx + dy * dy);
+                       dx /= rr;
+                       dy /= rr;
+                       if (rr >= 1.5 && da <= Math.PI / 2) {
+                               nstart = start + 1;
+                               if (nstart > nbase)
+                                       nstart -= nbase + 1;
+                               nend = end - 1;
+                               if (nend < 0)
+                                       nend += nbase + 1;
+                               bases.get(nstart).setX(bases.get(start).getX() + 0.5 * dx);
+                               bases.get(nstart).setY(bases.get(start).getY() + 0.5 * dy);
+                               bases.get(nend).setX(bases.get(end).getX() - 0.5 * dx);
+                               bases.get(nend).setY(bases.get(end).getY() - 0.5 * dy);
+                               start = nstart;
+                               end = nend;
+                       }
+                       do {
+                               collision = false;
+                               construct_circle_segment(start, end);
+                               nstart = start + 1;
+                               if (nstart > nbase)
+                                       nstart -= nbase + 1;
+                               dx = bases.get(nstart).getX() - bases.get(start).getX();
+                               dy = bases.get(nstart).getY() - bases.get(start).getY();
+                               a1 = Math.atan2(dy, dx);
+                               if (a1 < 0.0)
+                                       a1 += 2 * Math.PI;
+                               dac = a1 - astart;
+                               if (dac < 0.0)
+                                       dac += 2 * Math.PI;
+                               if (dac > Math.PI)
+                                       collision = true;
+                               nend = end - 1;
+                               if (nend < 0)
+                                       nend += nbase + 1;
+                               dx = bases.get(nend).getX() - bases.get(end).getX();
+                               dy = bases.get(nend).getY() - bases.get(end).getY();
+                               a2 = Math.atan2(dy, dx);
+                               if (a2 < 0.0)
+                                       a2 += 2 * Math.PI;
+                               dac = aend1 - a2;
+                               if (dac < 0.0)
+                                       dac += 2 * Math.PI;
+                               if (dac > Math.PI)
+                                       collision = true;
+                               if (collision) {
+                                       ac = minf2(aave, astart + 0.5);
+                                       bases.get(nstart).setX(
+                                                       bases.get(start).getX() + Math.cos(ac));
+                                       bases.get(nstart).setY(
+                                                       bases.get(start).getY() + Math.sin(ac));
+                                       start = nstart;
+                                       ac = maxf2(aave, aend2 - 0.5);
+                                       bases.get(nend).setX(bases.get(end).getX() + Math.cos(ac));
+                                       bases.get(nend).setY(bases.get(end).getY() + Math.sin(ac));
+                                       end = nend;
+                                       n -= 2;
+                               }
+                       } while (collision && n > 1);
+               }
+       }
+
+       /**
+        * Given n points to be placed equidistantly and equiangularly on a polygon
+        * which has a chord of length, b, find the distance, h, from the midpoint
+        * of the chord for the center of polygon. Positive values mean the center
+        * is within the polygon and the chord, whereas negative values mean the
+        * center is outside the chord. Also, the radial angle for each polygon side
+        * is returned in theta.
+        * 
+        * The procedure uses a bisection algorithm to find the correct value for
+        * the center. Two equations are solved, the angles around the center must
+        * add to 2*Math.PI, and the sides of the polygon excluding the chord must
+        * have a length of 1.
+        * 
+        * @throws ExceptionNAViewAlgorithm
+        */
+       private void find_center_for_arc(double n, double b)
+                       throws ExceptionNAViewAlgorithm {
+               if (debug)
+                       System.out.println("  Find_center_for_arc");
+               double h, hhi, hlow, r, disc, theta, e, phi;
+               int iter;
+
+               hhi = (n + 1.0) / Math.PI;
+               // changed to prevent div by zero if (ih)
+               hlow = -hhi - b / (n + 1.000001 - b);
+               if (b < 1)
+                       // otherwise we might fail below (ih)
+                       hlow = 0;
+               iter = 0;
+               do {
+                       h = (hhi + hlow) / 2.0;
+                       r = Math.sqrt(h * h + b * b / 4.0);
+                       // if (r<0.5) {r = 0.5; h = 0.5*Math.sqrt(1-b*b);}
+                       disc = 1.0 - 0.5 / (r * r);
+                       if (Math.abs(disc) > 1.0) {
+                               throw new ExceptionNAViewAlgorithm(
+                                               "Unexpected large magnitude discriminant = " + disc
+                                                               + " " + r);
+                       }
+                       theta = Math.acos(disc);
+                       // theta = 2*Math.acos(Math.sqrt(1-1/(4*r*r)));
+                       phi = Math.acos(h / r);
+                       e = theta * (n + 1) + 2 * phi - 2 * Math.PI;
+                       if (e > 0.0) {
+                               hlow = h;
+                       } else {
+                               hhi = h;
+                       }
+               } while (Math.abs(e) > 0.0001 && ++iter < MAXITER);
+               if (iter >= MAXITER) {
+                       if (noIterationFailureYet) {
+                               warningEmition("Iteration failed in find_center_for_arc");
+                               noIterationFailureYet = false;
+                       }
+                       h = 0.0;
+                       theta = 0.0;
+               }
+               _h = h;
+               angleinc = theta;
+       }
+
+       private double minf2(double x1, double x2) {
+               return ((x1) < (x2)) ? (x1) : (x2);
+       }
+
+       private double maxf2(double x1, double x2) {
+               return ((x1) > (x2)) ? (x1) : (x2);
+       }
+
+       public void warningEmition(String warningMessage) throws ExceptionNAViewAlgorithm {
+               throw (new ExceptionNAViewAlgorithm(warningMessage));
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/naView/Radloop.java b/src2/fr/orsay/lri/varna/models/naView/Radloop.java
new file mode 100644 (file)
index 0000000..1fc775b
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.naView;
+
+public class Radloop {
+       private double radius;
+       private int loopnumber;
+       private Radloop next, prev;
+
+       public double getRadius() {
+               return radius;
+       }
+
+       public void setRadius(double radius) {
+               this.radius = radius;
+       }
+
+       public int getLoopnumber() {
+               return loopnumber;
+       }
+
+       public void setLoopnumber(int loopnumber) {
+               this.loopnumber = loopnumber;
+       }
+
+       public Radloop getNext() {
+               return next;
+       }
+
+       public void setNext(Radloop next) {
+               this.next = next;
+       }
+
+       public Radloop getPrev() {
+               return prev;
+       }
+
+       public void setPrev(Radloop prev) {
+               this.prev = prev;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/naView/Region.java b/src2/fr/orsay/lri/varna/models/naView/Region.java
new file mode 100644 (file)
index 0000000..7633935
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.naView;
+
+public class Region {
+       private int _start1, _end1, _start2, _end2;
+
+       public int getStart1() {
+               return _start1;
+       }
+
+       public void setStart1(int start1) {
+               this._start1 = start1;
+       }
+
+       public int getEnd1() {
+               return _end1;
+       }
+
+       public void setEnd1(int end1) {
+               this._end1 = end1;
+       }
+
+       public int getStart2() {
+               return _start2;
+       }
+
+       public void setStart2(int start2) {
+               this._start2 = start2;
+       }
+
+       public int getEnd2() {
+               return _end2;
+       }
+
+       public void setEnd2(int end2) {
+               this._end2 = end2;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/DrawRNATemplate.java b/src2/fr/orsay/lri/varna/models/rna/DrawRNATemplate.java
new file mode 100644 (file)
index 0000000..37b41b8
--- /dev/null
@@ -0,0 +1,1421 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Line2D;
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import fr.orsay.lri.varna.exceptions.ExceptionInvalidRNATemplate;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.geom.ComputeArcCenter;
+import fr.orsay.lri.varna.models.geom.ComputeEllipseAxis;
+import fr.orsay.lri.varna.models.geom.CubicBezierCurve;
+import fr.orsay.lri.varna.models.geom.HalfEllipse;
+import fr.orsay.lri.varna.models.geom.LinesIntersect;
+import fr.orsay.lri.varna.models.geom.MiscGeom;
+import fr.orsay.lri.varna.models.templates.DrawRNATemplateCurveMethod;
+import fr.orsay.lri.varna.models.templates.DrawRNATemplateMethod;
+import fr.orsay.lri.varna.models.templates.RNANodeValueTemplate;
+import fr.orsay.lri.varna.models.templates.RNANodeValueTemplateBasePair;
+import fr.orsay.lri.varna.models.templates.RNATemplate;
+import fr.orsay.lri.varna.models.templates.RNATemplateAlign;
+import fr.orsay.lri.varna.models.templates.RNATemplateDrawingAlgorithmException;
+import fr.orsay.lri.varna.models.templates.RNATemplateMapping;
+import fr.orsay.lri.varna.models.templates.RNATemplate.EdgeEndPointPosition;
+import fr.orsay.lri.varna.models.templates.RNATemplate.In1Is;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateHelix;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateUnpairedSequence;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement.EdgeEndPoint;
+import fr.orsay.lri.varna.models.treealign.Tree;
+
+public class DrawRNATemplate {
+       private RNA rna;
+       private RNATemplateMapping mapping;
+       private ArrayList<ModeleBase> _listeBases;
+       
+       
+       public DrawRNATemplate(RNA rna) {
+               this.rna = rna;
+               this._listeBases = rna.getListeBases();
+       }
+       
+       public RNATemplateMapping getMapping() {
+               return mapping;
+       }
+       
+       
+       
+       /**
+        * Draw this RNA like the given template.
+        * The helixLengthAdjustmentMethod argument tells what to do in case
+        * some helices are of a different length in the template and the
+        * actual helix. See class DrawRNATemplateMethod above for possible values.
+        * @param straightBulges 
+        */
+       public void drawRNATemplate(
+                       RNATemplate template,
+                       VARNAConfig conf,
+                       DrawRNATemplateMethod helixLengthAdjustmentMethod,
+                       DrawRNATemplateCurveMethod curveMethod, boolean straightBulges)
+       throws RNATemplateDrawingAlgorithmException {
+               
+               // debug
+//             try {
+//                     RNA perfectMatchingRNA = template.toRNA();
+//                     System.out.println("An RNA that would perfectly match this template would be:");
+//                     System.out.println(perfectMatchingRNA.getStructDBN());
+//             } catch (ExceptionInvalidRNATemplate e) {
+//                     e.printStackTrace();
+//             }
+               
+               mapping = RNATemplateAlign.mapRNAWithTemplate(rna, template);
+               //System.out.println(mapping.showCompact(this));
+               
+               // debug
+//                     RNATemplateAlign.printMapping(mapping, template, getSeq());
+//                     try {
+//                             TreeGraphviz.treeToGraphvizPostscript(alignment, "alignment_graphviz.ps");
+//                     } catch (IOException e) {
+//                             e.printStackTrace();
+//                     }
+               
+               
+
+               Iterator<RNATemplateElement> iter;
+               double globalIncreaseFactor = 1;
+               Map<RNATemplateHelix, Point2D.Double> translateVectors = null;
+               if (helixLengthAdjustmentMethod == DrawRNATemplateMethod.MAXSCALINGFACTOR) {
+                       // Compute increase factors for helices.
+                       Map<RNATemplateHelix, Double> lengthIncreaseFactor = new HashMap<RNATemplateHelix, Double>();
+                       double maxLengthIncreaseFactor = Double.NEGATIVE_INFINITY;
+                       //RNATemplateHelix maxIncreaseHelix = null;
+                       iter = template.rnaIterator();
+                       while (iter.hasNext()) {
+                               RNATemplateElement element = iter.next();
+                               if (element instanceof RNATemplateHelix
+                                               && mapping.getAncestor(element) != null
+                                               && !lengthIncreaseFactor.containsKey(element)) {
+                                       RNATemplateHelix helix = (RNATemplateHelix) element;
+                                       int[] basesInHelixArray = RNATemplateAlign.intArrayFromList(mapping.getAncestor(helix));
+                                       Arrays.sort(basesInHelixArray);
+                                       double l = computeLengthIncreaseFactor(basesInHelixArray, helix, straightBulges);
+                                       lengthIncreaseFactor.put(helix, l);
+                                       if (l > maxLengthIncreaseFactor) {
+                                               maxLengthIncreaseFactor = l;
+                                               //maxIncreaseHelix = helix;
+                                       }
+                               }
+                       }
+                       
+                       // debug
+                       //System.out.println("Max helix length increase factor = " + maxLengthIncreaseFactor + " reached with helix " + maxIncreaseHelix);;
+                       
+                       globalIncreaseFactor = Math.max(1, maxLengthIncreaseFactor);
+                       
+               } else if (helixLengthAdjustmentMethod == DrawRNATemplateMethod.HELIXTRANSLATE) {
+                       try {
+                               // Now we need to propagate this helices translations
+                               Tree<RNANodeValueTemplate> templateAsTree = template.toTree();
+                               translateVectors = computeHelixTranslations(templateAsTree, mapping, straightBulges);
+                       
+                       } catch (ExceptionInvalidRNATemplate e) {
+                               throw (new RNATemplateDrawingAlgorithmException("ExceptionInvalidRNATemplate: " + e.getMessage()));
+                       }
+               }
+               
+               // Allocate the coords and centers arrays
+               // We create Point2D.Double objects in it but the algorithms
+               // we use may choose to create new Point2D.Double objects or to
+               // modify those created here.
+               Point2D.Double[] coords = new Point2D.Double[_listeBases.size()];
+               Point2D.Double[] centers = new Point2D.Double[_listeBases.size()];
+               double[] angles = new double[_listeBases.size()];
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       coords[i] = new Point2D.Double(0, 0);
+                       centers[i] = new Point2D.Double(0, 0);
+               }
+               
+               boolean computeCoords = true;
+               while (computeCoords) {
+                       computeCoords = false;
+                       // Compute coords and centers
+                       Set<RNATemplateHelix> alreadyDrawnHelixes = new HashSet<RNATemplateHelix>();
+                       RNATemplateHelix lastMappedHelix = null;
+                       EdgeEndPoint howWeGotOutOfLastHelix = null;
+                       int howWeGotOutOfLastHelixBaseIndex = 0;
+                       iter = template.rnaIterator();
+                       RNATemplateElement element = null;
+                       while (iter.hasNext()) {
+                               element = iter.next();
+                               if (element instanceof RNATemplateHelix
+                                               && mapping.getAncestor(element) != null) {
+                                       // We have a mapping between an helix in the RNA sequence
+                                       // and an helix in the template.
+                                       
+                                       RNATemplateHelix helix = (RNATemplateHelix) element;
+                                       boolean firstTimeWeMeetThisHelix;
+                                       int[] basesInHelixArray = RNATemplateAlign.intArrayFromList(mapping.getAncestor(helix));
+                                       Arrays.sort(basesInHelixArray);
+                                       
+                                       // Draw this helix if it has not already been done
+                                       if (!alreadyDrawnHelixes.contains(helix)) {
+                                               firstTimeWeMeetThisHelix = true;
+                                               drawHelixLikeTemplateHelix(basesInHelixArray, helix, coords, centers,angles, globalIncreaseFactor, translateVectors, straightBulges);
+                                               alreadyDrawnHelixes.add(helix);
+                                       } else {
+                                               firstTimeWeMeetThisHelix = false;
+                                       }
+                                       
+                                       EdgeEndPoint howWeGetInCurrentHelix;
+                                       if (firstTimeWeMeetThisHelix) {
+                                               if (helix.getIn1Is() == In1Is.IN1_IS_5PRIME) {
+                                                       howWeGetInCurrentHelix = helix.getIn1();
+                                               } else {
+                                                       howWeGetInCurrentHelix = helix.getIn2();
+                                               }
+                                       } else {
+                                               if (helix.getIn1Is() == In1Is.IN1_IS_5PRIME) {
+                                                       howWeGetInCurrentHelix = helix.getIn2();
+                                               } else {
+                                                       howWeGetInCurrentHelix = helix.getIn1();
+                                               }
+                                       }
+                                       
+                                       Point2D.Double P0 = new Point2D.Double();
+                                       Point2D.Double P3 = new Point2D.Double();
+                                       
+                                       if (lastMappedHelix != null) {
+                                               // Now draw the RNA sequence (possibly containing helixes)
+                                               // between the last template drawn helix and this one.
+       
+                                               if (lastMappedHelix == helix) {
+                                                       // Last helix is the same as the current one so
+                                                       // nothing matched (or at best a single
+                                                       // non-paired sequence) so we will just
+                                                       // use the Radiate algorithm
+                                                       
+                                                       Point2D.Double helixVector = new Point2D.Double();
+                                                       computeHelixEndPointDirections(howWeGotOutOfLastHelix, helixVector, new Point2D.Double());
+                                                       
+                                                       double angle = MiscGeom.angleFromVector(helixVector);
+                                                       int b1 = basesInHelixArray[basesInHelixArray.length/2 - 1];
+                                                       P0.setLocation(coords[b1]);
+                                                       int b2 = basesInHelixArray[basesInHelixArray.length/2];
+                                                       P3.setLocation(coords[b2]);
+                                                       Point2D.Double loopCenter = new Point2D.Double((P0.x + P3.x)/2, (P0.y + P3.y)/2);
+                                                       rna.drawLoop(b1,
+                                                                        b2,
+                                                                        loopCenter.x,
+                                                                        loopCenter.y,
+                                                                        angle,
+                                                                        coords,
+                                                                        centers,
+                                                                        angles,
+                                                                        straightBulges);
+                                                       // If the helix is flipped, we need to compute the symmetric
+                                                       // of the whole loop.
+                                                       if (helix.isFlipped()) {
+                                                               symmetric(loopCenter, helixVector, coords, b1, b2);
+                                                               symmetric(loopCenter, helixVector, centers, b1, b2);
+                                                       }
+                                               } else {
+                                                       // No helices matched between the last helix and
+                                                       // the current one, so we draw what is between
+                                                       // using the radiate algorithm but on the Bezier curve.
+                                                       
+                                                       int b1 = howWeGotOutOfLastHelixBaseIndex;
+                                                       int b2 = firstTimeWeMeetThisHelix ? basesInHelixArray[0] : basesInHelixArray[basesInHelixArray.length/2];
+                                                       P0.setLocation(coords[b1]);
+                                                       P3.setLocation(coords[b2]);
+                                                       
+                                                       Point2D.Double P1, P2;
+                                                       
+                                                       if (howWeGotOutOfLastHelix.getOtherElement() instanceof RNATemplateUnpairedSequence
+                                                                       && howWeGetInCurrentHelix.getOtherElement() instanceof RNATemplateUnpairedSequence) {
+                                                               // We will draw the bases on a Bezier curve
+                                                               P1 = new Point2D.Double();
+                                                               computeBezierTangentVectorTarget(howWeGotOutOfLastHelix, P0, P1);
+                                                               
+                                                               P2 = new Point2D.Double();
+                                                               computeBezierTangentVectorTarget(howWeGetInCurrentHelix, P3, P2);
+                                                       } else {
+                                                               // We will draw the bases on a straight line between P0 and P3
+                                                               P1 = null;
+                                                               P2 = null;
+                                                       }
+                                                       
+                                                       drawAlongCurve(b1, b2, P0, P1, P2, P3, coords, centers, angles, curveMethod, lastMappedHelix.isFlipped(), straightBulges);
+                                               }
+                                               
+                                       } else if (basesInHelixArray[0] > 0) {
+                                               // Here we draw what is before the first mapped helix.
+       
+                                               RNATemplateUnpairedSequence templateSequence;
+                                               // Try to find our template sequence as the mapped element of base 0
+                                               RNATemplateElement templateSequenceCandidate = mapping.getPartner(0);
+                                               if (templateSequenceCandidate != null
+                                                               && templateSequenceCandidate instanceof RNATemplateUnpairedSequence) {
+                                                       templateSequence = (RNATemplateUnpairedSequence) templateSequenceCandidate;
+                                               } else {
+                                                       // Try other idea: first template element if it is a sequence
+                                                       templateSequenceCandidate = template.getFirst();
+                                                       if (templateSequenceCandidate != null
+                                                                       && templateSequenceCandidate instanceof RNATemplateUnpairedSequence) {
+                                                               templateSequence = (RNATemplateUnpairedSequence) templateSequenceCandidate;
+                                                       } else {
+                                                               // We don't know where to start
+                                                               templateSequence = null;
+                                                       }
+                                               }
+                                               
+                                               int b1 = 0;
+                                               int b2 = firstTimeWeMeetThisHelix ? basesInHelixArray[0] : basesInHelixArray[basesInHelixArray.length/2];
+                                               P3.setLocation(coords[b2]);
+                                               
+                                               if (templateSequence != null) {
+                                                       coords[0].setLocation(templateSequence.getVertex5());
+                                                       coords[0].x *= globalIncreaseFactor;
+                                                       coords[0].y *= globalIncreaseFactor;
+                                               } else {
+                                                       // Put b1 at an ideal distance from b2, using the "flat exterior loop" method
+                                                       double idealLength = computeStraightLineIdealLength(b1, b2);
+                                                       Point2D.Double j = new Point2D.Double();
+                                                       if (howWeGetInCurrentHelix != null) {
+                                                               computeHelixEndPointDirections(howWeGetInCurrentHelix, new Point2D.Double(), j);
+                                                       } else {
+                                                               j.setLocation(1, 0);
+                                                       }
+                                                       coords[b1].setLocation(coords[b2].x + j.x*idealLength, coords[b2].y + j.y*idealLength);
+                                               }
+                                               P0.setLocation(coords[0]);
+                                               
+                                               Point2D.Double P1, P2;
+                                               
+                                               if (howWeGetInCurrentHelix.getOtherElement() instanceof RNATemplateUnpairedSequence
+                                                               && templateSequence != null) {
+                                                       // We will draw the bases on a Bezier curve
+                                                       P1 = new Point2D.Double();
+                                                       computeBezierTangentVectorTarget(templateSequence.getIn(), P0, P1);
+                                                       
+                                                       P2 = new Point2D.Double();
+                                                       computeBezierTangentVectorTarget(howWeGetInCurrentHelix, P3, P2);
+                                               } else {
+                                                       // We will draw the bases on a straight line between P0 and P3
+                                                       P1 = null;
+                                                       P2 = null;
+                                               }
+                                               
+                                               drawAlongCurve(b1, b2, P0, P1, P2, P3, coords, centers, angles, curveMethod, false, straightBulges);
+                                       }
+                                       
+                                       lastMappedHelix = helix;
+                                       howWeGotOutOfLastHelix = howWeGetInCurrentHelix.getNextEndPoint();
+                                       if (firstTimeWeMeetThisHelix) {
+                                               howWeGotOutOfLastHelixBaseIndex = basesInHelixArray[basesInHelixArray.length/2-1];
+                                       } else {
+                                               howWeGotOutOfLastHelixBaseIndex = basesInHelixArray[basesInHelixArray.length-1];
+                                       }
+                               }
+                       } // end template iteration
+                       
+                       
+                       // Now we need to draw what is after the last mapped helix.
+                       if (howWeGotOutOfLastHelixBaseIndex < coords.length-1
+                                       && element != null
+                                       && coords.length > 1) {
+                               
+                               RNATemplateUnpairedSequence beginTemplateSequence = null;
+                               if (lastMappedHelix == null) {
+                                       // No helix at all matched between the template and RNA!
+                                       // So the sequence we want to draw is the full RNA.
+                                       
+                                       // Try to find our template sequence as the mapped element of base 0
+                                       RNATemplateElement templateSequenceCandidate = mapping.getPartner(0);
+                                       if (templateSequenceCandidate != null
+                                                       && templateSequenceCandidate instanceof RNATemplateUnpairedSequence) {
+                                               beginTemplateSequence = (RNATemplateUnpairedSequence) templateSequenceCandidate;
+                                       } else {
+                                               // Try other idea: first template element if it is a sequence
+                                               templateSequenceCandidate = template.getFirst();
+                                               if (templateSequenceCandidate != null
+                                                               && templateSequenceCandidate instanceof RNATemplateUnpairedSequence) {
+                                                       beginTemplateSequence = (RNATemplateUnpairedSequence) templateSequenceCandidate;
+                                               } else {
+                                                       // We don't know where to start
+                                                       beginTemplateSequence = null;
+                                               }
+                                       }
+                                       
+                                       if (beginTemplateSequence != null) {
+                                               coords[0].setLocation(beginTemplateSequence.getVertex5());
+                                               coords[0].x *= globalIncreaseFactor;
+                                               coords[0].y *= globalIncreaseFactor;
+                                       }
+                                       
+                               }
+                               
+                               RNATemplateUnpairedSequence endTemplateSequence;
+                               // Try to find our template sequence as the mapped element of last base
+                               RNATemplateElement templateSequenceCandidate = mapping.getPartner(coords.length-1);
+                               if (templateSequenceCandidate != null
+                                               && templateSequenceCandidate instanceof RNATemplateUnpairedSequence) {
+                                       endTemplateSequence = (RNATemplateUnpairedSequence) templateSequenceCandidate;
+                               } else {
+                                       // Try other idea: last template element if it is a sequence
+                                       templateSequenceCandidate = element;
+                                       if (templateSequenceCandidate != null
+                                                       && templateSequenceCandidate instanceof RNATemplateUnpairedSequence) {
+                                               endTemplateSequence = (RNATemplateUnpairedSequence) templateSequenceCandidate;
+                                       } else {
+                                               // We don't know where to end
+                                               endTemplateSequence = null;
+                                       }
+                               }
+                               
+                               int b1 = howWeGotOutOfLastHelixBaseIndex;
+                               int b2 = coords.length - 1;
+                               
+                               if (endTemplateSequence != null) {
+                                       coords[b2].setLocation(endTemplateSequence.getVertex3());
+                                       coords[b2].x *= globalIncreaseFactor;
+                                       coords[b2].y *= globalIncreaseFactor;
+                               } else {
+                                       // Put b2 at an ideal distance from b1, using the "flat exterior loop" method
+                                       double idealLength = computeStraightLineIdealLength(b1, b2);
+                                       Point2D.Double j = new Point2D.Double();
+                                       if (howWeGotOutOfLastHelix != null) {
+                                               computeHelixEndPointDirections(howWeGotOutOfLastHelix, new Point2D.Double(), j);
+                                       } else {
+                                               j.setLocation(1, 0);
+                                       }
+                                       coords[b2].setLocation(coords[b1].x + j.x*idealLength, coords[b1].y + j.y*idealLength);
+                               }
+
+                               
+                               Point2D.Double P0 = new Point2D.Double();
+                               Point2D.Double P3 = new Point2D.Double();
+                               
+                               P0.setLocation(coords[b1]);
+                               P3.setLocation(coords[b2]);
+                               
+                               Point2D.Double P1, P2;
+                               
+                               if (howWeGotOutOfLastHelix != null
+                                               && howWeGotOutOfLastHelix.getOtherElement() instanceof RNATemplateUnpairedSequence
+                                               && endTemplateSequence != null) {
+                                       // We will draw the bases on a Bezier curve
+                                       P1 = new Point2D.Double();
+                                       computeBezierTangentVectorTarget(howWeGotOutOfLastHelix, P0, P1);
+                                       
+                                       P2 = new Point2D.Double();
+                                       computeBezierTangentVectorTarget(endTemplateSequence.getOut(), P3, P2);
+                               } else if (lastMappedHelix == null
+                                               && beginTemplateSequence != null
+                                               && endTemplateSequence != null) {
+                                       // We will draw the bases on a Bezier curve
+                                       P1 = new Point2D.Double();
+                                       computeBezierTangentVectorTarget(beginTemplateSequence.getIn(), P0, P1);
+                                       
+                                       P2 = new Point2D.Double();
+                                       computeBezierTangentVectorTarget(endTemplateSequence.getOut(), P3, P2);
+                               } else {
+                                       // We will draw the bases on a straight line between P0 and P3
+                                       P1 = null;
+                                       P2 = null;
+                               }
+                               
+                               drawAlongCurve(b1, b2, P0, P1, P2, P3, coords, centers, angles, curveMethod, lastMappedHelix != null ? lastMappedHelix.isFlipped() : false, straightBulges);
+                       
+                       }
+                       
+                       
+                       if (helixLengthAdjustmentMethod == DrawRNATemplateMethod.NOINTERSECT && coords.length > 3) {
+                               // Are we happy with this value of globalIncreaseFactor?
+                               Line2D.Double[] lines = new Line2D.Double[coords.length-1];
+                               for (int i=0; i<coords.length-1; i++) {
+                                       lines[i] = new Line2D.Double(coords[i], coords[i+1]);
+                               }
+                               int intersectLines = 0;
+                               for (int i=0; i<lines.length; i++) {
+                                       for (int j=i+2; j<lines.length; j++) {
+                                               if (LinesIntersect.linesIntersect(lines[i], lines[j])) {
+                                                       intersectLines++;
+                                               }
+                                       }
+                               }
+                               // If no intersection we keep this globalIncreaseFactor value
+                               if (intersectLines > 0) {
+                                       // Don't increase more than a maximum value
+                                       if (globalIncreaseFactor < 3) {
+                                               globalIncreaseFactor += 0.1;
+                                               //System.out.println("globalIncreaseFactor increased to " + globalIncreaseFactor);
+                                               // Compute the drawing again
+                                               computeCoords = true;
+                                       }
+                               }
+                       }
+                       
+               }
+               
+               // debug
+               if (helixLengthAdjustmentMethod == DrawRNATemplateMethod.MAXSCALINGFACTOR
+                               || helixLengthAdjustmentMethod == DrawRNATemplateMethod.NOINTERSECT) {
+                       //System.out.println("globalIncreaseFactor = " + globalIncreaseFactor);
+               }
+               
+               // Now we actually move the bases, according to arrays coords and centers
+               // and taking in account the space between bases parameter.
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       _listeBases.get(i).setCoords(
+                                       new Point2D.Double(coords[i].x * conf._spaceBetweenBases,
+                                                       coords[i].y * conf._spaceBetweenBases));
+                       _listeBases.get(i).setCenter(
+                                       new Point2D.Double(centers[i].x * conf._spaceBetweenBases,
+                                                       centers[i].y * conf._spaceBetweenBases));
+               }
+       
+       }
+       
+       
+       
+       
+       
+       
+       /**
+        * IN: Argument helixEndPoint is an IN argument (will be read),
+        * and must contain an helix edge endpoint.
+        * 
+        * The other arguments are OUT arguments
+        * (must be existing objects, content will be overwritten).
+        * 
+        * OUT: The i argument will contain a vector colinear to the vector
+        * from the helix startPosition to endPosition or the opposite
+        * depending on there the endpoint is (the endpoint will be on the
+        * destination side of the vector). ||i|| = 1
+        * 
+        * OUT: The j vector will contain an vector that is colinear
+        * to the last/first base pair connection on the side of this endpoint.
+        * The vector will be oriented to the side of the given endpoint.
+        * ||j|| = 1
+        */
+       private void computeHelixEndPointDirections(
+                       EdgeEndPoint helixEndPoint, // IN
+                       Point2D.Double i, // OUT
+                       Point2D.Double j // OUT
+                       ) {
+               RNATemplateHelix helix = (RNATemplateHelix) helixEndPoint.getElement();
+               Point2D.Double startpos = helix.getStartPosition();
+               Point2D.Double endpos = helix.getEndPosition();
+               Point2D.Double helixVector = new Point2D.Double();
+               switch (helixEndPoint.getPosition()) {
+               case IN1:
+               case OUT2:
+                       helixVector.x = startpos.x - endpos.x;
+                       helixVector.y = startpos.y - endpos.y;
+                       break;
+               case IN2:
+               case OUT1:
+                       helixVector.x = endpos.x - startpos.x;
+                       helixVector.y = endpos.y - startpos.y;
+                       break;
+               }
+               double helixVectorLength = Math.hypot(helixVector.x, helixVector.y);
+               // i is the vector which is colinear to helixVector and such that ||i|| = 1
+               i.x = helixVector.x / helixVectorLength;
+               i.y = helixVector.y / helixVectorLength;
+               // Find j such that it is orthogonal to i, ||j|| = 1
+               // and j goes to the side where the sequence will be connected
+               switch (helixEndPoint.getPosition()) {
+               case IN1:
+               case IN2:
+                       // rotation of +pi/2
+                       j.x = - i.y;
+                       j.y =   i.x;
+                       break;
+               case OUT1:
+               case OUT2:
+                       // rotation of -pi/2
+                       j.x =   i.y;
+                       j.y = - i.x;
+                       break;
+               }
+               if (helix.isFlipped()) {
+                       j.x = - j.x;
+                       j.y = - j.y;
+               }
+
+       }
+       
+       /**
+        * A cubic Bezier curve can be defined by 4 points,
+        * see http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
+        * For each of the curve end points, there is the last/first point of the
+        * curve and a point which gives the direction and length of the tangent
+        * vector on that side. This two points are respectively curveEndPoint
+        * and curveVectorOtherPoint.
+        * IN:  Argument helixVector is the vector formed by the helix,
+        *      in the right direction for our sequence.
+        * IN:  Argument curveEndPoint is the position of the endpoint on the helix.
+        * OUT: Argument curveVectorOtherPoint must be allocated
+        *      and the values will be modified.
+        */
+       private void computeBezierTangentVectorTarget(
+                       EdgeEndPoint endPoint,
+                       Point2D.Double curveEndPoint,
+                       Point2D.Double curveVectorOtherPoint)
+                       throws RNATemplateDrawingAlgorithmException {
+               
+               boolean sequenceEndPointIsIn;
+               RNATemplateUnpairedSequence sequence;
+               
+               if (endPoint.getElement() instanceof RNATemplateHelix) {
+                       sequence = (RNATemplateUnpairedSequence) endPoint.getOtherElement();
+                       EdgeEndPointPosition endPointPositionOnHelix = endPoint.getPosition();
+                       switch (endPointPositionOnHelix) {
+                       case IN1:
+                       case IN2:
+                               sequenceEndPointIsIn = false;
+                               break;
+                       default:
+                               sequenceEndPointIsIn = true;
+                       }
+                       
+                       EdgeEndPoint endPointOnHelix =
+                               sequenceEndPointIsIn ?
+                                               sequence.getIn().getOtherEndPoint() :
+                                               sequence.getOut().getOtherEndPoint();
+                       if (endPointOnHelix == null) {
+                               throw (new RNATemplateDrawingAlgorithmException("Sequence is not connected to an helix."));
+                       }
+               } else {
+                       // The endpoint is on an unpaired sequence.
+                       sequence = (RNATemplateUnpairedSequence) endPoint.getElement();
+                       if (endPoint == sequence.getIn()) {
+                               // endpoint is 5'
+                               sequenceEndPointIsIn = true;
+                       } else {
+                               sequenceEndPointIsIn = false;
+                       }
+               }
+
+               double l =
+                       sequenceEndPointIsIn ?
+                               sequence.getInTangentVectorLength() :
+                               sequence.getOutTangentVectorLength();
+               
+               // Compute the absolute angle our line makes to the helix
+               double theta =
+                       sequenceEndPointIsIn ?
+                               sequence.getInTangentVectorAngle() :
+                               sequence.getOutTangentVectorAngle();
+               
+               // Compute v, the tangent vector of the Bezier curve
+               Point2D.Double v = new Point2D.Double();
+               v.x = l * Math.cos(theta);
+               v.y = l * Math.sin(theta);
+               curveVectorOtherPoint.x = curveEndPoint.x + v.x;
+               curveVectorOtherPoint.y = curveEndPoint.y + v.y;
+       }
+       
+
+       /**
+        * Compute (actual helix length / helix length in template).
+        * @param straightBulges 
+        */
+       private double computeLengthIncreaseFactor(
+                       int[] basesInHelixArray,  // IN
+                       RNATemplateHelix helix,    // IN
+                       boolean straightBulges
+                       ) {
+               double templateLength = computeHelixTemplateLength(helix);
+               double realLength = computeHelixRealLength(basesInHelixArray,straightBulges);
+               return realLength / templateLength;
+       }
+       
+       /**
+        * Compute (actual helix vector - helix vector in template).
+        */
+       private Point2D.Double computeLengthIncreaseDelta(
+                       int[] basesInHelixArray,  // IN
+                       RNATemplateHelix helix,   // IN
+                       boolean straightBulges
+                       ) {
+               double templateLength = computeHelixTemplateLength(helix);
+               double realLength = computeHelixRealLength(basesInHelixArray,straightBulges);
+               Point2D.Double i = new Point2D.Double();
+               computeTemplateHelixVectors(helix, null, i, null);
+               return new Point2D.Double(i.x*(realLength-templateLength), i.y*(realLength-templateLength));
+       }
+       
+       /**
+        * Compute helix interesting vectors from template helix.
+        * @param helix The template helix you want to compute the vectors from.
+        * @param o This point coordinates will be set the origin of the helix (or not if null),
+        *          ie. the point in the middle of the base pair with the two most extreme bases.
+        * @param i Will be set to the normalized helix vector. (nothing done if null)
+        * @param j Will be set to the normalized helix base pair vector (5' -> 3'). (nothing done if null)
+        */
+       private void computeTemplateHelixVectors(
+                       RNATemplateHelix helix,  // IN
+                       Point2D.Double o,        // OUT
+                       Point2D.Double i,        // OUT
+                       Point2D.Double j         // OUT
+                       ) {
+               Point2D.Double startpos, endpos;
+               if (helix.getIn1Is() == In1Is.IN1_IS_5PRIME) {
+                       startpos = helix.getStartPosition();
+                       endpos = helix.getEndPosition();
+               } else {
+                       endpos = helix.getStartPosition();
+                       startpos = helix.getEndPosition();
+               }
+               if (o != null) {
+                       o.x = startpos.x;
+                       o.y = startpos.y;
+               }
+               if (i != null || j != null) {
+                       // (i_x,i_y) is the vector between two consecutive bases of the same side of an helix
+                       if (i == null)
+                               i = new Point2D.Double();
+                       i.x = (endpos.x - startpos.x);
+                       i.y = (endpos.y - startpos.y);
+                       double i_original_norm = Math.hypot(i.x, i.y);
+                       // change its norm to 1
+                       i.x = i.x / i_original_norm;
+                       i.y = i.y / i_original_norm;
+                       if (j != null) {
+                               j.x = - i.y;
+                               j.y =   i.x;
+                               if (helix.isFlipped()) {
+                                       j.x = - j.x;
+                                       j.y = - j.y;
+                               }
+                               double j_original_norm = Math.hypot(j.x, j.y);
+                               // change (j_x,j_y) so that its norm is 1
+                               j.x = j.x / j_original_norm;
+                               j.y = j.y / j_original_norm;
+                       }
+               }
+       }
+       
+       
+       /**
+        * Estimate bulge arc length.
+        */
+       private double estimateBulgeArcLength(int firstBase, int lastBase) {
+               if (firstBase + 1 == lastBase)
+                       return RNA.LOOP_DISTANCE; // there is actually no bulge
+               double len = 0.0;
+               int k = firstBase;
+               while (k < lastBase) {
+                       int l = _listeBases.get(k).getElementStructure();
+                       if (k < l && l < lastBase) {
+                               len += RNA.BASE_PAIR_DISTANCE;
+                               k = l;
+                       } else {
+                               len += RNA.LOOP_DISTANCE;
+                               k++;
+                       }
+               }
+               return len;
+       }
+       
+       
+       /**
+        * Estimate bulge width, the given first and last bases must be those in the helix.
+        */
+       private double estimateBulgeWidth(int firstBase, int lastBase) {
+               double len = estimateBulgeArcLength(firstBase, lastBase);
+               return 2 * (len / Math.PI);
+       }
+       
+       
+       /**
+        * Get helix length in template.
+        */
+       private double computeHelixTemplateLength(RNATemplateHelix helix) {
+               return Math.hypot(helix.getStartPosition().x - helix.getEndPosition().x,
+                               helix.getStartPosition().y - helix.getEndPosition().y);
+       }
+       
+       
+       /**
+        * Compute helix actual length (as drawHelixLikeTemplateHelix() would draw it).
+        */
+       private double computeHelixRealLength(int[] basesInHelixArray, boolean straightBulges) {
+               return drawHelixLikeTemplateHelix(basesInHelixArray, null, null, null, null, 0, null,straightBulges);
+       }
+       
+       
+       /**
+        * Result type of countUnpairedLine(), see below.
+        */
+       private static class UnpairedLineCounts {
+               public int nBP, nLD, total;
+       }
+       /**
+        * If we are drawing an unpaired region that may contains helices,
+        * and we are drawing it on a line (curve or straight, doesn't matter),
+        * how many intervals should have a base-pair length (start of an helix)
+        * and how many should have a consecutive unpaired bases length?
+        * Returns an array with three elements:
+        * - answer to first question
+        * - answer to second question
+        * - sum of both, ie. total number of intervals
+        *   (this is NOT lastBase-firstBase because bases deep in helices do not count)
+        */
+       private UnpairedLineCounts countUnpairedLine(int firstBase, int lastBase) {
+               UnpairedLineCounts counts = new UnpairedLineCounts();
+               int nBP = 0;
+               int nLD = 0;
+               {
+                       int b = firstBase;
+                       while (b < lastBase) {
+                               int l = _listeBases.get(b).getElementStructure();
+                               if (b < l && l < lastBase) {
+                                       nBP++;
+                                       b = l;
+                               } else {
+                                       nLD++;
+                                       b++;
+                               }
+                       }
+               }
+               counts.nBP = nBP;
+               counts.nLD = nLD;
+               counts.total = nBP + nLD;
+               return counts;
+       }
+       
+       
+       /**
+        * Draw the given helix (given as a *SORTED* array of indexes)
+        * like defined in the given template helix.
+        * OUT: The bases positions are not changed in fact,
+        *      instead the coords and centers arrays are modified.
+        * IN:  The helix origin position is multiplied by scaleHelixOrigin
+        *      and translateVectors.get(helix) is added.
+        * RETURN VALUE:
+        *      The length of the drawn helix.
+        * @param straightBulges 
+        * 
+        */
+       private double drawHelixLikeTemplateHelix(
+                       int[] basesInHelixArray,  // IN
+                       RNATemplateHelix helix,   // IN  (optional, ie. may be null)
+                       Point2D.Double[] coords,  // OUT (optional, ie. may be null)
+                       Point2D.Double[] centers, // OUT (optional, ie. may be null)
+                       double[] angles,  // OUT 
+                       double scaleHelixOrigin,  // IN
+                       Map<RNATemplateHelix, Point2D.Double> translateVectors // IN (optional, ie. may be null)
+, boolean straightBulges
+                       ) {
+               int n = basesInHelixArray.length / 2;
+               if (n == 0)
+                       return 0;
+                // Default values when not template helix is provided:
+               Point2D.Double o = new Point2D.Double(0, 0);
+               Point2D.Double i = new Point2D.Double(1, 0);
+               Point2D.Double j = new Point2D.Double(0, 1);
+               boolean flipped = false;
+               if (helix != null) {
+                       computeTemplateHelixVectors(helix, o, i, j);
+                       flipped = helix.isFlipped();
+               }
+               Point2D.Double li = new Point2D.Double(i.x*RNA.LOOP_DISTANCE, i.y*RNA.LOOP_DISTANCE);
+               // We want o to be the point where the first base (5' end) is
+               o.x = (o.x - j.x * RNA.BASE_PAIR_DISTANCE / 2) * scaleHelixOrigin;
+               o.y = (o.y - j.y * RNA.BASE_PAIR_DISTANCE / 2) * scaleHelixOrigin;
+               if (translateVectors != null && translateVectors.containsKey(helix)) {
+                       Point2D.Double v = translateVectors.get(helix);
+                       o.x = o.x + v.x;
+                       o.y = o.y + v.y;
+               }
+               
+               // We need this array so that we can store positions even if coords == null
+               Point2D.Double[] helixBasesPositions = new Point2D.Double[basesInHelixArray.length];
+               for (int k=0; k<helixBasesPositions.length; k++) {
+                       helixBasesPositions[k] = new Point2D.Double();  
+               }
+               Point2D.Double accDelta = new Point2D.Double(0, 0);
+               for (int k=0; k<n; k++) {
+                       int kp = 2*n-k-1;
+                       Point2D.Double p1 = helixBasesPositions[k]; // we assign the point *reference*
+                       Point2D.Double p2 = helixBasesPositions[kp];
+                       // Do we have a bulge between previous base pair and this one?
+                       boolean bulge = k >= 1 && (basesInHelixArray[k] != basesInHelixArray[k-1] + 1
+                                                          || basesInHelixArray[kp+1] != basesInHelixArray[kp] + 1);
+                       if (k >= 1) {
+                               if (basesInHelixArray[k] < basesInHelixArray[k-1]
+                                   || basesInHelixArray[kp+1] < basesInHelixArray[kp]) {
+                                       throw new Error("Internal bug: basesInHelixArray must be sorted");
+                               }
+                               if (bulge) {
+                                       // Estimate a good distance (delta) between the previous base pair and this one
+                                       double delta1 = estimateBulgeWidth(basesInHelixArray[k-1], basesInHelixArray[k]);
+                                       double delta2 = estimateBulgeWidth(basesInHelixArray[kp], basesInHelixArray[kp+1]);
+                                       // The biggest bulge defines the width
+                                       double delta = Math.max(delta1, delta2);
+
+                                       if (coords != null) {
+                                               // Now, where do we put the bases that are part of the bulge?
+                                               for (int side=0; side<2; side++) {
+                                                       Point2D.Double pstart = new Point2D.Double();
+                                                       Point2D.Double pend = new Point2D.Double();
+                                                       Point2D.Double bisectVect = new Point2D.Double();
+                                                       Point2D.Double is = new Point2D.Double();
+                                                       int firstBase, lastBase;
+                                                       double alphasign = flipped ? -1 : 1;
+                                                       if (side == 0) {
+                                                               firstBase = basesInHelixArray[k-1];
+                                                               lastBase  = basesInHelixArray[k];
+                                                               pstart.setLocation(o.x + accDelta.x,
+                                                                                  o.y + accDelta.y);
+                                                               pend.setLocation(o.x + accDelta.x + i.x*delta,
+                                                                                o.y + accDelta.y + i.y*delta);
+                                                               bisectVect.setLocation(-j.x, -j.y);
+                                                               is.setLocation(i);
+                                                       } else {
+                                                               firstBase = basesInHelixArray[kp];
+                                                               lastBase  = basesInHelixArray[kp+1];
+                                                               pstart.setLocation(o.x + accDelta.x + i.x*delta + j.x*RNA.BASE_PAIR_DISTANCE,
+                                                                          o.y + accDelta.y + i.y*delta + j.y*RNA.BASE_PAIR_DISTANCE);
+                                                               pend.setLocation(o.x + accDelta.x + j.x*RNA.BASE_PAIR_DISTANCE,
+                                                                                o.y + accDelta.y + j.y*RNA.BASE_PAIR_DISTANCE);
+
+                                                               bisectVect.setLocation(j);
+                                                               is.setLocation(-i.x, -i.y);
+                                                       }
+                                                       double arclen = estimateBulgeArcLength(firstBase, lastBase);
+                                                       double centerOnBisect = ComputeArcCenter.computeArcCenter(delta, arclen);
+                                                       
+                                                       // Should we draw the base on an arc or simply use a line?
+                                                       if (centerOnBisect > -1000) {
+                                                               Point2D.Double center = new Point2D.Double(pstart.x + is.x*delta/2 + bisectVect.x*centerOnBisect,
+                                                                                                          pstart.y + is.y*delta/2 + bisectVect.y*centerOnBisect);
+                                                               int b = firstBase;
+                                                               double len = 0;
+                                                               double r = Math.hypot(pstart.x - center.x, pstart.y - center.y);
+                                                               double alpha0 = MiscGeom.angleFromVector(pstart.x - center.x, pstart.y - center.y);
+                                                               while (b < lastBase) {
+                                                                       int l = _listeBases.get(b).getElementStructure();
+                                                                       if (b < l && l < lastBase) {
+                                                                               len += RNA.BASE_PAIR_DISTANCE;
+                                                                               b = l;
+                                                                       } else {
+                                                                               len += RNA.LOOP_DISTANCE;
+                                                                               b++;
+                                                                       }
+                                                                       if (b < lastBase) {
+                                                                               coords[b].x = center.x + r*Math.cos(alpha0 + alphasign*len/r);
+                                                                               coords[b].y = center.y + r*Math.sin(alpha0 + alphasign*len/r);
+                                                                       }
+                                                               }
+                                                       } else {
+                                                               // Draw on a line
+                                                               
+                                                               // Distance between paired bases cannot be changed
+                                                               // (imposed by helix width) but distance between other
+                                                               // bases can be adjusted.
+                                                               UnpairedLineCounts counts = countUnpairedLine(firstBase, lastBase);
+                                                               double LD = Math.max((delta - counts.nBP*RNA.BASE_PAIR_DISTANCE) / (double) counts.nLD, 0);
+                                                               //System.out.println("nBP=" + nBP + " nLD=" + nLD);
+                                                               double len = 0;
+                                                               {
+                                                                       int b = firstBase;
+                                                                       while (b < lastBase) {
+                                                                               int l = _listeBases.get(b).getElementStructure();
+                                                                               if (b < l && l < lastBase) {
+                                                                                       len += RNA.BASE_PAIR_DISTANCE;
+                                                                                       b = l;
+                                                                               } else {
+                                                                                       len += LD;
+                                                                                       b++;
+                                                                               }
+                                                                               if (b < lastBase) {
+                                                                                       coords[b].x = pstart.x + is.x*len;
+                                                                                       coords[b].y = pstart.y + is.y*len;
+                                                                               }
+                                                                       }
+                                                               }
+                                                               //System.out.println("len=" + len + " delta=" + delta + " d(pstart,pend)=" + Math.hypot(pend.x-pstart.x, pend.y-pstart.y));
+                                                       }
+                                                       
+                                                       // Does the bulge contain an helix?
+                                                       // If so, use drawLoop() to draw it.
+                                                       {
+                                                               int b = firstBase;
+                                                               while (b < lastBase) {
+                                                                       int l = _listeBases.get(b).getElementStructure();
+                                                                       if (b < l && l < lastBase) {
+                                                                               // Helix present in bulge
+                                                                               Point2D.Double b1pos = coords[b];
+                                                                               Point2D.Double b2pos = coords[l];
+                                                                               double beta = MiscGeom.angleFromVector(b2pos.x - b1pos.x, b2pos.y - b1pos.y) - Math.PI / 2 + (flipped ? Math.PI : 0);
+                                                                               Point2D.Double loopCenter = new Point2D.Double((b1pos.x + b2pos.x)/2, (b1pos.y + b2pos.y)/2);
+                                                                               rna.drawLoop(b,
+                                                                                                l,
+                                                                                                loopCenter.x,
+                                                                                                loopCenter.y,
+                                                                                                beta,
+                                                                                                coords,
+                                                                                                centers,
+                                                                                                angles,
+                                                                                                straightBulges);
+                                                                               // If the helix is flipped, we need to compute the symmetric
+                                                                               // of the whole loop.
+                                                                               if (helix.isFlipped()) {
+                                                                                       Point2D.Double v = new Point2D.Double(Math.cos(beta), Math.sin(beta));
+                                                                                       symmetric(loopCenter, v, coords, b, l);
+                                                                                       symmetric(loopCenter, v, centers, b, l);
+                                                                               }
+                                                                               // Continue
+                                                                               b = l;
+                                                                       } else {
+                                                                               b++;
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       }
+                                       
+                                       accDelta.x += i.x*delta;
+                                       accDelta.y += i.y*delta;
+                                       p1.x = o.x + accDelta.x;
+                                       p1.y = o.y + accDelta.y;
+                                       p2.x = p1.x + j.x*RNA.BASE_PAIR_DISTANCE;
+                                       p2.y = p1.y + j.y*RNA.BASE_PAIR_DISTANCE;
+                                       
+                               } else {
+                                       accDelta.x += li.x;
+                                       accDelta.y += li.y;
+                                       p1.x = o.x + accDelta.x;
+                                       p1.y = o.y + accDelta.y;
+                                       p2.x = p1.x + j.x*RNA.BASE_PAIR_DISTANCE;
+                                       p2.y = p1.y + j.y*RNA.BASE_PAIR_DISTANCE;
+                               }
+                       } else {
+                               // First base pair
+                               p1.x = o.x;
+                               p1.y = o.y;
+                               p2.x = p1.x + j.x*RNA.BASE_PAIR_DISTANCE;
+                               p2.y = p1.y + j.y*RNA.BASE_PAIR_DISTANCE;
+                       }
+               }
+               
+               Point2D.Double p1 = helixBasesPositions[0];
+               Point2D.Double p2 = helixBasesPositions[n-1];
+               
+               if (coords != null) {
+                       for (int k=0; k<helixBasesPositions.length; k++) {
+                               coords[basesInHelixArray[k]] = helixBasesPositions[k];
+                       }
+               }
+               
+               return Math.hypot(p2.x-p1.x, p2.y-p1.y);
+       }
+       
+       
+       
+
+       /**
+        * Return ideal length to draw unpaired region from firstBase to lastBase.
+        */
+       private double computeStraightLineIdealLength(int firstBase, int lastBase) {
+               UnpairedLineCounts counts = countUnpairedLine(firstBase, lastBase);
+               return RNA.BASE_PAIR_DISTANCE*counts.nBP + RNA.LOOP_DISTANCE*counts.nLD;
+       }
+       
+       /**
+        * Like drawOnBezierCurve(), but on a straight line.
+        */
+       private boolean drawOnStraightLine(
+                       int firstBase,
+                       int lastBase,
+                       Point2D.Double P0,
+                       Point2D.Double P3,
+                       Point2D.Double[] coords,
+                       Point2D.Double[] centers,
+                       boolean cancelIfNotGood) {
+               
+               Point2D.Double vector = new Point2D.Double(P3.x - P0.x, P3.y - P0.y); 
+               double vectorNorm = Math.hypot(vector.x, vector.y);
+
+               UnpairedLineCounts counts = countUnpairedLine(firstBase, lastBase);
+               double LD = Math.max((vectorNorm - counts.nBP*RNA.BASE_PAIR_DISTANCE) / (double) counts.nLD, 0);
+               
+               if (cancelIfNotGood && LD < RNA.LOOP_DISTANCE*0.75) {
+                       // Bases would be drawn "too" near (0.75 is heuristic)
+                       return false;
+               }
+               
+               double len = 0;
+               {
+                       int b = firstBase;
+                       while (b <= lastBase) {
+                               coords[b].x = P0.x + vector.x*len/vectorNorm;
+                               coords[b].y = P0.y + vector.y*len/vectorNorm;
+                               int l = _listeBases.get(b).getElementStructure();
+                               if (b < l && l < lastBase) {
+                                       len += RNA.BASE_PAIR_DISTANCE;
+                                       b = l;
+                               } else {
+                                       len += LD;
+                                       b++;
+                               }
+                       }
+               }
+               
+               return true;
+       }
+       
+       
+
+
+       /**
+        * A Bezier curve can be defined by four points,
+        * see http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
+        * Here we give this four points and an array of bases indexes
+        * (which must be indexes in this RNA sequence) which will be moved
+        * to be on the Bezier curve.
+        * The bases positions are not changed in fact, instead the coords and
+        * centers arrays are modified.
+        * If cancelIfNotGood, draw only if it would look good,
+        * otherwise just return false.
+        */
+       private boolean drawOnBezierCurve(
+                       int firstBase,
+                       int lastBase,
+                       Point2D.Double P0,
+                       Point2D.Double P1,
+                       Point2D.Double P2,
+                       Point2D.Double P3,
+                       Point2D.Double[] coords,
+                       Point2D.Double[] centers,
+                       boolean cancelIfNotGood) {
+               
+               UnpairedLineCounts counts = countUnpairedLine(firstBase, lastBase);
+               
+               // Draw the bases of the sequence along a Bezier curve
+               int n = counts.total;
+               
+               // We choose to approximate the Bezier curve by 10*n straight lines.
+               CubicBezierCurve bezier = new CubicBezierCurve(P0, P1, P2, P3, 10*n);
+               double curveLength = bezier.getApproxCurveLength();
+               
+               
+               double LD = Math.max((curveLength - counts.nBP*RNA.BASE_PAIR_DISTANCE) / (double) counts.nLD, 0);
+               
+               if (cancelIfNotGood && LD < RNA.LOOP_DISTANCE*0.75) {
+                       // Bases would be drawn "too" near (0.75 is heuristic)
+                       return false;
+               }
+               
+               double[] t = new double[n+1];
+
+               {
+                       double len = 0;
+                       int k = 0;
+                       int b = firstBase;
+                       while (b <= lastBase) {
+                               t[k] = len;
+                               k++;
+                               
+                               int l = _listeBases.get(b).getElementStructure();
+                               if (b < l && l < lastBase) {
+                                       len += RNA.BASE_PAIR_DISTANCE;
+                                       b = l;
+                               } else {
+                                       len += LD;
+                                       b++;
+                               }
+                       }
+               }
+               
+               Point2D.Double[] sequenceBasesCoords = bezier.uniformParam(t);
+               
+               {
+                       int k = 0;
+                       int b = firstBase;
+                       while (b <= lastBase) {
+                               coords[b] = sequenceBasesCoords[k];
+                               int l = _listeBases.get(b).getElementStructure();
+                               if (b < l && l < lastBase) {
+                                       b = l;
+                               } else {
+                                       b++;
+                               }
+                               k++;
+                       }
+               }
+
+               return true;
+       }
+       
+       
+       
+       private void drawOnEllipse(
+                       int firstBase,
+                       int lastBase,
+                       Point2D.Double P0,
+                       Point2D.Double P3,
+                       Point2D.Double[] coords,
+                       Point2D.Double[] centers,
+                       boolean reverse) {              
+
+               UnpairedLineCounts counts = countUnpairedLine(firstBase, lastBase);
+               double halfEllipseLength = RNA.BASE_PAIR_DISTANCE*counts.nBP + RNA.LOOP_DISTANCE*counts.nLD;
+               double fullEllipseLength = halfEllipseLength*2;
+               
+               double axisA = P0.distance(P3)/2;
+               double axisB = ComputeEllipseAxis.computeEllipseAxis(axisA, fullEllipseLength);
+               
+               if (axisB == 0) {
+                       // Ellipse is in fact a line, and it is much faster to draw it as such.
+                       drawOnStraightLine(firstBase, lastBase, P0, P3, coords, centers, false);
+                       return;
+               }
+               
+               //System.out.println("Ellipse a=" + axisA + " b=" + axisB);
+               
+               int n = counts.total;
+               
+               // We choose to approximate the Bezier curve by 10*n straight lines.
+               HalfEllipse curve = new HalfEllipse(axisA, axisB, 10*n);
+               double curveLength = curve.getApproxCurveLength();
+               
+               
+               double LD = Math.max((curveLength - counts.nBP*RNA.BASE_PAIR_DISTANCE) / (double) counts.nLD, 0);
+               
+               double[] t = new double[n+1];
+
+               {
+                       double len = 0;
+                       int k = 0;
+                       int b = firstBase;
+                       while (b <= lastBase) {
+                               t[k] = len;
+                               k++;
+                               
+                               int l = _listeBases.get(b).getElementStructure();
+                               if (b < l && l < lastBase) {
+                                       len += RNA.BASE_PAIR_DISTANCE;
+                                       b = l;
+                               } else {
+                                       len += LD;
+                                       b++;
+                               }
+                       }
+               }
+               
+               // Ellipse with axis = X,Y
+               Point2D.Double[] sequenceBasesCoords = curve.uniformParam(t);
+               
+               // Compute the symmetric half-ellipse
+               if (reverse) {
+                       AffineTransform tranform1 = new AffineTransform();
+                       tranform1.scale(1, -1);
+                       tranform1.transform(sequenceBasesCoords, 0, sequenceBasesCoords, 0, sequenceBasesCoords.length);
+               }
+
+               // Translate + rotate such that ellipse is at the right place
+               AffineTransform tranform = HalfEllipse.matchAxisA(P0, P3);
+               tranform.transform(sequenceBasesCoords, 0, sequenceBasesCoords, 0, sequenceBasesCoords.length);
+               
+               {
+                       int k = 0;
+                       int b = firstBase;
+                       while (b <= lastBase) {
+                               coords[b] = sequenceBasesCoords[k];
+                               //coords[b] = curve.standardParam((double) k/n);
+                               //System.out.println(b + " " + coords[b]);
+                               int l = _listeBases.get(b).getElementStructure();
+                               if (b < l && l < lastBase) {
+                                       b = l;
+                               } else {
+                                       b++;
+                               }
+                               k++;
+                       }
+               }
+
+       }
+       
+       /**
+        * This functions draws the RNA sequence between (including)
+        * firstBase and lastBase along a curve.
+        * The sequence may contain helices.
+        * 
+        * Bezier curve:
+        * A Bezier curve can be defined by four points,
+        * see http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves
+        * 
+        * Straight line:
+        * If P1 and P2 are null, the bases are drawn on a straight line.
+        * 
+        * OUT: The bases positions are not changed in fact,
+        * instead the coords and centers arrays are modified.
+        * 
+        * Argument reverse says if we should reverse the direction of inserted helices.
+        */
+       private void drawAlongCurve(
+                       int firstBase,
+                       int lastBase,
+                       Point2D.Double P0,
+                       Point2D.Double P1,
+                       Point2D.Double P2,
+                       Point2D.Double P3,
+                       Point2D.Double[] coords,
+                       Point2D.Double[] centers,
+                       double[] angles,
+                       DrawRNATemplateCurveMethod curveMethod,
+                       boolean reverse,
+                       boolean straightBulges) {
+               
+               // First we find the bases which are directly on the Bezier curve
+               ArrayList<Integer> alongBezierCurve = new ArrayList<Integer>();
+               for (int depth=0, i=firstBase; i<=lastBase; i++) {
+                       int k = _listeBases.get(i).getElementStructure();
+                       if (k < 0 || k > lastBase || k < firstBase) {
+                               if (depth == 0) {
+                                       alongBezierCurve.add(i);
+                               }
+                       } else {
+                               if (i < k) {
+                                       if (depth == 0) {
+                                               alongBezierCurve.add(i);
+                                               alongBezierCurve.add(k);
+                                       }
+                                       depth++;
+                               } else {
+                                       depth--;
+                               }
+                       }
+               }
+               // number of bases along the Bezier curve
+               int n = alongBezierCurve.size();
+               int[] alongBezierCurveArray = RNATemplateAlign.intArrayFromList(alongBezierCurve);
+               if (n > 0) {
+                       if (curveMethod == DrawRNATemplateCurveMethod.ALWAYS_REPLACE_BY_ELLIPSES) {
+                               drawOnEllipse(firstBase, lastBase, P0, P3, coords, centers, reverse);
+                       } else if (curveMethod == DrawRNATemplateCurveMethod.SMART) {
+                               boolean passed;
+                               if (P1 != null && P2 != null) {
+                                       passed = drawOnBezierCurve(firstBase, lastBase, P0, P1, P2, P3, coords, centers, true);
+                               } else {
+                                       passed = drawOnStraightLine(firstBase, lastBase, P0, P3, coords, centers, true);
+                               }
+                               if (!passed) {
+                                       drawOnEllipse(firstBase, lastBase, P0, P3, coords, centers, reverse);
+                               }
+                       } else {
+                               if (P1 != null && P2 != null) {
+                                       drawOnBezierCurve(firstBase, lastBase, P0, P1, P2, P3, coords, centers, false);
+                               } else {
+                                       drawOnStraightLine(firstBase, lastBase, P0, P3, coords, centers, false);
+                               }
+                       }
+               }
+               // Now use the radiate algorithm to draw the helixes
+               for (int k=0; k<n-1; k++) {
+                       int b1 = alongBezierCurveArray[k];
+                       int b2 = alongBezierCurveArray[k+1];
+                       if (_listeBases.get(b1).getElementStructure() == b2) {
+                               Point2D.Double b1pos = coords[b1];
+                               Point2D.Double b2pos = coords[b2];
+                               double alpha = MiscGeom.angleFromVector(b2pos.x - b1pos.x, b2pos.y - b1pos.y);
+                               rna.drawLoop(b1,
+                                                b2,
+                                                (b1pos.x + b2pos.x)/2,
+                                                (b1pos.y + b2pos.y)/2,
+                                                alpha - Math.PI / 2,
+                                                coords,
+                                                centers,
+                                                angles,
+                                                straightBulges);
+                               if (reverse) {
+                                       Point2D.Double symAxisVect = new Point2D.Double(coords[b2].x - coords[b1].x, coords[b2].y - coords[b1].y); 
+                                       symmetric(coords[b1], symAxisVect, coords, b1, b2);
+                                       symmetric(coords[b1], symAxisVect, centers, b1, b2);
+                               }
+                       }
+               }       
+       }
+       
+       
+       /**
+        * Compute the symmetric of all the points from first to last in the points array
+        * relative to the line that goes through p and has director vector v.
+        * The array is modified in-place.
+        */
+       private static void symmetric(
+                       Point2D.Double p,
+                       Point2D.Double v,
+                       Point2D.Double[] points,
+                       int first,
+                       int last) {
+               // ||v||^2
+               double lv = v.x*v.x + v.y*v.y;
+               for (int i=first; i<=last; i++) {
+                       // A is the coordinates of points[i] after moving the origin at p
+                       Point2D.Double A = new Point2D.Double(points[i].x - p.x, points[i].y - p.y);
+                       // Symmetric of A
+                       Point2D.Double B = new Point2D.Double(
+                                       -(A.x*v.y*v.y - 2*A.y*v.x*v.y - A.x*v.x*v.x) / lv,
+                                        (A.y*v.y*v.y + 2*A.x*v.x*v.y - A.y*v.x*v.x) / lv);
+                       // Change the origin back
+                       points[i].x = B.x + p.x;
+                       points[i].y = B.y + p.y;
+               }
+       }
+       
+       private void computeHelixTranslations(
+                       Tree<RNANodeValueTemplate> tree, // IN
+                       Map<RNATemplateHelix, Point2D.Double> translateVectors, // OUT (must be initialized)
+                       RNATemplateMapping mapping,      // IN
+                       Point2D.Double parentDeltaVector, // IN
+                       boolean straightBulges
+       ) {
+               RNANodeValueTemplate nvt = tree.getValue();
+               Point2D.Double newDeltaVector = parentDeltaVector;
+               if (nvt instanceof RNANodeValueTemplateBasePair) {
+                       RNATemplateHelix helix = ((RNANodeValueTemplateBasePair) nvt).getHelix();
+                       if (! translateVectors.containsKey(helix)) {
+                               translateVectors.put(helix, parentDeltaVector);
+                               int[] basesInHelixArray;
+                               if (mapping.getAncestor(helix) != null) {
+                                       basesInHelixArray = RNATemplateAlign.intArrayFromList(mapping.getAncestor(helix));
+                                       Arrays.sort(basesInHelixArray);
+                               } else {
+                                       basesInHelixArray = new int[0];
+                               }
+                               Point2D.Double helixDeltaVector = computeLengthIncreaseDelta(basesInHelixArray, helix, straightBulges);
+                               newDeltaVector = new Point2D.Double(parentDeltaVector.x+helixDeltaVector.x, parentDeltaVector.y+helixDeltaVector.y);
+                       } 
+               }
+               for (Tree<RNANodeValueTemplate> subtree: tree.getChildren()) {
+                       computeHelixTranslations(subtree, translateVectors, mapping, newDeltaVector, straightBulges);
+               }
+       }
+       
+       private Map<RNATemplateHelix, Point2D.Double> computeHelixTranslations(
+                       Tree<RNANodeValueTemplate> tree, // IN
+                       RNATemplateMapping mapping,       // IN
+                       boolean straightBulges
+       ) {
+               Map<RNATemplateHelix, Point2D.Double> translateVectors = new HashMap<RNATemplateHelix, Point2D.Double>();
+               computeHelixTranslations(tree, translateVectors, mapping, new Point2D.Double(0,0), straightBulges);
+               return translateVectors;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/Mapping.java b/src2/fr/orsay/lri/varna/models/rna/Mapping.java
new file mode 100644 (file)
index 0000000..d9b952b
--- /dev/null
@@ -0,0 +1,192 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.io.Serializable;
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+import fr.orsay.lri.varna.exceptions.MappingException;
+
+public class Mapping implements Serializable {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -3031358968555310380L;
+
+       public static final int UNKNOWN = -1;
+
+       Hashtable<Integer, Integer> _mapping = new Hashtable<Integer, Integer>();
+       Hashtable<Integer, Integer> _invMapping = new Hashtable<Integer, Integer>();
+
+       public Mapping() {
+
+       }
+
+       public void addCouple(int i, int j) throws MappingException {
+               if (_mapping.containsKey(i) || _invMapping.containsKey(j)) {
+                       throw new MappingException(
+                                       MappingException.MULTIPLE_PARTNERS_DEFINITION_ATTEMPT);
+               }
+
+               _mapping.put(new Integer(i), new Integer(j));
+               _invMapping.put(new Integer(j), new Integer(i));
+       }
+
+       public int getPartner(int i) {
+               if (!_mapping.containsKey(i))
+                       return UNKNOWN;
+               else
+                       return _mapping.get(i);
+       }
+
+       public int getAncestor(int j) {
+               if (!_invMapping.containsKey(j))
+                       return UNKNOWN;
+               else
+                       return _invMapping.get(j);
+       }
+
+       public int[] getSourceElems() {
+               int[] elems = new int[_mapping.size()];
+               Enumeration<Integer> en = _mapping.keys();
+               int i = 0;
+               while (en.hasMoreElements()) {
+                       int a = en.nextElement();
+                       elems[i] = a;
+                       i++;
+               }
+               return elems;
+       }
+
+       public int[] getTargetElems() {
+               int[] elems = new int[_invMapping.size()];
+               Enumeration<Integer> en = _invMapping.keys();
+               int i = 0;
+               while (en.hasMoreElements()) {
+                       int a = en.nextElement();
+                       elems[i] = a;
+                       i++;
+               }
+               return elems;
+       }
+
+       public static Mapping readMappingFromAlignment(String m, String n)
+                       throws MappingException {
+               Mapping map = new Mapping();
+               if (m.length() != n.length()) {
+                       throw new MappingException(MappingException.BAD_ALIGNMENT_INPUT);
+               }
+               int i = 0;
+               int j = 0;
+               for (int k = 0; k < m.length(); k++) {
+                       char a = m.charAt(k);
+                       char b = n.charAt(k);
+                       if ((a != '-') && (a != ':') && (b != '-') && (b != ':')) {
+                               map.addCouple(i, j);
+                       }
+
+                       if ((a != '-') && (a != ':')) {
+                               j++;
+                       }
+                       if ((b != '-') && (b != ':')) {
+                               i++;
+                       }
+               }
+               return map;
+       }
+
+       public static Mapping DefaultMapping(int n, int m) {
+               Mapping map = new Mapping();
+               try {
+                       for (int i = 0; i < Math.min(n, m); i++) {
+                               map.addCouple(i, i);
+                       }
+               } catch (MappingException e) {
+                       e.printStackTrace();
+               }
+               return map;
+       }
+
+       public static Mapping DefaultOutermostMapping(int n, int m) {
+               Mapping map = new Mapping();
+               try {
+                       int k = Math.min(n, m);
+                       int i = 0;
+                       int j = 0;
+                       boolean pile = true;
+                       while (i <= (k - 1) - j) {
+                               if (pile) {
+                                       map.addCouple(i, i);
+                                       i++;
+                               } else {
+                                       map.addCouple(n - 1 - j, m - 1 - j);
+                                       j++;
+                               }
+                               pile = !pile;
+                       }
+               } catch (MappingException e) {
+                       e.printStackTrace();
+               }
+               // System.println(map);
+               return map;
+       }
+
+       public String toString() {
+               Enumeration<Integer> en = _mapping.keys();
+               String tmp = "";
+               int l1 = 0;
+               int l2 = 0;
+               int maxIndex = 0;
+               while (en.hasMoreElements()) {
+                       Integer i = en.nextElement();
+                       Integer j = _mapping.get(i);
+                       l1 = Math.max(l1,i);
+                       l2 = Math.max(l2,j);
+                       tmp += "("+i+","+j+")";
+               }
+               maxIndex = Math.max(maxIndex,Math.max(l1,l2));
+               String tmp1 = ""; 
+               String tmp2 = ""; 
+               en = _mapping.keys();
+               
+               int i = l1;
+               int j = l2;
+               while (en.hasMoreElements()) {
+                       Integer a = en.nextElement();
+                       Integer b = _mapping.get(a);
+                       while(a<i)
+                       {
+                               tmp1 = 'x'+tmp1;
+                               tmp2 = '-'+tmp2;
+                               i--;
+                       }
+                       while(b<j)
+                       {
+                               tmp1 = '-'+tmp1;
+                               tmp2 = 'x'+tmp2;
+                               j--;
+                       }
+                       tmp1 = '|'+tmp1;
+                       tmp2 = '|'+tmp2;
+                       i--;j--;
+               }
+               return tmp+"\n"+tmp1+"\n"+tmp2;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModelBaseStyle.java b/src2/fr/orsay/lri/varna/models/rna/ModelBaseStyle.java
new file mode 100644 (file)
index 0000000..6d012a3
--- /dev/null
@@ -0,0 +1,266 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.io.Serializable;
+import java.util.ArrayList;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+/**
+ * The display Style of a rna base with the base name font, the ouline,
+ * innerline, number and name color
+ * 
+ * @author darty
+ * 
+ */
+public class ModelBaseStyle implements Cloneable, Serializable {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -4331494086323517208L;
+
+       private Color _base_outline_color, _base_inner_color, _base_number_color,
+                       _base_name_color;
+
+       private boolean _selected;
+       
+       
+       public static String XML_ELEMENT_NAME = "basestyle";
+       public static String XML_VAR_OUTLINE_NAME = "outline";
+       public static String XML_VAR_INNER_NAME = "inner";
+       public static String XML_VAR_NUMBER_NAME = "num";
+       public static String XML_VAR_NAME_NAME = "name";
+
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_OUTLINE_NAME,"CDATA",""+XMLUtils.toHTMLNotation(_base_outline_color));
+               atts.addAttribute("","",XML_VAR_INNER_NAME,"CDATA",""+XMLUtils.toHTMLNotation(_base_inner_color));
+               atts.addAttribute("","",XML_VAR_NUMBER_NAME,"CDATA",""+XMLUtils.toHTMLNotation(_base_number_color));
+               atts.addAttribute("","",XML_VAR_NAME_NAME,"CDATA",""+XMLUtils.toHTMLNotation(_base_name_color));
+               
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }       
+       
+       public ModelBaseStyle clone()
+       {
+               ModelBaseStyle result = new ModelBaseStyle();
+               result._base_inner_color  = this._base_inner_color;
+               result._base_name_color  = this._base_name_color;
+               result._base_number_color  = this._base_number_color;
+               result._base_outline_color  = this._base_outline_color;
+               result._selected  = this._selected;
+               return result;
+       }
+       
+       
+       
+       /**
+        * Creates a new base style with default colors and font
+        * 
+        * @see VARNAConfig#BASE_OUTLINE_COLOR_DEFAULT
+        * @see VARNAConfig#BASE_INNER_COLOR_DEFAULT
+        * @see VARNAConfig#BASE_NUMBER_COLOR_DEFAULT
+        * @see VARNAConfig#BASE_NAME_COLOR_DEFAULT
+        * 
+        */
+       public ModelBaseStyle() {
+               _base_outline_color = VARNAConfig.BASE_OUTLINE_COLOR_DEFAULT;
+               _base_inner_color = VARNAConfig.BASE_INNER_COLOR_DEFAULT;
+               _base_number_color = VARNAConfig.BASE_NUMBER_COLOR_DEFAULT;
+               _base_name_color = VARNAConfig.BASE_NAME_COLOR_DEFAULT;
+               _selected = false;
+       }
+
+       /**
+        * Creates a new base style with custom colors and custom font
+        * 
+        * @param outline
+        *            The out line color of the base
+        * @param inner
+        *            The inner line color of the base
+        * @param number
+        *            The number color of the base
+        * @param name
+        *            The name color of the base
+        * @param font
+        *            The name font of the base
+        */
+       public ModelBaseStyle(Color outline, Color inner, Color number,
+                       Color name, Font font) {
+               _base_outline_color = outline;
+               _base_inner_color = inner;
+               _base_number_color = number;
+               _base_name_color = name;
+       }
+
+       public ModelBaseStyle(String parameterValue)
+                       throws ExceptionModeleStyleBaseSyntaxError, ExceptionParameterError {
+               this();
+               assignParameters(parameterValue);
+       }
+
+       public ModelBaseStyle(ModelBaseStyle msb) {
+               _base_outline_color = msb.getBaseOutlineColor();
+               _base_inner_color = msb.getBaseInnerColor();
+               _base_number_color = msb.getBaseNumberColor();
+               _base_name_color = msb.getBaseNameColor();
+       }
+
+       public Color getBaseOutlineColor() {
+               return _base_outline_color;
+       }
+
+       public void setBaseOutlineColor(Color _base_outline_color) {
+               this._base_outline_color = _base_outline_color;
+       }
+
+       public Color getBaseInnerColor() {
+               return _base_inner_color;
+       }
+
+       public void setBaseInnerColor(Color _base_inner_color) {
+               this._base_inner_color = _base_inner_color;
+       }
+
+       public Color getBaseNumberColor() {
+               return _base_number_color;
+       }
+
+       public void setBaseNumberColor(Color _base_numbers_color) {
+               this._base_number_color = _base_numbers_color;
+       }
+
+       public Color getBaseNameColor() {
+               return _base_name_color;
+       }
+
+       public void setBaseNameColor(Color _base_name_color) {
+               this._base_name_color = _base_name_color;
+       }
+
+       public static final String PARAM_INNER_COLOR = "fill";
+       public static final String PARAM_OUTLINE_COLOR = "outline";
+       public static final String PARAM_TEXT_COLOR = "label";
+       public static final String PARAM_NUMBER_COLOR = "number";
+
+       public static Color getSafeColor(String col) {
+               Color result;
+               try {
+                       result = Color.decode(col);
+
+               } catch (NumberFormatException e) {
+
+                       result = Color.getColor(col, Color.green);
+               }
+               return result;
+       }
+
+       public void assignParameters(String parametersValue)
+                       throws ExceptionModeleStyleBaseSyntaxError, ExceptionParameterError {
+               if (parametersValue.equals(""))
+                       return;
+
+               String[] parametersL = parametersValue.split(",");
+
+               ArrayList<String> namesArray = new ArrayList<String>();
+               ArrayList<String> valuesArray = new ArrayList<String>();
+               String[] param;
+               for (int i = 0; i < parametersL.length; i++) {
+                       param = parametersL[i].split("=");
+                       if (param.length != 2)
+                               throw new ExceptionModeleStyleBaseSyntaxError(
+                                               "Bad parameter: '" + param[0] + "' ...");
+                       namesArray.add(param[0].replace(" ", ""));
+                       valuesArray.add(param[1].replace(" ", ""));
+
+               }
+
+               for (int i = 0; i < namesArray.size(); i++) {
+                       if (namesArray.get(i).toLowerCase().equals(PARAM_INNER_COLOR)) {
+                               try {
+                                       setBaseInnerColor(getSafeColor(valuesArray.get(i)));
+                               } catch (NumberFormatException e) {
+                                       throw new ExceptionParameterError(e.getMessage(),
+                                                       "Bad inner color Syntax:" + valuesArray.get(i));
+                               }
+                       } else if (namesArray.get(i).toLowerCase().equals(PARAM_TEXT_COLOR)) {
+                               try {
+                                       setBaseNameColor(getSafeColor(valuesArray.get(i)));
+                               } catch (NumberFormatException e) {
+                                       throw new ExceptionParameterError(e.getMessage(),
+                                                       "Bad name color Syntax:" + valuesArray.get(i));
+                               }
+                       } else if (namesArray.get(i).toLowerCase().equals(
+                                       PARAM_NUMBER_COLOR)) {
+                               try {
+                                       setBaseNumberColor(getSafeColor(valuesArray.get(i)));
+                               } catch (NumberFormatException e) {
+                                       throw new ExceptionParameterError(e.getMessage(),
+                                                       "Bad numbers color Syntax:" + valuesArray.get(i));
+                               }
+                       } else if (namesArray.get(i).toLowerCase().equals(
+                                       PARAM_OUTLINE_COLOR)) {
+                               try {
+                                       setBaseOutlineColor(getSafeColor(valuesArray.get(i)));
+                               } catch (NumberFormatException e) {
+                                       throw new ExceptionParameterError(e.getMessage(),
+                                                       "Bad outline color Syntax:" + valuesArray.get(i));
+                               }
+                       } else
+                               throw new ExceptionModeleStyleBaseSyntaxError(
+                                               "Unknown parameter:" + namesArray.get(i));
+               }
+       }
+
+       /**
+        * Find the font style integer from a string. Return <code>null</code> if
+        * the font style is unknown.
+        * 
+        * @param s
+        *            The <code>string</code> to decode
+        * @return The font style integer as <code>Font.PLAIN<code>.
+        */
+       public static Integer StyleToInteger(String s) {
+               Integer style;
+               if (s.toLowerCase().equals("italic"))
+                       style = Font.ITALIC;
+               else if (s.toLowerCase().equals("bold"))
+                       style = Font.BOLD;
+               else if (s.toLowerCase().equals("plain"))
+                       style = Font.PLAIN;
+               else
+                       style = null;
+               return style;
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleBP.java b/src2/fr/orsay/lri/varna/models/rna/ModeleBP.java
new file mode 100644 (file)
index 0000000..138edb0
--- /dev/null
@@ -0,0 +1,331 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Color;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Random;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.models.VARNAConfig;
+
+
+public class ModeleBP implements Serializable, Comparable<ModeleBP> {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -1344722280822711931L;
+
+       public enum Edge {
+               WC, SUGAR, HOOGSTEEN;
+       }
+       public enum Stericity {
+               CIS, TRANS;
+       }
+
+       private ModeleBase _partner5;
+       private Edge _edge5;
+       private ModeleBase _partner3;
+       private Edge _edge3;
+       private Stericity _stericity;
+       private ModeleBPStyle _style;
+
+       
+       public static String XML_ELEMENT_NAME = "bp";
+       public static String XML_VAR_PARTNER5_NAME = "part5";
+       public static String XML_VAR_EDGE5_NAME = "edge5";
+       public static String XML_VAR_PARTNER3_NAME = "part3";
+       public static String XML_VAR_EDGE3_NAME = "edge3";
+       public static String XML_VAR_STERICITY_NAME = "orient";
+       public static String XML_VAR_SEC_STR_NAME = "secstr";
+
+       public void toXML(TransformerHandler hd, boolean inSecondaryStructure) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_PARTNER5_NAME,"CDATA",""+_partner5.getIndex());
+               atts.addAttribute("","",XML_VAR_PARTNER3_NAME,"CDATA",""+_partner3.getIndex());
+               atts.addAttribute("","",XML_VAR_EDGE5_NAME,"CDATA",""+_edge5);
+               atts.addAttribute("","",XML_VAR_EDGE3_NAME,"CDATA",""+_edge3);
+               atts.addAttribute("","",XML_VAR_STERICITY_NAME,"CDATA",""+_stericity);
+               atts.addAttribute("","",XML_VAR_SEC_STR_NAME,"CDATA",""+inSecondaryStructure);
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               _style.toXML(hd);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }
+       
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               toXML(hd, false);
+       }
+       
+
+       
+       public ModeleBP(ModeleBase part5, ModeleBase part3) {
+               this(part5, part3, Edge.WC, Edge.WC, Stericity.CIS);
+       }
+
+       //private static Random rnd = new Random(System.currentTimeMillis());
+
+       public ModeleBP(ModeleBase part5, ModeleBase part3, Edge edge5,
+                       Edge edge3, Stericity ster) {
+               _partner5 = part5;
+               _partner3 = part3;
+               _edge5 = edge5;
+               _edge3 = edge3;
+               _stericity = ster;
+               _style = new ModeleBPStyle();
+       }
+
+       public ModeleBP(String text) throws ExceptionModeleStyleBaseSyntaxError, ExceptionParameterError {
+               _style = new ModeleBPStyle();
+               assignParameters(text);         
+       }
+       
+       public void setStericity(Stericity s) {
+               _stericity = s;
+       }
+
+       public void setEdge5(Edge e) {
+               _edge5 = e;
+       }
+
+       public void setEdge3(Edge e) {
+               _edge3 = e;
+       }
+
+       public void setStyle(ModeleBPStyle e) {
+               _style = e;
+       }
+       
+       public ModeleBPStyle getStyle() {
+               return _style;
+       }
+               
+       public boolean isCanonicalGC() {
+               String si = _partner5.getContent();
+               String sj = _partner3.getContent();
+               if ((si.length() >= 1) && (sj.length() >= 1)) {
+                       char ci = si.toUpperCase().charAt(0);
+                       char cj = sj.toUpperCase().charAt(0);
+                       if (((ci == 'G') && (cj == 'C')) || ((ci == 'C') && (cj == 'G'))) {
+                               return isCanonical() && (getStericity() == Stericity.CIS);
+                       }
+               }
+               return false;
+       }
+
+       public boolean isCanonicalAU() {
+               String si = _partner5.getContent();
+               String sj = _partner3.getContent();
+               if ((si.length() >= 1) && (sj.length() >= 1)) {
+                       char ci = si.toUpperCase().charAt(0);
+                       char cj = sj.toUpperCase().charAt(0);
+                       if (((ci == 'A') && (cj == 'U')) 
+                                       || ((ci == 'U') && (cj == 'A'))
+                                       || ((ci == 'U') && (cj == 'T'))
+                                       || ((ci == 'T') && (cj == 'U'))) {
+                               return isCanonical();
+                       }
+               }
+               return false;
+       }
+
+       public boolean isWobbleUG() {
+               String si = _partner5.getContent();
+               String sj = _partner3.getContent();
+               if ((si.length() >= 1) && (sj.length() >= 1)) {
+                       char ci = si.toUpperCase().charAt(0);
+                       char cj = sj.toUpperCase().charAt(0);
+                       if (((ci == 'G') && (cj == 'U')) || ((ci == 'U') && (cj == 'G'))) {
+                               return (isCanonical());
+                       }
+               }
+               return false;
+       }
+
+       public boolean isCanonical() {
+               return (_edge5 == Edge.WC) && (_edge3 == Edge.WC)
+                               && (_stericity == Stericity.CIS);
+       }
+
+       public Stericity getStericity() {
+               return _stericity;
+       }
+
+       public boolean isCIS() {
+               return (_stericity == Stericity.CIS);
+       }
+
+       public boolean isTRANS() {
+               return (_stericity == Stericity.TRANS);
+       }
+
+       public Edge getEdgePartner5() {
+               return _edge5;
+       }
+
+       public Edge getEdgePartner3() {
+               return _edge3;
+       }
+       
+       public ModeleBase getPartner(ModeleBase mb) {
+               if (mb == _partner3)
+                       return _partner5;
+               else
+                       return _partner3;
+       }
+
+       public ModeleBase getPartner5() {
+               return _partner5;
+       }
+
+       public ModeleBase getPartner3() {
+               return _partner3;
+       }
+
+       public int getIndex5() {
+               return _partner5.getIndex();
+       }
+
+       public int getIndex3() {
+               return _partner3.getIndex();
+       }
+
+       public void setPartner5(ModeleBase mb) {
+               _partner5 = mb;
+       }
+
+       public void setPartner3(ModeleBase mb) {
+               _partner3 = mb;
+       }
+
+
+
+       public static final String PARAM_COLOR = "color";
+       public static final String PARAM_THICKNESS = "thickness";
+       public static final String PARAM_EDGE5 = "edge5";
+       public static final String PARAM_EDGE3 = "edge3";
+       public static final String PARAM_STERICITY = "stericity";
+
+       public static final String VALUE_WATSON_CRICK = "wc";
+       public static final String VALUE_HOOGSTEEN = "h";
+       public static final String VALUE_SUGAR = "s";
+       public static final String VALUE_CIS = "cis";
+       public static final String VALUE_TRANS = "trans";
+
+       public void assignParameters(String parametersValue)
+                       throws ExceptionModeleStyleBaseSyntaxError, ExceptionParameterError {
+               if (parametersValue.equals(""))
+                       return;
+
+               String[] parametersL = parametersValue.split(",");
+
+               ArrayList<String> namesArray = new ArrayList<String>();
+               ArrayList<String> valuesArray = new ArrayList<String>();
+               String[] param;
+               for (int i = 0; i < parametersL.length; i++) {
+                       param = parametersL[i].split("=");
+                       if (param.length != 2)
+                               throw new ExceptionModeleStyleBaseSyntaxError(
+                                               "Bad parameter: '" + param[0] + "' ...");
+                       namesArray.add(param[0].replace(" ", ""));
+                       valuesArray.add(param[1].replace(" ", ""));
+
+               }
+               for (int i = 0; i < namesArray.size(); i++) {
+                       if (namesArray.get(i).toLowerCase().equals(PARAM_COLOR)) {
+                               try {
+                                       _style.setCustomColor(ModelBaseStyle
+                                                       .getSafeColor(valuesArray.get(i)));
+                               } catch (NumberFormatException e) {
+                                       throw new ExceptionParameterError(e.getMessage(),
+                                                       "Bad inner color Syntax:" + valuesArray.get(i));
+                               }
+                       } else if (namesArray.get(i).toLowerCase().equals(PARAM_THICKNESS)) {
+                               try {
+                                       _style.setThickness(Double.parseDouble(valuesArray.get(i)));
+                               } catch (NumberFormatException e) {
+                                       throw new ExceptionParameterError(e.getMessage(),
+                                                       "Bad value for bp thickness:" + valuesArray.get(i));
+                               }
+                       } else if (namesArray.get(i).toLowerCase().equals(PARAM_EDGE5)) {
+                               String s = valuesArray.get(i);
+                               if (s.toLowerCase().equals(VALUE_WATSON_CRICK)) {
+                                       setEdge5(Edge.WC);
+                               } else if (s.toLowerCase().equals(VALUE_HOOGSTEEN)) {
+                                       setEdge5(Edge.HOOGSTEEN);
+                               } else if (s.toLowerCase().equals(VALUE_SUGAR)) {
+                                       setEdge5(Edge.SUGAR);
+                               } else
+                                       throw new ExceptionParameterError("Bad value for edge:"
+                                                       + valuesArray.get(i));
+                       } else if (namesArray.get(i).toLowerCase().equals(PARAM_EDGE3)) {
+                               String s = valuesArray.get(i);
+                               if (s.toLowerCase().equals(VALUE_WATSON_CRICK)) {
+                                       setEdge3(Edge.WC);
+                               } else if (s.toLowerCase().equals(VALUE_HOOGSTEEN)) {
+                                       setEdge3(Edge.HOOGSTEEN);
+                               } else if (s.toLowerCase().equals(VALUE_SUGAR)) {
+                                       setEdge3(Edge.SUGAR);
+                               } else
+                                       throw new ExceptionParameterError("Bad value for edge:"
+                                                       + valuesArray.get(i));
+                       } else if (namesArray.get(i).toLowerCase().equals(PARAM_STERICITY)) {
+                               String s = valuesArray.get(i);
+                               if (s.toLowerCase().equals(VALUE_CIS)) {
+                                       setStericity(Stericity.CIS);
+                               } else if (s.toLowerCase().equals(VALUE_TRANS)) {
+                                       setStericity(Stericity.TRANS);
+                               } else
+                                       throw new ExceptionParameterError(
+                                                       "Bad value for stericity:" + valuesArray.get(i));
+                       } else
+                               throw new ExceptionModeleStyleBaseSyntaxError(
+                                               "Unknown parameter:" + namesArray.get(i));
+               }
+       }
+       
+       public String toString() {
+               String result = "";
+               result += "(" + _partner5.getIndex() + "," + _partner3.getIndex() + ")";
+               //result += " [" + _partner5.getElementStructure() + ","
+               //              + _partner3.getElementStructure() + "]\n";
+               //result += "  5':" + _partner5 + "\n";
+               //result += "  3':" + _partner3;
+               return result;
+       }
+
+
+       public int compareTo(ModeleBP mb) {
+               if (getIndex5()!=mb.getIndex5())
+               {  return getIndex5()-mb.getIndex5();  }
+               return getIndex3()-mb.getIndex3(); 
+               
+       }
+       
+       
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleBPStyle.java b/src2/fr/orsay/lri/varna/models/rna/ModeleBPStyle.java
new file mode 100644 (file)
index 0000000..f5b7398
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Color;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Random;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.exceptions.ExceptionModeleStyleBaseSyntaxError;
+import fr.orsay.lri.varna.exceptions.ExceptionParameterError;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+
+public class ModeleBPStyle implements Serializable {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 3006493290669550139L;
+       /**
+        * 
+        */
+       private boolean _isCustomColored = false;
+       private Color _color = VARNAConfig.DEFAULT_BOND_COLOR;
+
+       private double _thickness = -1.0;
+       private double _bent = 0.0;
+       
+       public static String XML_ELEMENT_NAME = "BPstyle";
+       public static String XML_VAR_CUSTOM_STYLED_NAME = "custom";
+       public static String XML_VAR_COLOR_NAME = "color";
+       public static String XML_VAR_THICKNESS_NAME = "thickness";
+       public static String XML_VAR_BENT_NAME = "bent";
+
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_CUSTOM_STYLED_NAME,"CDATA",""+_isCustomColored);
+               atts.addAttribute("","",XML_VAR_COLOR_NAME,"CDATA",XMLUtils.toHTMLNotation(_color));
+               atts.addAttribute("","",XML_VAR_THICKNESS_NAME,"CDATA",""+_thickness);
+               atts.addAttribute("","",XML_VAR_BENT_NAME,"CDATA",""+_bent);
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }
+
+       
+       public double getBent()
+       {
+               return _bent;
+       }
+
+       
+       public boolean isBent()
+       {
+               return (_bent!=0.0);
+       }
+
+       public void setBent(double b)
+       {
+               _bent = b;
+       }
+
+       
+       public ModeleBPStyle() {
+       }
+
+
+       public void setCustomColor(Color c) {
+               _isCustomColored = true;
+               _color = c;
+       }
+
+       public void useDefaultColor() {
+               _isCustomColored = false;
+       }
+
+       public boolean isCustomColored() {
+               return _isCustomColored;
+       }
+
+       public Color getCustomColor() {
+               return _color;
+       }
+
+       /**
+        * Returns the current custom color if such a color is defined to be used
+        * (through setCustomColor), or returns the default color.
+        * 
+        * @param def
+        *            - The default color is no custom color is defined
+        * @return The color to be used to draw this base-pair
+        */
+       public Color getColor(Color def) {
+               if (isCustomColored()) {
+                       return _color;
+               } else {
+                       return def;
+               }
+       }
+
+       public double getThickness(double def) {
+               if (_thickness > 0)
+                       return _thickness;
+               else
+                       return def;
+       }
+
+       public void setThickness(double thickness) {
+               _thickness = thickness;
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleBackbone.java b/src2/fr/orsay/lri/varna/models/rna/ModeleBackbone.java
new file mode 100644 (file)
index 0000000..caa4b5f
--- /dev/null
@@ -0,0 +1,75 @@
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Color;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.models.rna.ModeleBackboneElement.BackboneType;
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+public class ModeleBackbone  implements Serializable{
+
+       /**
+        * 
+        */
+       private Hashtable<Integer,ModeleBackboneElement> elems = new Hashtable<Integer,ModeleBackboneElement>();
+       
+       private static final long serialVersionUID = -614968737102943216L;
+
+       
+       
+       public static String XML_ELEMENT_NAME = "backbone";
+       
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               for (ModeleBackboneElement bck:elems.values())
+               {
+                       bck.toXML(hd);
+               }
+               hd.endElement("","",XML_ELEMENT_NAME);
+               atts.clear();
+       }
+
+       public void addElement(ModeleBackboneElement mbe)
+       {
+               elems.put(mbe.getIndex(),mbe);
+       }
+
+        public BackboneType getTypeBefore(int indexBase)
+        {
+                return getTypeAfter(indexBase-1);
+        }
+       
+        public BackboneType getTypeAfter(int indexBase)
+        {
+                if (elems.containsKey(indexBase))
+                        return elems.get(indexBase).getType();
+                else
+                        return BackboneType.SOLID_TYPE;
+        }
+
+        public Color getColorBefore(int indexBase, Color defCol)
+        {
+                return getColorAfter(indexBase-1,defCol);
+        }
+       
+        public Color getColorAfter(int indexBase, Color defCol)
+        {
+                if (elems.containsKey(indexBase))
+                {
+                        Color c = elems.get(indexBase).getColor();
+                        if (c != null)
+                                return c;
+                }
+                return defCol;
+        }
+        
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleBackboneElement.java b/src2/fr/orsay/lri/varna/models/rna/ModeleBackboneElement.java
new file mode 100644 (file)
index 0000000..6b16a05
--- /dev/null
@@ -0,0 +1,106 @@
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Color;
+import java.io.Serializable;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+public class ModeleBackboneElement implements Serializable{
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -614968737102943216L;
+
+       public ModeleBackboneElement(int index, BackboneType t)
+       {
+               _index=index;
+               if (t==BackboneType.CUSTOM_COLOR)
+               {
+                       throw new IllegalArgumentException("Error: Missing Color while constructing Backbone");
+               }
+               _type=t;
+       }
+       
+       public ModeleBackboneElement(int index, Color c)
+       {
+               _index=index;
+               _type=BackboneType.CUSTOM_COLOR;
+               _color = c;
+       }
+       
+       public enum BackboneType{
+               SOLID_TYPE ("solid"),
+               DISCONTINUOUS_TYPE ("discontinuous"),
+               MISSING_PART_TYPE ("missing"),
+               CUSTOM_COLOR ("custom");
+               
+               private String label;
+               
+               BackboneType(String s)
+               {
+                       label = s;
+               }
+               
+               public String getLabel()
+               {
+                       return label;
+               }
+               
+               
+               public static BackboneType getType(String lbl)
+               {
+                       BackboneType[] vals = BackboneType.values();
+                       for(int i=0;i<vals.length;i++)
+                       {
+                               if (vals[i].equals(lbl))
+                                       return vals[i];
+                       }
+                       return null;
+               }
+               
+       };
+       
+       private BackboneType _type;
+       private Color _color = null;
+       private int _index;
+
+       
+       public BackboneType getType()
+       {
+               return _type;
+       }
+       
+       public int getIndex()
+       {
+               return _index;
+       }
+       
+       public Color getColor()
+       {
+               return _color;
+       }
+       
+       public static String XML_ELEMENT_NAME = "BackboneElement";
+       public static String XML_VAR_INDEX_NAME = "index";
+       public static String XML_VAR_TYPE_NAME = "type";
+       public static String XML_VAR_COLOR_NAME = "color";      
+       
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_INDEX_NAME,"CDATA",""+_index);
+               atts.addAttribute("","",XML_VAR_TYPE_NAME,"CDATA",""+_type.getLabel());
+               if(_type==BackboneType.CUSTOM_COLOR){
+                       atts.addAttribute("","",XML_VAR_COLOR_NAME,"CDATA",""+XMLUtils.toHTMLNotation(_color)); 
+               }
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleBase.java b/src2/fr/orsay/lri/varna/models/rna/ModeleBase.java
new file mode 100644 (file)
index 0000000..9491ed8
--- /dev/null
@@ -0,0 +1,262 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Universit� Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.geom.Point2D;
+import java.io.Serializable;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+
+
+/**
+ * The abstract rna base model
+ * 
+ * @author darty
+ * 
+ */
+public abstract class ModeleBase implements Serializable, java.lang.Comparable<ModeleBase> {
+
+       private ModeleBP _BP;
+       /**
+        * The base style.
+        */
+       protected ModelBaseStyle _styleBase = new ModelBaseStyle();
+       /**
+        * TRUE if this InterfaceBase has to be colored, else FALSE.
+        */
+       protected Boolean _colorie = new Boolean(true);
+       /**
+        * The coordinate representation of this InterfaceBase on the final graphic.
+        */
+       protected VARNAPoint _coords = new VARNAPoint();
+       /**
+        * The nearest loop center of this InterfaceBase.
+        */
+       protected VARNAPoint _center = new VARNAPoint();
+
+       /**
+        * The label of this base.
+        */
+       protected String _label = "";
+
+       protected double _value;
+       protected int _realIndex = -1;
+
+       public abstract void toXML(TransformerHandler hd) throws SAXException;
+       
+       
+       
+       /**
+        * The internal index for this Base
+        */
+       public abstract int getIndex();
+
+       public abstract String getContent();
+       public abstract void setContent(String s);
+
+       /**
+        * Gets this InterfaceBase style.
+        * 
+        * @return this InterfaceBase style.
+        */
+       public ModelBaseStyle getStyleBase() {
+               return _styleBase;
+       }
+
+       public double getValue()
+       {
+               return _value;
+       }
+
+       public void setValue(double d)
+       {
+               _value = d;
+       }
+       
+       
+       /**
+        * Sets this InterfaceBase style.
+        * 
+        * @param base
+        *            - This InterfaceBase new style.
+        */
+       public void setStyleBase(ModelBaseStyle base) {
+               _styleBase = new ModelBaseStyle(base);
+       }
+
+       /**
+        * Gets this InterfaceBase color statement.
+        * 
+        * @return TRUE if this InterfaceBase has to be colored, else FALSE.
+        */
+       public final Boolean getColorie() {
+               return _colorie;
+       }
+
+       /**
+        * Sets this InterfaceBase color statement.
+        * 
+        * @param _colorie
+        *            - TRUE if you want this InterfaceBase to be colored, else
+        *            FALSE
+        */
+       public final void setColorie(Boolean _colorie) {
+               this._colorie = _colorie;
+       }
+
+
+       /**
+        * Gets this InterfaceBase associated structure element.
+        * 
+        * @return this InterfaceBase associated structure element.
+        */
+       public int getElementStructure() {
+               if (_BP==null)
+                       return -1;
+               else
+               {
+                 if (_BP.getPartner5()==this)
+                         return _BP.getPartner3().getIndex();
+                 else
+                         return _BP.getPartner5().getIndex();
+               }
+       }
+
+
+       /**
+        * Sets this InterfaceBase assiocated structure element.
+        * 
+        * @param structure
+        *            - This new assiocated structure element.
+       
+       public void setElementStructure(int structure) {
+               setElementStructure(structure, new ModeleBP());
+       } */
+
+       /**
+        * Sets this InterfaceBase associated structure element.
+        * 
+        * @param structure
+        *            - This new associated structure element.
+        * @param type
+        *            - The type of this base pair.
+        */
+       public void setElementStructure(int structure, ModeleBP type) {
+//             _elementStructure = structure;
+               _BP = type;
+
+       }
+
+       public void removeElementStructure() {
+//             _elementStructure = -1;
+               _BP = null;
+       }
+       
+       
+       /**
+        * Gets the base pair type for this element.
+        * 
+        * @return the base pair type for this element.
+        */
+       public ModeleBP getStyleBP() {
+               return _BP;
+       }
+
+       /**
+        * Sets the base pair type for this element.
+        * 
+        * @param type
+        *            - The new base pair type for this element.
+        */
+       public void setStyleBP(ModeleBP type) {
+               _BP = type;
+       }
+
+       public int getBaseNumber() {
+               return _realIndex;
+       }
+
+       public void setBaseNumber(int bn) {
+               _realIndex = bn;
+       }
+       
+       public Point2D.Double getCoords() {
+               return new Point2D.Double(_coords.x,_coords.y);
+       }
+
+       public void setCoords(Point2D.Double coords) {
+               this._coords.x = coords.x;
+               this._coords.y = coords.y;
+       }
+
+       public Point2D.Double getCenter() {
+               return new Point2D.Double(_center.x,_center.y);
+       }
+
+       public void setCenter(Point2D.Double center) {
+               this._center.x = center.x;
+               this._center.y = center.y;
+       }
+
+       public String getLabel() {
+               if (_label==null || _label.equals(""))
+               {
+                       return ""+this.getBaseNumber();
+               }
+               else
+               {
+                       return _label;
+               }
+                       
+       }
+
+       public void setLabel(String s) {
+               _label= s;
+       }
+
+       public void setLabel(Point2D.Double center) {
+               this._center.x = center.x;
+               this._center.y = center.y;
+       }
+
+
+       public int compareTo(ModeleBase other) { 
+           int nombre1 = ((ModeleBase) other).getIndex(); 
+           int nombre2 = this.getIndex(); 
+           if (nombre1 > nombre2)  return -1; 
+           else if(nombre1 == nombre2) return 0; 
+           else return 1; 
+       } 
+       
+       public static String XML_VAR_TYPE_NAME = "type";
+       public static String XML_VAR_INDEX_NAME = "index";
+       public static String XML_VAR_LABEL_NAME = "label";
+       public static String XML_VAR_VALUE_NAME = "val";
+       public static String XML_VAR_POSITION_NAME = "pos";
+       public static String XML_VAR_CENTER_NAME = "center";
+       public static String XML_VAR_NUMBER_NAME = "num";
+       public static String XML_VAR_CUSTOM_DRAWN_NAME = "custom";
+       
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleBaseNucleotide.java b/src2/fr/orsay/lri/varna/models/rna/ModeleBaseNucleotide.java
new file mode 100644 (file)
index 0000000..ad0c5c1
--- /dev/null
@@ -0,0 +1,408 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.geom.Point2D;
+import java.util.HashMap;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+
+/**
+ * The rna base model with the first character of the nitrogenous base and it
+ * display
+ * 
+ * @author darty
+ * 
+ */
+public class ModeleBaseNucleotide extends ModeleBase {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -5493938366569588113L;
+       private String _c;
+       private int _index;
+       
+
+       
+       public static String XML_ELEMENT_NAME = "nt";
+       public static String XML_VAR_CONTENT_NAME = "base";
+       
+       
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_INDEX_NAME,"CDATA",""+_index);
+               atts.addAttribute("","",XML_VAR_NUMBER_NAME,"CDATA",""+_realIndex);
+               atts.addAttribute("","",XML_VAR_CUSTOM_DRAWN_NAME,"CDATA",""+_colorie);
+               atts.addAttribute("","",XML_VAR_VALUE_NAME,"CDATA",""+_value);
+               atts.addAttribute("","",XML_VAR_LABEL_NAME,"CDATA",""+_label);
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               atts.clear();
+               hd.startElement("","",XML_VAR_CONTENT_NAME,atts);
+               XMLUtils.exportCDATAString(hd, _c);
+               hd.endElement("","",XML_VAR_CONTENT_NAME);
+
+               _coords.toXML(hd,XML_VAR_POSITION_NAME);
+               _center.toXML(hd,XML_VAR_CENTER_NAME);
+               if (_colorie)
+               { _styleBase.toXML(hd); }
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }
+
+       /**
+        * Creates a new rna base with the default display style and a space as
+        * nitrogenous base
+        * @param index The index of this base
+        */
+       public ModeleBaseNucleotide(int index) {
+               this(" ", index);
+       }
+
+       /**
+        * Creates a new rna base with the nitrogenous base
+        * 
+        * @param s
+        *            The code of this base
+        * @param index The index of this base
+        */
+       public ModeleBaseNucleotide(String s, int index) {
+               this(s, new ModelBaseStyle(), index);
+       }
+
+
+       /**
+        * Creates a new rna base with the nitrogenous base
+        * 
+        * @param s
+        *            The full label, potentially requiring further decoding
+        * @param index The index of this base
+        * @param baseNumber The number of this base, which may differ from the index (e.g. discontinuous numbering)
+        */
+       public ModeleBaseNucleotide(String s, int index, int baseNumber) {
+               this(s, new ModelBaseStyle(), index);
+               _realIndex = baseNumber;
+       }
+
+       /**
+        * Creates a new rna base with the nitrogenous base and the display style
+        * 
+        * @param s
+        *            The full label, potentially requiring further decoding
+        * @param msb
+        *            The display style
+        * @param index The index of this base
+        */
+       public ModeleBaseNucleotide(String s, ModelBaseStyle msb, int index) {
+               this(new Point2D.Double(), new Point2D.Double(), true, s, msb, -1,
+                               index);
+       }
+
+       /**
+        * Creates a new rna base with a display style
+        * 
+        * @param msb
+        *            The display style
+        */
+       public ModeleBaseNucleotide(ModelBaseStyle msb, int index, int baseNumber) {
+               this("", msb, index);
+               _realIndex = baseNumber;
+       }
+
+       /**
+        * Creates a new rna base with a space as the nitrogenous base and the
+        * display style
+        * 
+        * @param coord
+        * @param index
+        */
+       public ModeleBaseNucleotide(Point2D.Double coord, int index) {
+               this(new Point2D.Double(coord.getX(), coord.getY()),
+                               new Point2D.Double(), true, "", new ModelBaseStyle(), -1,
+                               index);
+       }
+
+       /**
+        * Creates a new rna base from another one with the same attributes
+        * 
+        * @param mb
+        *            The base to copy
+        */
+       public ModeleBaseNucleotide(ModeleBaseNucleotide mb, int index) {
+               this(
+                               new Point2D.Double(mb.getCoords().getX(), mb.getCoords()
+                                               .getY()), new Point2D.Double(mb.getCenter().getX(), mb
+                                               .getCenter().getY()), true, mb.getBase(), mb
+                                               .getStyleBase(), mb.getElementStructure(), index);
+       }
+
+       public ModeleBaseNucleotide(Point2D.Double coords, Point2D.Double center,
+                       boolean colorie, String label, ModelBaseStyle mb, int elementStruct,
+                       int index) {
+               _colorie = colorie;
+               _c = label;
+               _styleBase = mb;
+               _coords = new VARNAPoint(coords);
+               _center = new VARNAPoint(center);
+               _index = index;
+               _realIndex = index + 1;
+               _value = 0.0;
+       }
+
+       
+       public ModelBaseStyle getStyleBase() {
+               if (_colorie)
+                       return _styleBase;
+               return new ModelBaseStyle();
+       }
+
+       public String getBase() {
+               return decode(_c);
+       }
+
+       public void setBase(String _s) {
+               this._c = _s;
+       }
+
+
+
+       public String getContent() {
+               return getBase();
+       }
+
+       public void setContent(String s) {
+               setBase(s);
+       }
+
+       public int getIndex() {
+               return _index;
+       }
+       
+       public String toString()
+       {
+               return ""+this._realIndex+" ("+_index+") (x,y):"+this._coords +" C:"+_center;
+       }
+
+       
+       private enum STATE_SPECIAL_CHARS_STATES{ NORMAL,SUBSCRIPT, SUPERSCRIPT, COMMAND};
+
+       private static HashMap<Character,Character> _subscripts = new HashMap<Character,Character>();
+       private static HashMap<Character,Character> _superscripts = new HashMap<Character,Character>();
+       private static HashMap<String,Character> _commands = new HashMap<String,Character>();
+       {
+               _subscripts.put('0', '\u2080');
+               _subscripts.put('1', '\u2081');
+               _subscripts.put('2', '\u2082');
+               _subscripts.put('3', '\u2083');
+               _subscripts.put('4', '\u2084');
+               _subscripts.put('5', '\u2085');
+               _subscripts.put('6', '\u2086');
+               _subscripts.put('7', '\u2087');
+               _subscripts.put('8', '\u2088');
+               _subscripts.put('9', '\u2089');
+               _subscripts.put('+', '\u208A');
+               _subscripts.put('-', '\u208B');
+               _subscripts.put('a', '\u2090');
+               _subscripts.put('e', '\u2091');
+               _subscripts.put('o', '\u2092');
+               _subscripts.put('i', '\u1D62');
+               _subscripts.put('r', '\u1D63');
+               _subscripts.put('u', '\u1D64');
+               _subscripts.put('v', '\u1D65');
+               _subscripts.put('x', '\u2093');
+               _superscripts.put('0', '\u2070');
+               _superscripts.put('1', '\u00B9');
+               _superscripts.put('2', '\u00B2');
+               _superscripts.put('3', '\u00B3');
+               _superscripts.put('4', '\u2074');
+               _superscripts.put('5', '\u2075');
+               _superscripts.put('6', '\u2076');
+               _superscripts.put('7', '\u2077');
+               _superscripts.put('8', '\u2078');
+               _superscripts.put('9', '\u2079');
+               _superscripts.put('+', '\u207A');
+               _superscripts.put('-', '\u207B');
+               _superscripts.put('i', '\u2071');
+               _superscripts.put('n', '\u207F');
+               _commands.put("alpha",  '\u03B1');
+               _commands.put("beta",   '\u03B2');
+               _commands.put("gamma",  '\u03B3');
+               _commands.put("delta",  '\u03B4');
+               _commands.put("epsilon",'\u03B5');
+               _commands.put("zeta",   '\u03B6');
+               _commands.put("eta",    '\u03B7');
+               _commands.put("theta",  '\u03B8');
+               _commands.put("iota",   '\u03B9');
+               _commands.put("kappa",  '\u03BA');
+               _commands.put("lambda", '\u03BB');
+               _commands.put("mu",     '\u03BC');
+               _commands.put("nu",     '\u03BD');
+               _commands.put("xi",     '\u03BE');
+               _commands.put("omicron",'\u03BF');
+               _commands.put("pi",     '\u03C1');
+               _commands.put("rho",    '\u03C2');
+               _commands.put("sigma",  '\u03C3');
+               _commands.put("tau",    '\u03C4');
+               _commands.put("upsilon",'\u03C5');
+               _commands.put("phi",    '\u03C6');
+               _commands.put("chi",    '\u03C7');
+               _commands.put("psi",    '\u03C8');
+               _commands.put("omega",  '\u03C9');
+               _commands.put("Psi",    '\u03A8');
+               _commands.put("Phi",    '\u03A6');
+               _commands.put("Sigma",  '\u03A3');
+               _commands.put("Pi",     '\u03A0');
+               _commands.put("Theta",  '\u0398');
+               _commands.put("Omega",  '\u03A9');
+               _commands.put("Gamma",  '\u0393');
+               _commands.put("Delta",  '\u0394');
+               _commands.put("Lambda", '\u039B');
+       }
+
+       
+       
+       private static String decode(String s)
+       {
+               if (s.length()<=1)
+               {
+                       return s;
+               }
+               STATE_SPECIAL_CHARS_STATES state = STATE_SPECIAL_CHARS_STATES.NORMAL;
+               
+               String result = "";
+               String buffer = ""; 
+               for(int i=0;i<s.length();i++)
+               {
+                       char c = s.charAt(i);
+                       switch (state)
+                       {
+                               case NORMAL:
+                               {
+                                       switch(c)
+                                       {
+                                               case '_':
+                                                       state = STATE_SPECIAL_CHARS_STATES.SUBSCRIPT;
+                                               break;
+                                               case '^':
+                                                       state = STATE_SPECIAL_CHARS_STATES.SUPERSCRIPT;
+                                               break;
+                                               case '\\':
+                                                       buffer = "";
+                                                       state = STATE_SPECIAL_CHARS_STATES.COMMAND;
+                                               break;
+                                               default:
+                                                       result += c;
+                                                       state = STATE_SPECIAL_CHARS_STATES.NORMAL;
+                                               break;
+                                       }
+                               }
+                               break;
+                               case SUBSCRIPT:
+                               case SUPERSCRIPT:
+                               {
+                                       switch(c)
+                                       {
+                                               case '_':
+                                                       state = STATE_SPECIAL_CHARS_STATES.SUBSCRIPT;
+                                               break;
+                                               case '^':
+                                                       state = STATE_SPECIAL_CHARS_STATES.SUPERSCRIPT;
+                                               break;
+                                               case '\\':
+                                                       buffer = "";
+                                                       state = STATE_SPECIAL_CHARS_STATES.COMMAND;
+                                               break;
+                                               default:
+                                                       if ((state==STATE_SPECIAL_CHARS_STATES.SUBSCRIPT) && _subscripts.containsKey(c))
+                                                               result += _subscripts.get(c); 
+                                                       else if ((state==STATE_SPECIAL_CHARS_STATES.SUPERSCRIPT) && _superscripts.containsKey(c))
+                                                               result += _superscripts.get(c); 
+                                                       else
+                                                               result += c;
+                                                       state = STATE_SPECIAL_CHARS_STATES.NORMAL;
+                                               break;
+                                       }
+                               }
+                               break;
+                               case COMMAND:
+                               {
+                                       switch(c)
+                                       {
+                                               case '_':
+                                                       if (_commands.containsKey(buffer))
+                                                       { result += _commands.get(buffer); }
+                                                       else
+                                                       { result += buffer; }
+                                                       buffer = "";
+                                                       state = STATE_SPECIAL_CHARS_STATES.SUBSCRIPT;
+                                               break;
+                                               case '^':
+                                                       if (_commands.containsKey(buffer))
+                                                       { result += _commands.get(buffer); }
+                                                       else
+                                                       { result += buffer; }
+                                                       buffer = "";
+                                                       state = STATE_SPECIAL_CHARS_STATES.SUPERSCRIPT;
+                                               break;
+                                               case '\\':
+                                                       if (_commands.containsKey(buffer))
+                                                       { result += _commands.get(buffer); }
+                                                       else
+                                                       { result += buffer; }
+                                                       buffer = "";
+                                                       state = STATE_SPECIAL_CHARS_STATES.COMMAND;
+                                               break;
+                                               case ' ':
+                                                       state = STATE_SPECIAL_CHARS_STATES.NORMAL;
+                                                       if (_commands.containsKey(buffer))
+                                                       { 
+                                                               result += _commands.get(buffer);
+                                                       }
+                                                       else
+                                                       {
+                                                               result += buffer;
+                                                       }
+                                                       buffer = "";
+                                               break;
+                                               default:
+                                                       buffer += c;
+                                               break;
+                                       }
+                               }
+                               break;
+                       }
+               }
+               if (_commands.containsKey(buffer))
+               { 
+                       result += _commands.get(buffer);
+               }
+               else
+               {
+                       result += buffer;
+               }
+               return result;
+       }
+       
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleBasesComparison.java b/src2/fr/orsay/lri/varna/models/rna/ModeleBasesComparison.java
new file mode 100644 (file)
index 0000000..6e9fec7
--- /dev/null
@@ -0,0 +1,354 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Color;
+import java.awt.geom.Point2D;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.utils.XMLUtils;
+
+
+/**
+ * <b>The RNA base comparison model</b>. In each bases we'll place <b>two
+ * characters</b> representing nitrogenous bases of both RNA that have to be
+ * compared. So, in each base in the comparison model, we'll have a <b>couple of
+ * bases</b>, with the same coordinates on the final drawing.
+ * 
+ * @author Masson
+ * 
+ */
+public class ModeleBasesComparison extends ModeleBase {
+
+       /*
+        * LOCAL FIELDS
+        */
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -2733063250714562463L;
+
+       /**
+        * The base of the first RNA associated with the base of the second RNA.
+        */
+       private Character _base1;
+
+       /**
+        * The base of the second RNA associated with the base of the first RNA.
+        */
+       private Character _base2;
+
+       /**
+        * This ModeleBasesComparison owning statement. It's value will be 0 if this
+        * base is common for both RNA that had been compared, 1 if this base is
+        * related to the first RNA, 2 if related to the second. Default is -1.
+        */
+       private int _appartenance = -1;
+
+       /**
+        * This base's offset in the sequence
+        */
+       private int _index;
+
+       public static String XML_ELEMENT_NAME = "NTPair";
+       public static String XML_VAR_FIRST_CONTENT_NAME = "base1";
+       public static String XML_VAR_SECOND_CONTENT_NAME = "base2";
+       public static String XML_VAR_MEMBERSHIP_NAME = "type";
+
+       
+       
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("","",XML_VAR_INDEX_NAME,"CDATA",""+_index);
+               atts.addAttribute("","",XML_VAR_NUMBER_NAME,"CDATA",""+_realIndex);
+               atts.addAttribute("","",XML_VAR_CUSTOM_DRAWN_NAME,"CDATA",""+_colorie);
+               atts.addAttribute("","",XML_VAR_LABEL_NAME,"CDATA",""+_label);
+               atts.addAttribute("","",XML_VAR_MEMBERSHIP_NAME,"CDATA",""+_appartenance);
+               atts.addAttribute("","","VALUE","CDATA",""+_value);
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               atts.clear();
+               hd.startElement("","",XML_VAR_FIRST_CONTENT_NAME,atts);
+               XMLUtils.exportCDATAString(hd, ""+_base1);
+               hd.endElement("","",XML_VAR_FIRST_CONTENT_NAME);
+               atts.clear();
+               hd.startElement("","",XML_VAR_SECOND_CONTENT_NAME,atts);
+               XMLUtils.exportCDATAString(hd, ""+_base2);
+               hd.endElement("","",XML_VAR_SECOND_CONTENT_NAME);
+               
+               _coords.toXML(hd,XML_VAR_POSITION_NAME);
+               _center.toXML(hd,XML_VAR_CENTER_NAME);
+               if (_colorie)
+               { _styleBase.toXML(hd); }
+               hd.endElement("","",XML_ELEMENT_NAME);
+
+       }
+
+
+       /*
+        * -> END LOCAL FIELDS <--
+        */
+
+       public static Color FIRST_RNA_COLOR = Color.decode("#FFDD99");
+       public static Color SECOND_RNA_COLOR = Color.decode("#99DDFF");
+       public static Color BOTH_RNA_COLOR = Color.decode("#99DD99");
+       public static Color DEFAULT_RNA_COLOR = Color.white;
+
+       /*
+        * CONSTRUCTORS
+        */
+
+       /**
+        * Creates a new comparison base with the default display style and no
+        * nitrogenous bases.
+        */
+       public ModeleBasesComparison(int index) {
+               this(' ', ' ', index);
+       }
+
+       /**
+        * Creates a new comparison base at the specified coordinates, with the
+        * default display style and no nitrogenous bases.
+        * 
+        * @param coords
+        *            - The coordinates in which the comparison base has to be
+        *            placed.
+        */
+       public ModeleBasesComparison(Point2D coords, int index) {
+               this(' ', ' ', new Point2D.Double(coords.getX(), coords.getY()), index);
+       }
+
+       /**
+        * Creates a new comparison base with the specified nitrogenous bases.
+        * 
+        * @param base1
+        *            - The first RNA' nitrogenous base
+        * @param base2
+        *            - The second RNA' nitrogenous base
+        */
+       public ModeleBasesComparison(char base1, char base2, int index) {
+               this(base1, base2, -1, index);
+       }
+
+       /**
+        * Creates a new comparison base with the specified nitrogenous bases, at
+        * the specified coordinates.
+        * 
+        * @param base1
+        *            - The first RNA' nitrogenous base
+        * @param base2
+        *            - The second RNA' nitrogenous base
+        * @param coords
+        *            - The coordinates in which the comparison base has to be
+        *            placed.
+        */
+       public ModeleBasesComparison(char base1, char base2, Point2D coords,
+                       int index) {
+               this(new Point2D.Double(coords.getX(), coords.getY()), base1, base2,
+                               true, new ModelBaseStyle(), -1, index);
+       }
+
+       /**
+        * Creates a new comparison base with the specified nitrogenous bases.
+        * 
+        * @param base1
+        *            - The first RNA' nitrogenous base
+        * @param base2
+        *            - The second RNA' nitrogenous base
+        */
+       public ModeleBasesComparison(char base1, char base2, int elementStructure,
+                       int index) {
+               this(new Point2D.Double(), base1, base2, true, new ModelBaseStyle(),
+                               elementStructure, index);
+       }
+
+       /**
+        * Creates a new comparison base with the specified nitrogenous bases.
+        * 
+        * @param coords
+        *            - This base's XY coordinates
+        * @param base1
+        *            - The first RNA' nitrogenous base
+        * @param base2
+        *            - The second RNA' nitrogenous base
+        * @param colorie
+        *            - Whether or not this base will be drawn
+        * @param mb
+        *            - The drawing style for this base
+        * @param elementStructure
+        *            - The index of a bp partner in the secondary structure
+        * @param index
+        *            - Index of this base in its initial sequence
+        */
+       public ModeleBasesComparison(Point2D coords, char base1, char base2,
+                       boolean colorie, ModelBaseStyle mb, int elementStructure, int index) {
+               _colorie = colorie;
+               _base1 = base1;
+               _base2 = base2;
+               _styleBase = mb;
+               _coords = new VARNAPoint(coords.getX(), coords.getY());
+               _index = index;
+       }
+
+       /*
+        * -> END CONSTRUCTORS <--
+        */
+
+       /*
+        * GETTERS & SETTERS
+        */
+
+       /**
+        * Return the display style associated to this comparison base.
+        * 
+        * @return The display style associated to this comparison base.
+        */
+       public ModelBaseStyle getStyleBase() {
+               if (_colorie)
+                       return _styleBase;
+               return new ModelBaseStyle();
+       }
+
+       /**
+        * Allows to know if this comparison base is colored.
+        * 
+        * @return TRUE if this comparison base is colored, else FALSE.
+        */
+       public Boolean getColored() {
+               return _colorie;
+       }
+
+       /**
+        * Sets the coloration authorization of this comparison base.
+        * 
+        * @param colored
+        *            - TRUE if this comparison base has to be colored, else FALSE.
+        */
+       public void set_colored(Boolean colored) {
+               this._colorie = colored;
+       }
+
+
+       /**
+        * Return the base of the first RNA in this comparison base.
+        * 
+        * @return The base of the first RNA in this comparison base.
+        */
+       public Character getBase1() {
+               return _base1;
+       }
+
+       /**
+        * Sets the base of the first RNA in this comparison base.
+        * 
+        * @param _base1
+        *            - The base of the first RNA in this comparison base.
+        */
+       public void setBase1(Character _base1) {
+               this._base1 = _base1;
+       }
+
+       /**
+        * Return the base of the second RNA in this comparison base.
+        * 
+        * @return The base of the second RNA in this comparison base.
+        */
+       public Character getBase2() {
+               return _base2;
+       }
+
+       /**
+        * Sets the base of the second RNA in this comparison base.
+        * 
+        * @param _base2
+        *            - The base of the second RNA in this comparison base.
+        */
+       public void setBase2(Character _base2) {
+               this._base2 = _base2;
+       }
+
+       /*
+        * --> END GETTERS & SETTERS <--
+        */
+
+       /**
+        * Gets the string representation of the two bases in this
+        * ModeleBasesComparison.
+        * 
+        * @return the string representation of the two bases in this
+        *         ModeleBasesComparison.
+        */
+       public String getBases() {
+               return String.valueOf(_base1) + String.valueOf(_base2);
+       }
+
+       public String getContent() {
+               return getBases();
+       }
+
+
+       /**
+        * Gets this base's related RNA.
+        * 
+        * @return 0 if this base is common for both RNA<br>
+        *         1 if this base is related to the first RNA<br>
+        *         2 if this base is related to the second RNA
+        */
+       public int get_appartenance() {
+               return _appartenance;
+       }
+
+       /**
+        * Sets this base's related RNA.
+        * 
+        * @param _appartenance
+        *            : 0 if this base is common for both RNA<br>
+        *            1 if this base is related to the first RNA<br>
+        *            2 if this base is related to the second RNA.
+        */
+       public void set_appartenance(int _appartenance) {
+               if (_appartenance == 0) {
+                       this.getStyleBase().setBaseInnerColor(BOTH_RNA_COLOR);
+               } else if (_appartenance == 1) {
+                       this.getStyleBase().setBaseInnerColor(FIRST_RNA_COLOR);
+               } else if (_appartenance == 2) {
+                       this.getStyleBase().setBaseInnerColor(SECOND_RNA_COLOR);
+               } else {
+                       this.getStyleBase().setBaseInnerColor(DEFAULT_RNA_COLOR);
+               }
+               this._appartenance = _appartenance;
+       }
+
+
+
+       public int getIndex() {
+               return _index;
+       }
+
+       @Override
+       public void setContent(String s) {
+               this.setBase1(s.charAt(0));
+               this.setBase2(s.charAt(1));
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleColorMap.java b/src2/fr/orsay/lri/varna/models/rna/ModeleColorMap.java
new file mode 100644 (file)
index 0000000..9570ad4
--- /dev/null
@@ -0,0 +1,357 @@
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Color;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Serializable;
+import java.io.StreamTokenizer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Formatter;
+import java.util.Vector;
+
+public class ModeleColorMap implements Cloneable, Serializable{
+  /**
+        * 
+        */
+       private static final long serialVersionUID = 4055062096061553106L;
+private Vector<Color> _map;
+  private Vector<Double> _values;
+  
+  public static final Color DEFAULT_COLOR = Color.GREEN; 
+  
+  public enum NamedColorMapTypes {
+         RED ("red",ModeleColorMap.redColorMap()),
+         BLUE ("blue",ModeleColorMap.blueColorMap()),
+         GREEN ("green",ModeleColorMap.greenColorMap()),
+         HEAT ("heat",ModeleColorMap.heatColorMap()),
+         ENERGY ("energy",ModeleColorMap.energyColorMap()),
+         ROCKNROLL ("rocknroll",ModeleColorMap.rockNRollColorMap()),
+         VIENNA ("vienna",ModeleColorMap.viennaColorMap()),
+         BW ("bw",ModeleColorMap.bwColorMap());
+         
+         String _id;
+         ModeleColorMap _cm;
+         
+         private NamedColorMapTypes(String id, ModeleColorMap cm)
+         {
+               _id = id;
+               _cm = cm;
+         }
+         
+         public String getId()
+         {
+                 return _id;
+         }
+         public ModeleColorMap getColorMap()
+         {
+                 return _cm;
+         }
+         public String toString()
+         {
+               return _id; 
+         }
+  }
+  
+  
+  public ModeleColorMap()
+  {
+    this(new Vector<Color>(),new Vector<Double>());
+  }
+
+  
+  public ModeleColorMap(Vector<Color> map,
+                 Vector<Double> values)
+  {
+         _map = map;
+         _values = values;
+  }
+  
+  public void addColor(double val, Color col)
+  {
+         int offset = Arrays.binarySearch(_values.toArray(), val) ;
+         if (offset<0)
+         {
+                 int inspoint = (-offset)-1;
+                 _map.insertElementAt(col, inspoint);            
+                 _values.insertElementAt(val,inspoint);                  
+         }
+  }
+
+  public double getMinValue()
+  {
+         if (_values.size()>0)
+           return _values.get(0);
+         return 0.0;
+  }
+  public double getMaxValue()
+  {
+         if (_values.size()>0)
+           return _values.get(_values.size()-1);
+         return 0.0;
+  }
+  
+  public Color getMinColor()
+  {
+         if (_map.size()>0)
+           return _map.get(0);
+         return DEFAULT_COLOR;
+  }
+
+  public Color getMaxColor()
+  {
+         if (_map.size()>0)
+           return _map.get(_map.size()-1);
+         return DEFAULT_COLOR;
+  }
+
+  public int getNumColors()
+  {
+         return (_map.size());
+  }
+  public Color getColorAt(int i)
+  {
+         return (_map.get(i));
+  }
+
+  public Double getValueAt(int i)
+  {
+         return (_values.get(i));
+  }
+  
+  public Color getColorForValue(double val)
+  {
+         Color result; 
+         if (val<=getMinValue())
+         {       result = getMinColor(); }
+         else if (val>=getMaxValue())
+         {
+                 result = getMaxColor();
+         }
+         else
+         {
+         int offset = Arrays.binarySearch(_values.toArray(), val) ;
+         if (offset>=0)
+         {
+                 result =  _map.get(offset);
+         }
+         else
+         {
+                 int inspoint = (-offset)-1;
+                 Color c1 = _map.get(inspoint);
+                 double v1 = _values.get(inspoint);
+                 if (inspoint>0)
+                 {
+                         Color c2 = _map.get(inspoint-1);
+                         double v2 = _values.get(inspoint-1);
+                         double blendCoeff = (v2-val)/(v2-v1);
+                         result =  new Color((int)(blendCoeff*c1.getRed()+(1.0-blendCoeff)*c2.getRed()),
+                                 (int)(blendCoeff*c1.getGreen()+(1.0-blendCoeff)*c2.getGreen()),
+                                 (int)(blendCoeff*c1.getBlue()+(1.0-blendCoeff)*c2.getBlue()));
+                        
+                 }
+                 else
+                 {
+                       result = c1;  
+                 }
+         }
+         }
+         return result;
+  }
+  
+  public static ModeleColorMap energyColorMap()
+  {
+         ModeleColorMap cm = new ModeleColorMap();
+         cm.addColor(1.0,new Color(128,50,50).brighter());
+         cm.addColor(0.9,new Color(255,50,50).brighter());
+         cm.addColor(0.65,new Color(255,255,50).brighter());
+         cm.addColor(0.55,new Color(20,255,50).brighter());
+         cm.addColor(0.2,new Color(50,50,255).brighter());
+         cm.addColor(0.0,new Color(50,50,128).brighter());
+         return cm;
+  }
+  
+  public static ModeleColorMap viennaColorMap()
+  {
+         ModeleColorMap cm = new ModeleColorMap();
+         cm.addColor(0.0,new Color(0,80,220));
+         cm.addColor(0.1,new Color(0,139,220));
+         cm.addColor(0.2,new Color(0,220,218));
+         cm.addColor(0.3,new Color(0,220,123));
+         cm.addColor(0.4,new Color(0,220,49));
+         cm.addColor(0.5,new Color(34,220,0));
+         cm.addColor(0.6,new Color(109,220,0));
+         cm.addColor(0.7,new Color(199,220,0));
+         cm.addColor(0.8,new Color(220,165,0));
+         cm.addColor(0.9,new Color(220,86,0));
+         cm.addColor(1.0,new Color(220,0,0));
+         return cm;
+  }
+  
+  public static ModeleColorMap bwColorMap()
+  {
+         ModeleColorMap cm = new ModeleColorMap();
+         cm.addColor(0.0,Color.white);
+         cm.addColor(1.0,Color.gray.darker());
+         return cm;
+  }
+
+  public static ModeleColorMap greenColorMap()
+  {
+         ModeleColorMap cm = new ModeleColorMap();
+         cm.addColor(0.0,Color.gray.brighter().brighter());
+         cm.addColor(1.0,Color.green.darker());
+         return cm;
+  }
+  
+  public static ModeleColorMap blueColorMap()
+  {
+         ModeleColorMap cm = new ModeleColorMap();
+         cm.addColor(0.0,Color.gray.brighter().brighter());
+         cm.addColor(1.0,Color.blue);
+         return cm;
+  }
+  
+  public static ModeleColorMap redColorMap()
+  {
+         ModeleColorMap cm = new ModeleColorMap();
+         cm.addColor(0.0,Color.gray.brighter().brighter());
+         cm.addColor(1.0,Color.red);
+         return cm;
+  }
+
+  public static ModeleColorMap heatColorMap()
+  {
+         ModeleColorMap cm = new ModeleColorMap();
+         cm.addColor(0.0,Color.yellow);
+         cm.addColor(1.0,Color.red);
+         return cm;
+  }
+  
+  public static ModeleColorMap rockNRollColorMap()
+  {
+         ModeleColorMap cm = new ModeleColorMap();
+         cm.addColor(0.0,Color.red.brighter());
+         cm.addColor(1.0,Color.black);
+         cm.addColor(2.0,Color.green.brighter());
+         return cm;      
+  }
+
+  
+  public static ModeleColorMap defaultColorMap()
+  {
+         return energyColorMap();
+  }
+  
+  public static ModeleColorMap parseColorMap(String s)
+  {
+         String[] data = s.split("[;,]");
+         if (data.length==1)
+         {
+                 String name = data[0].toLowerCase();
+                 for (NamedColorMapTypes p : NamedColorMapTypes.values())
+                 {
+                         if (name.equals(p.getId().toLowerCase()))
+                         {
+                                 return p.getColorMap();
+                         }
+                 }
+                 return ModeleColorMap.defaultColorMap();
+         }
+         else
+         {
+                 ModeleColorMap cm = new ModeleColorMap();
+                 
+                 for(int i=0;i<data.length;i++)
+                 {
+                         String[] data2 = data[i].split(":");
+                         if (data2.length==2)
+                         {
+                                 try{
+                                         Double val = Double.parseDouble(data2[0]);
+                                         Color col = Color.decode(data2[1]);
+                                         cm.addColor(val, col);
+                                 }
+                                 catch(Exception e)
+                                 {  
+                                 }
+                         }
+                 }
+                 if (cm.getNumColors()>1)
+                         return cm;
+         }
+         return ModeleColorMap.defaultColorMap();
+  }
+  
+  public void setMinValue(double newMin)
+  {
+         rescale(newMin,getMaxValue());
+  }
+
+  public void setMaxValue(double newMax)
+  {
+         rescale(getMinValue(),newMax);
+  }
+
+  public void rescale(double newMin, double newMax)
+  {
+         double minBck = getMinValue();
+         double maxBck = getMaxValue();
+         double spanBck = maxBck-minBck;
+         if (newMax!=newMin)
+         {
+             newMax = Math.max(newMax,newMin+1.0);
+                 for (int i=0;i<_values.size();i++)
+                 {
+                         double valBck = _values.get(i);
+                         _values.set(i, newMin+(newMax-newMin)*(valBck-minBck)/(spanBck));
+                 }
+         }
+  }
+  
+  public ModeleColorMap clone()
+  {
+         ModeleColorMap cm = new ModeleColorMap(); 
+         cm._map = (Vector<Color>) _map.clone();
+         cm._values = (Vector<Double>)_values.clone();
+         return cm;
+  }
+  
+  public boolean equals(ModeleColorMap cm)
+  {
+         if ( getNumColors()!=cm.getNumColors())
+                 return false;
+         for (int i=0;i<getNumColors();i++)
+         {
+                 if ((!getColorAt(i).equals(cm.getColorAt(i))) || (!getValueAt(i).equals(cm.getValueAt(i))) )
+                                 return false;
+         }
+         return true;
+                 
+  }
+  
+  public String getParamEncoding()
+  {
+         String result = "";
+         Formatter f = new Formatter();
+         for(int i=0;i<getNumColors();i++)
+         {
+                 if (i!=0)
+                         f.format(",");
+                 f.format("%.2f:#%02X%02X%02X", _values.get(i),_map.get(i).getRed(),_map.get(i).getGreen(),_map.get(i).getBlue());
+         }
+         return f.out().toString();
+  }
+  
+
+  
+  public String toString()
+  {
+         return getParamEncoding();
+  }
+}
+
diff --git a/src2/fr/orsay/lri/varna/models/rna/ModeleStrand.java b/src2/fr/orsay/lri/varna/models/rna/ModeleStrand.java
new file mode 100644 (file)
index 0000000..1af1454
--- /dev/null
@@ -0,0 +1,79 @@
+package fr.orsay.lri.varna.models.rna;
+
+import java.util.ArrayList;
+
+public class ModeleStrand {
+       
+       private ArrayList<ModeleBase> _strand = new ArrayList<ModeleBase>();
+       private boolean hasBeenPlaced = false;
+       private boolean strandLeft = false;
+       private boolean strandRight = false;
+       private int levelPosition;
+       
+       public ModeleStrand(){
+               
+       }
+       
+       public void addBase(ModeleBase mb){
+               this._strand.add(mb);
+       }
+       
+       public void addBase(int index, ModeleBase mb){
+               this._strand.add(index, mb);
+       }
+       
+       public int sizeStrand() {
+               return this._strand.size();
+       }
+       
+       public ModeleBase getMB(int a) {        
+               return this._strand.get(a);     
+       }
+       
+       public ArrayList<ModeleBase> getArrayListMB() { 
+               return this._strand;    
+       }
+       
+       public int getLevelPosition(){
+               return this.levelPosition;
+       }
+       
+       public void setLevelPosition(int a){
+               this.levelPosition=a;
+       }
+       
+       public boolean getStrandRight(){
+               return this.strandRight;
+       }
+       
+       public void setStrandRight(boolean bool){
+               this.strandRight=bool;
+       }
+       
+       public boolean getStrandLeft(){
+               return this.strandLeft;
+       }
+       
+       public void setStrandLeft(boolean bool){
+               this.strandLeft=bool;
+       }
+       
+       public boolean hasBeenPlaced(){
+               return this.hasBeenPlaced;
+       }
+       
+       public void setHasBeenPlaced(boolean bool){
+               this.hasBeenPlaced =bool;
+       }
+       
+       public boolean existInStrand(int a){
+               int size =sizeStrand();
+               boolean exist=false; 
+               for (int i=0; i<size;i++){
+                       if(a==this.getMB(i).getIndex()){
+                               exist=true;
+                       }
+               }
+               return exist;
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/rna/RNA.java b/src2/fr/orsay/lri/varna/models/rna/RNA.java
new file mode 100644 (file)
index 0000000..4b530e0
--- /dev/null
@@ -0,0 +1,4164 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Color;
+import java.awt.Point;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.Serializable;
+import java.io.StreamTokenizer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Set;
+import java.util.Stack;
+import java.util.Vector;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.applications.templateEditor.Couple;
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.exceptions.ExceptionWritingForbidden;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAListener;
+import fr.orsay.lri.varna.interfaces.InterfaceVARNAObservable;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.VARNAConfig.BP_STYLE;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.export.PSExport;
+import fr.orsay.lri.varna.models.export.SVGExport;
+import fr.orsay.lri.varna.models.export.SecStrDrawingProducer;
+import fr.orsay.lri.varna.models.export.TikzExport;
+import fr.orsay.lri.varna.models.export.XFIGExport;
+import fr.orsay.lri.varna.models.naView.NAView;
+import fr.orsay.lri.varna.models.rna.ModeleBackboneElement.BackboneType;
+import fr.orsay.lri.varna.models.templates.DrawRNATemplateCurveMethod;
+import fr.orsay.lri.varna.models.templates.DrawRNATemplateMethod;
+import fr.orsay.lri.varna.models.templates.RNATemplate;
+import fr.orsay.lri.varna.models.templates.RNATemplateDrawingAlgorithmException;
+import fr.orsay.lri.varna.models.templates.RNATemplateMapping;
+import fr.orsay.lri.varna.utils.RNAMLParser;
+import fr.orsay.lri.varna.utils.XMLUtils;
+import fr.orsay.lri.varna.views.VueUI;
+
+/**
+ * The RNA model which contain the base list and the draw algorithm mode
+ * 
+ * @author darty
+ * 
+ */
+public class RNA extends InterfaceVARNAObservable implements Serializable {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 7541274455751497303L;
+
+       /**
+        * Selects the "Feynman diagram" drawing algorithm that places the bases on
+        * a circle and draws the base-pairings as chords of the circle graph.
+        */
+
+       public static final int DRAW_MODE_CIRCULAR = 1;
+       /**
+        * Selects the "tree drawing" algorithm. Draws each loop on a circle whose
+        * radius depends on the number of bases involved in the loop. As some
+        * helices can be overlapping in the result, basic interaction is provided
+        * so that the user can "disentangle" the drawing by spinning the helices
+        * around the axis defined by their multiloop (bulge or internal loop)
+        * origin. This is roughly the initial placement strategy of RNAViz.
+        * 
+        * @see <a href="http://rnaviz.sourceforge.net/">RNAViz</a>
+        */
+       public static final int DRAW_MODE_RADIATE = 2;
+
+       /**
+        * Selects the NAView algorithm.
+        */
+       public static final int DRAW_MODE_NAVIEW = 3;
+       /**
+        * Selects the linear algorithm.
+        */
+       public static final int DRAW_MODE_LINEAR = 4;
+
+       public static final int DRAW_MODE_VARNA_VIEW = 5;
+
+       /**
+        * Selects the RNAView algorithm.
+        */
+       public static final int DRAW_MODE_MOTIFVIEW = 6;
+
+       public static final int DRAW_MODE_TEMPLATE = 7;
+
+       public static final int DEFAULT_DRAW_MODE = DRAW_MODE_RADIATE;
+
+       public int BASE_RADIUS = 10;
+       public static final double LOOP_DISTANCE = 40.0; // distance between base
+                                                                                                               // pairs in an helix
+       public static final double BASE_PAIR_DISTANCE = 65.0; // distance between
+                                                                                                                       // the two bases of
+                                                                                                                       // a pair
+       public static final double MULTILOOP_DISTANCE = 35.0;
+       public static final double VIRTUAL_LOOP_RADIUS = 40.0;
+
+       public double CHEM_PROB_DIST = 14;
+       public double CHEM_PROB_BASE_LENGTH = 30;
+       public double CHEM_PROB_ARROW_HEIGHT = 10;
+       public double CHEM_PROB_ARROW_WIDTH = 5;
+       public double CHEM_PROB_TRIANGLE_WIDTH = 2.5;
+       public double CHEM_PROB_PIN_SEMIDIAG = 6;
+       public double CHEM_PROB_DOT_RADIUS = 6.;
+       public static double CHEM_PROB_ARROW_THICKNESS = 2.0;
+
+       public static ArrayList<String> NormalBases = new ArrayList<String>();
+       {
+               NormalBases.add("a");
+               NormalBases.add("c");
+               NormalBases.add("g");
+               NormalBases.add("u");
+               NormalBases.add("t");
+       }
+
+       public GeneralPath _debugShape = null;
+
+       /**
+        * The draw algorithm mode
+        */
+       private int _drawMode = DRAW_MODE_RADIATE;
+       private boolean _drawn = false;
+       private String _name = "";
+       private String _id = "";
+       public double _bpHeightIncrement = VARNAConfig.DEFAULT_BP_INCREMENT;
+       /**
+        * the base list
+        */
+       private ArrayList<ModeleBase> _listeBases;
+       /**
+        * the strand list
+        */
+       StructureTemp _listStrands = new StructureTemp();
+       /**
+        * Additional bonds and info can be specified here.
+        */
+       private ArrayList<ModeleBP> _structureAux = new ArrayList<ModeleBP>();
+       private ArrayList<TextAnnotation> _listeAnnotations = new ArrayList<TextAnnotation>();
+       private ArrayList<HighlightRegionAnnotation> _listeRegionHighlights = new ArrayList<HighlightRegionAnnotation>();
+       private ArrayList<ChemProbAnnotation> _chemProbAnnotations = new ArrayList<ChemProbAnnotation>();
+       private ModeleBackbone _backbone = new ModeleBackbone();
+
+       public static String XML_ELEMENT_NAME = "RNA";
+       public static String XML_VAR_BASE_SPACING_NAME = "spacing";
+       public static String XML_VAR_DRAWN_NAME = "drawn";
+       public static String XML_VAR_NAME_NAME = "name";
+       public static String XML_VAR_DRAWN_MODE_NAME = "mode";
+       public static String XML_VAR_ID_NAME = "id";
+       public static String XML_VAR_BP_HEIGHT_NAME = "delta";
+       public static String XML_VAR_BASES_NAME = "bases";
+       public static String XML_VAR_BASEPAIRS_NAME = "BPs";
+       public static String XML_VAR_ANNOTATIONS_NAME = "annotations";
+       public static String XML_VAR_BACKBONE_NAME = "backbone";
+
+       public void toXML(TransformerHandler hd) throws SAXException {
+               AttributesImpl atts = new AttributesImpl();
+               atts.addAttribute("", "", XML_VAR_DRAWN_NAME, "CDATA", "" + _drawn);
+               atts.addAttribute("", "", XML_VAR_DRAWN_MODE_NAME, "CDATA", ""
+                               + _drawMode);
+               atts.addAttribute("", "", XML_VAR_ID_NAME, "CDATA", "" + _id);
+               atts.addAttribute("", "", XML_VAR_BP_HEIGHT_NAME, "CDATA", ""
+                               + _bpHeightIncrement);
+               hd.startElement("", "", XML_ELEMENT_NAME, atts);
+
+               atts.clear();
+               hd.startElement("", "", XML_VAR_NAME_NAME, atts);
+               XMLUtils.exportCDATAString(hd, "" + _name);
+               hd.endElement("", "", XML_VAR_NAME_NAME);
+
+               atts.clear();
+               hd.startElement("", "", XML_VAR_BASES_NAME, atts);
+               for (ModeleBase mb : _listeBases) {
+                       mb.toXML(hd);
+               }
+               hd.endElement("", "", XML_VAR_BASES_NAME);
+               atts.clear();
+
+               hd.startElement("", "", XML_VAR_BASEPAIRS_NAME, atts);
+               for (ModeleBP mbp : getSecStrBPs()) {
+                       mbp.toXML(hd, true);
+               }
+               for (ModeleBP mbp : _structureAux) {
+                       mbp.toXML(hd, false);
+               }
+               hd.endElement("", "", XML_VAR_BASEPAIRS_NAME);
+               atts.clear();
+
+               getBackbone().toXML(hd);
+               atts.clear();
+
+               hd.startElement("", "", XML_VAR_ANNOTATIONS_NAME, atts);
+               for (TextAnnotation ta : _listeAnnotations) {
+                       ta.toXML(hd);
+               }
+               for (HighlightRegionAnnotation hra : _listeRegionHighlights) {
+                       hra.toXML(hd);
+               }
+               for (ChemProbAnnotation cpa : _chemProbAnnotations) {
+                       cpa.toXML(hd);
+               }
+               hd.endElement("", "", XML_VAR_ANNOTATIONS_NAME);
+               hd.endElement("", "", XML_ELEMENT_NAME);
+       }
+
+       public ModeleBackbone getBackbone() {
+               return _backbone;
+       }
+
+       public void setBackbone(ModeleBackbone b) {
+               _backbone = b;
+       }
+
+       transient private ArrayList<InterfaceVARNAListener> _listeVARNAListener = new ArrayList<InterfaceVARNAListener>();
+
+       public RNA() {
+               this("");
+       }
+
+       public RNA(String name) {
+               _name = name;
+               _listeBases = new ArrayList<ModeleBase>();
+               _drawn = false;
+               init();
+       }
+
+       public String toString() {
+               if (_name.equals("")) {
+                       return getStructDBN();
+               } else {
+                       return _name;
+               }
+       }
+
+       public RNA(RNA r) {
+               _drawMode = r._drawMode;
+               _listeBases.addAll(r._listeBases);
+               _listeVARNAListener = (ArrayList<InterfaceVARNAListener>) r._listeVARNAListener;
+               _drawn = r._drawn;
+               init();
+       }
+
+       public void init() {
+       }
+
+       public void saveRNADBN(String path, String title)
+                       throws ExceptionWritingForbidden {
+               try {
+                       FileWriter out = new FileWriter(path);
+                       if (!title.equals("")) {
+                               out.write("> " + title + "\n");
+                       }
+                       out.write(getListeBasesToString());
+                       out.write('\n');
+                       String str = "";
+                       for (int i = 0; i < _listeBases.size(); i++) {
+                               if (_listeBases.get(i).getElementStructure() == -1) {
+                                       str += '.';
+                               } else {
+                                       if (_listeBases.get(i).getElementStructure() > i) {
+                                               str += '(';
+                                       } else {
+                                               str += ')';
+                                       }
+                               }
+                       }
+                       out.write(str);
+                       out.write('\n');
+                       out.close();
+               } catch (IOException e) {
+                       throw new ExceptionWritingForbidden(e.getMessage());
+               }
+       }
+
+       public Color getBaseInnerColor(int i, VARNAConfig conf) {
+               Color result = _listeBases.get(i).getStyleBase().getBaseInnerColor();
+               String res = _listeBases.get(i).getContent();
+               if (conf._drawColorMap) {
+                       result = conf._cm.getColorForValue(_listeBases.get(i).getValue());
+               } else if ((conf._colorDashBases && (res.contains("-")))) {
+                       result = conf._dashBasesColor;
+               } else if ((conf._colorSpecialBases && !NormalBases.contains(res
+                               .toLowerCase()))) {
+                       result = conf._specialBasesColor;
+               }
+               return result;
+       }
+
+       public Color getBaseOuterColor(int i, VARNAConfig conf) {
+               Color result = _listeBases.get(i).getStyleBase()
+                               .getBaseOutlineColor();
+               return result;
+       }
+
+       private static double correctComponent(double c)
+       {
+           c = c / 255.0;
+           if (c <= 0.03928) 
+               c = c/12.92;
+           else 
+               c = Math.pow(((c+0.055)/1.055) , 2.4);
+           return c;
+       }
+       public static double getLuminance(Color c)
+       {
+               return 0.2126 * correctComponent(c.getRed()) + 0.7152 * correctComponent(c.getGreen()) + 0.0722 * correctComponent(c.getBlue());
+       }
+       
+       public static boolean whiteLabelPreferrable(Color c)
+       {
+               if (getLuminance(c) > 0.32)
+                       return false;
+               return true;
+       }
+       
+
+       
+       public Color getBaseNameColor(int i, VARNAConfig conf) {
+               Color result = _listeBases.get(i).getStyleBase().getBaseNameColor();
+               if ( RNA.whiteLabelPreferrable(getBaseInnerColor(i, conf)))
+               {
+                       result=Color.white;
+               }
+
+               return result;
+       }
+
+       public Color getBasePairColor(ModeleBP bp, VARNAConfig conf) {
+               Color bondColor = conf._bondColor;
+               if (conf._useBaseColorsForBPs) {
+                       bondColor = _listeBases.get(bp.getPartner5().getIndex())
+                                       .getStyleBase().getBaseInnerColor();
+               }
+               if (bp != null) {
+                       bondColor = bp.getStyle().getColor(bondColor);
+               }
+               return bondColor;
+       }
+
+       public double getBasePairThickness(ModeleBP bp, VARNAConfig conf) {
+               double thickness = bp.getStyle().getThickness(conf._bpThickness);
+               return thickness;
+       }
+
+       private void drawSymbol(SecStrDrawingProducer out, double posx,
+                       double posy, double normx, double normy, double radius,
+                       boolean isCIS, ModeleBP.Edge e, double thickness) {
+               Color bck = out.getCurrentColor();
+               switch (e) {
+               case WC:
+                       if (isCIS) {
+                               out.fillCircle(posx, posy, (radius / 2.0), thickness, bck);
+                       } else {
+                               out.fillCircle(posx, posy, (radius / 2.0), thickness,
+                                               Color.white);
+                               out.setColor(bck);
+                               out.drawCircle(posx, posy, (radius / 2.0), thickness);
+                       }
+                       break;
+               case HOOGSTEEN: {
+                       double xtab[] = new double[4];
+                       double ytab[] = new double[4];
+                       xtab[0] = posx - radius * normx / 2.0 - radius * normy / 2.0;
+                       ytab[0] = posy - radius * normy / 2.0 + radius * normx / 2.0;
+                       xtab[1] = posx + radius * normx / 2.0 - radius * normy / 2.0;
+                       ytab[1] = posy + radius * normy / 2.0 + radius * normx / 2.0;
+                       xtab[2] = posx + radius * normx / 2.0 + radius * normy / 2.0;
+                       ytab[2] = posy + radius * normy / 2.0 - radius * normx / 2.0;
+                       xtab[3] = posx - radius * normx / 2.0 + radius * normy / 2.0;
+                       ytab[3] = posy - radius * normy / 2.0 - radius * normx / 2.0;
+                       if (isCIS) {
+                               out.fillPolygon(xtab, ytab, bck);
+                       } else {
+                               out.fillPolygon(xtab, ytab, Color.white);
+                               out.setColor(bck);
+                               out.drawPolygon(xtab, ytab, thickness);
+                       }
+               }
+                       break;
+               case SUGAR: {
+                       double ix = radius * normx / 2.0;
+                       double iy = radius * normy / 2.0;
+                       double jx = radius * normy / 2.0;
+                       double jy = -radius * normx / 2.0;
+                       double xtab[] = new double[3];
+                       double ytab[] = new double[3];
+                       xtab[0] = posx - ix + jx;
+                       ytab[0] = posy - iy + jy;
+                       xtab[1] = posx + ix + jx;
+                       ytab[1] = posy + iy + jy;
+                       xtab[2] = posx - jx;
+                       ytab[2] = posy - jy;
+
+                       if (isCIS) {
+                               out.fillPolygon(xtab, ytab, bck);
+                       } else {
+                               out.fillPolygon(xtab, ytab, Color.white);
+                               out.setColor(bck);
+                               out.drawPolygon(xtab, ytab, thickness);
+                       }
+               }
+                       break;
+               }
+               out.setColor(bck);
+       }
+
+       private void drawBasePairArc(SecStrDrawingProducer out, int i, int j,
+                       Point2D.Double orig, Point2D.Double dest, ModeleBP style,
+                       VARNAConfig conf) {
+               double coef;
+               double distance;
+               Point2D.Double center = new Point2D.Double((orig.x + dest.x)/2., (orig.y + dest.y)/2. + BASE_RADIUS); 
+               if (j - i == 1)
+                       coef = _bpHeightIncrement * 2;
+               else
+                       coef = _bpHeightIncrement * 1;
+               distance = (int) Math.round(dest.x - orig.x);
+               if (conf._mainBPStyle != BP_STYLE.LW) {
+                       out.drawArc(center, distance, distance * coef, 180, 0);
+               } else {
+                       double thickness = getBasePairThickness(style, conf);
+                       double radiusCircle = ((BASE_PAIR_DISTANCE - BASE_RADIUS) / 5.0);
+
+                       if (style.isCanonical()) {
+                               if (style.isCanonicalGC()) {
+                                       if ((orig.x != dest.x) || (orig.y != dest.y)) {
+                                               out.drawArc(center, distance - BASE_RADIUS / 2.,
+                                                               distance * coef - BASE_RADIUS / 2, 180, 0);
+                                               out.drawArc(center, distance + BASE_RADIUS / 2.,
+                                                               distance * coef + BASE_RADIUS / 2, 180, 0);
+                                       }
+                               } else if (!style.isWobbleUG()) {
+                                       out.drawArc(center, distance, distance * coef, 180, 0);
+                                       drawSymbol(out, center.x, center.y + distance * coef / 2., 180., 0,
+                                                       radiusCircle, style.isCIS(),
+                                                       style.getEdgePartner5(), thickness);
+                               } else {
+                                       out.drawArc(orig, distance, distance * coef, 180, 0);
+                               }
+                       } else {
+                               ModeleBP.Edge p1 = style.getEdgePartner5();
+                               ModeleBP.Edge p2 = style.getEdgePartner3();
+                               out.drawArc(center, distance, distance * coef, 180, 0);
+                               if (p1 == p2) {
+                                       drawSymbol(out, center.x, center.y + distance * coef / 2., 1., 0,
+                                                       radiusCircle, style.isCIS(),
+                                                       style.getEdgePartner5(), thickness);
+                               } else {
+                                       drawSymbol(out, center.x - BASE_RADIUS,
+                                                       center.y + distance * coef / 2., 1., 0, radiusCircle,
+                                                       style.isCIS(), p1, thickness);
+                                       drawSymbol(out, center.x + BASE_RADIUS,
+                                                       center.y + distance * coef / 2., 1., 0, radiusCircle,
+                                                       style.isCIS(), p2, thickness);
+                               }
+                       }
+               }
+       }
+
+       private void drawBasePair(SecStrDrawingProducer out, Point2D.Double orig,
+                       Point2D.Double dest, ModeleBP style, VARNAConfig conf) {
+               double dx = dest.x - orig.x;
+               double dy = dest.y - orig.y;
+               double dist = Math.sqrt((dest.x - orig.x) * (dest.x - orig.x)
+                               + (dest.y - orig.y) * (dest.y - orig.y));
+               dx /= dist;
+               dy /= dist;
+               double nx = -dy;
+               double ny = dx;
+               orig = new Point2D.Double(orig.x + BASE_RADIUS * dx, orig.y
+                               + BASE_RADIUS * dy);
+               dest = new Point2D.Double(dest.x - BASE_RADIUS * dx, dest.y
+                               - BASE_RADIUS * dy);
+               if (conf._mainBPStyle == VARNAConfig.BP_STYLE.LW) {
+                       double thickness = getBasePairThickness(style, conf);
+                       double radiusCircle = ((BASE_PAIR_DISTANCE - BASE_RADIUS) / 5.0);
+
+                       if (style.isCanonical()) {
+                               if (style.isCanonicalGC()) {
+                                       if ((orig.x != dest.x) || (orig.y != dest.y)) {
+                                               nx *= BASE_RADIUS / 4.0;
+                                               ny *= BASE_RADIUS / 4.0;
+                                               out.drawLine((orig.x + nx), (orig.y + ny),
+                                                               (dest.x + nx), (dest.y + ny), conf._bpThickness);
+                                               out.drawLine((orig.x - nx), (orig.y - ny),
+                                                               (dest.x - nx), (dest.y - ny), conf._bpThickness);
+                                       }
+                               } else if (style.isCanonicalAU()) {
+                                       out.drawLine(orig.x, orig.y, dest.x, dest.y,
+                                                       conf._bpThickness);
+                               } else if (style.isWobbleUG()) {
+                                       double cx = (dest.x + orig.x) / 2.0;
+                                       double cy = (dest.y + orig.y) / 2.0;
+                                       out.drawLine(orig.x, orig.y, dest.x, dest.y,
+                                                       conf._bpThickness);
+                                       drawSymbol(out, cx, cy, nx, ny, radiusCircle, false,
+                                                       ModeleBP.Edge.WC, thickness);
+                               }
+
+                               else {
+                                       double cx = (dest.x + orig.x) / 2.0;
+                                       double cy = (dest.y + orig.y) / 2.0;
+                                       out.drawLine(orig.x, orig.y, dest.x, dest.y,
+                                                       conf._bpThickness);
+                                       drawSymbol(out, cx, cy, nx, ny, radiusCircle,
+                                                       style.isCIS(), style.getEdgePartner5(), thickness);
+                               }
+                       } else {
+                               ModeleBP.Edge p1 = style.getEdgePartner5();
+                               ModeleBP.Edge p2 = style.getEdgePartner3();
+                               double cx = (dest.x + orig.x) / 2.0;
+                               double cy = (dest.y + orig.y) / 2.0;
+                               out.drawLine(orig.x, orig.y, dest.x, dest.y, conf._bpThickness);
+                               if (p1 == p2) {
+                                       drawSymbol(out, cx, cy, nx, ny, radiusCircle,
+                                                       style.isCIS(), p1, thickness);
+                               } else {
+                                       double vdx = (dest.x - orig.x);
+                                       double vdy = (dest.y - orig.y);
+                                       vdx /= 6.0;
+                                       vdy /= 6.0;
+                                       drawSymbol(out, cx + vdx, cy + vdy, nx, ny, radiusCircle,
+                                                       style.isCIS(), p2, thickness);
+                                       drawSymbol(out, cx - vdx, cy - vdy, nx, ny, radiusCircle,
+                                                       style.isCIS(), p1, thickness);
+                               }
+                       }
+               } else if (conf._mainBPStyle == VARNAConfig.BP_STYLE.RNAVIZ) {
+                       double xcenter = (orig.x + dest.x) / 2.0;
+                       double ycenter = (orig.y + dest.y) / 2.0;
+                       out.fillCircle(xcenter, ycenter, 3.0 * conf._bpThickness,
+                                       conf._bpThickness, out.getCurrentColor());
+               } else if (conf._mainBPStyle == VARNAConfig.BP_STYLE.SIMPLE) {
+                       out.drawLine(orig.x, orig.y, dest.x, dest.y, conf._bpThickness);
+               }
+       }
+
+       private void drawColorMap(VARNAConfig _conf, SecStrDrawingProducer out) {
+               double v1 = _conf._cm.getMinValue();
+               double v2 = _conf._cm.getMaxValue();
+               int x, y;
+               double xSpaceAvail = 0;
+               double ySpaceAvail = 0;
+               double thickness = 1.0;
+               /*
+                * ySpaceAvail =
+                * Math.min((getHeight()-rnabbox.height*scaleFactor-getTitleHeight
+                * ())/2.0,scaleFactor*(_conf._colorMapHeight+VARNAConfig.
+                * DEFAULT_COLOR_MAP_FONT_SIZE)); if ((int)ySpaceAvail==0) { xSpaceAvail
+                * =
+                * Math.min((getWidth()-rnabbox.width*scaleFactor)/2,scaleFactor*(_conf
+                * ._colorMapWidth)+VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH); }
+                */
+               Rectangle2D.Double currentBBox = out.getBoundingBox();
+
+               double xBase = (currentBBox.getMaxX() - _conf._colorMapWidth - _conf._colorMapXOffset);
+               // double yBase = (minY - _conf._colorMapHeight +
+               // _conf._colorMapYOffset);
+               double yBase = (currentBBox.getMinY() - _conf._colorMapHeight - VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE);
+
+               for (int i = 0; i < _conf._colorMapWidth; i++) {
+                       double ratio = (((double) i) / ((double) _conf._colorMapWidth - 1));
+                       double val = v1 + (v2 - v1) * ratio;
+                       Color c = _conf._cm.getColorForValue(val);
+                       x = (int) (xBase + i);
+                       y = (int) yBase;
+                       out.fillRectangle(x, y, VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH,
+                                       _conf._colorMapHeight, c);
+               }
+               out.setColor(VARNAConfig.DEFAULT_COLOR_MAP_OUTLINE);
+               out.drawRectangle(xBase, yBase, (double) _conf._colorMapWidth
+                               + VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH - 1,
+                               _conf._colorMapHeight, thickness);
+
+               out.setColor(VARNAConfig.DEFAULT_COLOR_MAP_FONT_COLOR);
+               out.setFont(out.getCurrentFont(),
+                               VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE / 1.5);
+               out.drawText(xBase, yBase + _conf._colorMapHeight
+                               + VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE / 1.7,
+                               "" + _conf._cm.getMinValue());
+               out.drawText(xBase + VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH
+                               + _conf._colorMapWidth, yBase + _conf._colorMapHeight
+                               + VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE / 1.7,
+                               "" + _conf._cm.getMaxValue());
+               out.drawText(
+                               xBase
+                                               + (VARNAConfig.DEFAULT_COLOR_MAP_STRIPE_WIDTH + _conf._colorMapWidth)
+                                               / 2.0, yBase
+                                               - (VARNAConfig.DEFAULT_COLOR_MAP_FONT_SIZE / 1.7),
+                               _conf._colorMapCaption);
+
+       }
+
+       private void renderRegionHighlights(SecStrDrawingProducer out,
+                       Point2D.Double[] realCoords, Point2D.Double[] realCenters) {
+               for (HighlightRegionAnnotation r : _listeRegionHighlights) {
+                       GeneralPath s = r.getShape(realCoords, realCenters, 1.0);
+                       out.setColor(r.getFillColor());
+                       out.fillPolygon(s, r.getFillColor());
+                       out.setColor(r.getOutlineColor());
+                       out.drawPolygon(s, 1l);
+               }
+
+       }
+
+       private void saveRNA(String path, VARNAConfig conf, double scale,
+                       SecStrDrawingProducer out) throws ExceptionWritingForbidden {
+               out.setScale(scale);
+               // Computing bounding boxes
+               double EPSMargin = 40;
+               double minX = Double.MAX_VALUE;
+               double maxX = Double.MIN_VALUE;
+               double minY = Double.MAX_VALUE;
+               double maxY = Double.MIN_VALUE;
+
+               double x0, y0, x1, y1, xc, yc, xp, yp, dx, dy, norm;
+
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       minX = Math.min(minX, (_listeBases.get(i).getCoords().getX()
+                                       - BASE_RADIUS - EPSMargin));
+                       minY = Math.min(minY, -(_listeBases.get(i).getCoords().getY()
+                                       - BASE_RADIUS - EPSMargin));
+                       maxX = Math.max(maxX, (_listeBases.get(i).getCoords().getX()
+                                       + BASE_RADIUS + EPSMargin));
+                       maxY = Math.max(maxY, -(_listeBases.get(i).getCoords().getY()
+                                       + BASE_RADIUS + EPSMargin));
+               }
+
+               // Rescaling everything
+               Point2D.Double[] coords = new Point2D.Double[_listeBases.size()];
+               Point2D.Double[] centers = new Point2D.Double[_listeBases.size()];
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       xp = (_listeBases.get(i).getCoords().getX() - minX);
+                       yp = -(_listeBases.get(i).getCoords().getY() - minY);
+                       coords[i] = new Point2D.Double(xp, yp);
+
+                       Point2D.Double centerBck = getCenter(i);
+                       if (get_drawMode() == RNA.DRAW_MODE_NAVIEW
+                                       || get_drawMode() == RNA.DRAW_MODE_RADIATE) {
+                               if ((_listeBases.get(i).getElementStructure() != -1)
+                                               && i < _listeBases.size() - 1 && i > 1) {
+                                       ModeleBase b1 = get_listeBases().get(i - 1);
+                                       ModeleBase b2 = get_listeBases().get(i + 1);
+                                       int j1 = b1.getElementStructure();
+                                       int j2 = b2.getElementStructure();
+                                       if ((j1 == -1) ^ (j2 == -1)) {
+                                               // alors la position du nombre associé doit etre
+                                               // décalé
+                                               Point2D.Double a1 = b1.getCoords();
+                                               Point2D.Double a2 = b2.getCoords();
+                                               Point2D.Double c1 = b1.getCenter();
+                                               Point2D.Double c2 = b2.getCenter();
+
+                                               centerBck.x = _listeBases.get(i).getCoords().x
+                                                               + (c1.x - a1.x) / c1.distance(a1)
+                                                               + (c2.x - a2.x) / c2.distance(a2);
+                                               centerBck.y = _listeBases.get(i).getCoords().y
+                                                               + (c1.y - a1.y) / c1.distance(a1)
+                                                               + (c2.y - a2.y) / c2.distance(a2);
+                                       }
+                               }
+                       }
+                       xc = (centerBck.getX() - minX);
+                       yc = -(centerBck.getY() - minY);
+                       centers[i] = new Point2D.Double(xc, yc);
+               }
+
+               // Drawing background
+               if (conf._drawBackground)
+                       out.setBackgroundColor(conf._backgroundColor);
+
+               // Drawing region highlights
+               renderRegionHighlights(out, coords, centers);
+
+               // Drawing backbone
+               if (conf._drawBackbone)
+               {
+                       for (int i = 1; i < _listeBases.size(); i++) {
+                               Point2D.Double p1 = coords[i - 1];
+                               Point2D.Double p2 = coords[i];
+                               x0 = p1.x;
+                               y0 = p1.y;
+                               x1 = p2.x;
+                               y1 = p2.y;
+                               Point2D.Double vn = new Point2D.Double();
+                               double dist = p1.distance(p2);
+                               int a = _listeBases.get(i - 1).getElementStructure();
+                               int b = _listeBases.get(i).getElementStructure();
+                               BackboneType bt = _backbone.getTypeBefore(i);
+                               boolean consecutivePair = (a == i) && (b == i - 1);
+       
+                               if (dist > 0) {
+                                       if (bt != BackboneType.DISCONTINUOUS_TYPE) {
+                                               Color c = _backbone.getColorBefore(i, conf._backboneColor);
+                                               if (bt == BackboneType.MISSING_PART_TYPE) {
+                                                       c.brighter();
+                                               }
+                                               out.setColor(c);
+       
+                                               vn.x = (x1 - x0) / dist;
+                                               vn.y = (y1 - y0) / dist;
+                                               if (consecutivePair
+                                                               &&(getDrawMode() != RNA.DRAW_MODE_LINEAR)
+                                                               && (getDrawMode() != RNA.DRAW_MODE_CIRCULAR)) {
+                                                       int dir = 0;
+                                                       if (i + 1 < coords.length) {
+                                                               dir = (testDirectionality(i - 1, i, i + 1) ? 1 : -1);
+                                                       } else if (i - 2 >= 0) {
+                                                               dir = (testDirectionality(i - 2, i - 1, i) ? 1 : -1);
+                                                       }
+                                                       Point2D.Double centerSeg = new Point2D.Double(
+                                                                       (p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0);
+                                                       double centerDist = RNA.VIRTUAL_LOOP_RADIUS * scale;
+                                                       Point2D.Double centerLoop = new Point2D.Double(
+                                                                       centerSeg.x + centerDist * dir * vn.y,
+                                                                       centerSeg.y - centerDist * dir * vn.x);
+                                                       // Debug crosshair
+                                                       //out.drawLine(centerLoop.x - 5, centerLoop.y,
+                                                       //              centerLoop.x + 5, centerLoop.y, 2.0);
+                                                       //out.drawLine(centerLoop.x, centerLoop.y - 5,
+                                                       //              centerLoop.x, centerLoop.y + 5, 2.0);
+                                                       
+                                                       double radius = centerLoop.distance(p1);
+                                                       double a1 = 360.
+                                                                       * (Math.atan2(p1.y - centerLoop.y, p1.x - centerLoop.x))
+                                                                       / (2. * Math.PI);
+                                                       double a2 = 360.
+                                                                       * (Math.atan2(p2.y - centerLoop.y, p2.x - centerLoop.x))
+                                                                       / (2. * Math.PI);
+                                                       if (dir>0)
+                                                       {
+                                                               double tmp = a1;
+                                                               a1 = a2;
+                                                               a2 = tmp;
+                                                       }
+                                                       if (a1 < 0) {
+                                                               a1 += 360.;
+                                                       }
+                                                       if (a2 < 0) {
+                                                               a2 += 360.;
+                                                       }
+                                                       out.drawArc(centerLoop, 2. * radius, 2. * radius, a1,
+                                                                       a2);
+                                               } else {
+                                                       out.drawLine((x0 + BASE_RADIUS * vn.x),
+                                                                       (y0 + BASE_RADIUS * vn.y), (x1 - BASE_RADIUS
+                                                                                       * vn.x), (y1 - BASE_RADIUS * vn.y), 1.0);
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               // Drawing bonds
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       if (_listeBases.get(i).getElementStructure() > i) {
+                               ModeleBP style = _listeBases.get(i).getStyleBP();
+                               if (style.isCanonical() || conf._drawnNonCanonicalBP) {
+                                       Color bpcol = getBasePairColor(style, conf);
+                                       out.setColor(bpcol);
+
+                                       int j = _listeBases.get(i).getElementStructure();
+                                       x0 = coords[i].x;
+                                       y0 = coords[i].y;
+                                       x1 = coords[j].x;
+                                       y1 = coords[j].y;
+                                       dx = x1 - x0;
+                                       dy = y1 - y0;
+                                       norm = Math.sqrt(dx * dx + dy * dy);
+                                       dx /= norm;
+                                       dy /= norm;
+
+                                       if (_drawMode == DRAW_MODE_CIRCULAR
+                                                       || _drawMode == DRAW_MODE_RADIATE
+                                                       || _drawMode == DRAW_MODE_NAVIEW) {
+                                               drawBasePair(out, new Point2D.Double(x0, y0),
+                                                               new Point2D.Double(x1, y1), style, conf);
+                                       } else if (_drawMode == DRAW_MODE_LINEAR) {
+                                               drawBasePairArc(out, i, j, new Point2D.Double(x0, y0),
+                                                               new Point2D.Double(x1, y1), style, conf);
+                                       }
+                               }
+                       }
+               }
+
+               // Drawing additional bonds
+               if (conf._drawnNonPlanarBP) {
+                       for (int i = 0; i < _structureAux.size(); i++) {
+                               ModeleBP bp = _structureAux.get(i);
+                               out.setColor(getBasePairColor(bp, conf));
+
+                               int a = bp.getPartner5().getIndex();
+                               int b = bp.getPartner3().getIndex();
+
+                               if (bp.isCanonical() || conf._drawnNonCanonicalBP) {
+                                       x0 = coords[a].x;
+                                       y0 = coords[a].y;
+                                       x1 = coords[b].x;
+                                       y1 = coords[b].y;
+                                       dx = x1 - x0;
+                                       dy = y1 - y0;
+                                       norm = Math.sqrt(dx * dx + dy * dy);
+                                       dx /= norm;
+                                       dy /= norm;
+                                       if ((_drawMode == DRAW_MODE_CIRCULAR)
+                                                       || (_drawMode == DRAW_MODE_RADIATE)
+                                                       || _drawMode == DRAW_MODE_NAVIEW) {
+                                               drawBasePair(out, new Point2D.Double(x0, y0),
+                                                               new Point2D.Double(x1, y1), bp, conf);
+                                       } else if (_drawMode == DRAW_MODE_LINEAR) {
+                                               drawBasePairArc(out, a, b, new Point2D.Double(x0, y0),
+                                                               new Point2D.Double(x1, y1), bp, conf);
+                                       }
+                               }
+                       }
+               }
+
+               // Drawing Bases
+               double baseFontSize = (1.5 * BASE_RADIUS);
+               out.setFont(PSExport.FONT_HELVETICA_BOLD, baseFontSize);
+               
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       x0 = coords[i].x;
+                       y0 = coords[i].y;
+                       
+                       Color baseInnerColor = getBaseInnerColor(i, conf);
+                       Color baseOuterColor = getBaseOuterColor(i, conf);
+                       Color baseNameColor = getBaseNameColor(i, conf);
+                       if ( RNA.whiteLabelPreferrable(baseInnerColor))
+                       {
+                               baseNameColor=Color.white;
+                       }
+
+
+                       if (_listeBases.get(i) instanceof ModeleBasesComparison) {
+                               ModeleBasesComparison mb = (ModeleBasesComparison) _listeBases
+                                               .get(i);
+                               if (conf._fillBases) {
+                                       out.fillRectangle(x0 - 1.5 * BASE_RADIUS, y0 - BASE_RADIUS,
+                                                       3 * BASE_RADIUS, 2 * BASE_RADIUS,
+                                                       baseInnerColor);
+                               }
+                               if (conf._drawOutlineBases) {
+                                       out.setColor(baseOuterColor);
+                                       out.drawRectangle(x0 - 1.5 * BASE_RADIUS, y0 - BASE_RADIUS,
+                                                       3 * BASE_RADIUS, 2 * BASE_RADIUS, 1l);
+                                       out.drawLine(x0, y0 - BASE_RADIUS, x0, y0 + BASE_RADIUS, 1l);
+                               }
+                               
+                               out.setColor(baseNameColor);
+                               out.drawText(x0 - .75 * BASE_RADIUS, y0, "" + mb.getBase1());
+                               out.drawText(x0 + .75 * BASE_RADIUS, y0, "" + mb.getBase2());
+                       } else if (_listeBases.get(i) instanceof ModeleBaseNucleotide) {
+                               if (conf._fillBases) {
+                                       out.fillCircle(x0, y0, BASE_RADIUS, 1l,
+                                                       baseInnerColor);
+                               }
+                               if (conf._drawOutlineBases) {
+                                       out.setColor(baseOuterColor);
+                                       out.drawCircle(x0, y0, BASE_RADIUS, 1l);
+                               }
+                               out.setColor(baseNameColor);
+                               out.drawText(x0, y0, _listeBases.get(i).getContent());
+
+                       }
+               }
+
+               // Drawing base numbers
+               double numFontSize = (double) (1.5 * BASE_RADIUS);
+               out.setFont(PSExport.FONT_HELVETICA_BOLD, numFontSize);
+
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       int basenum = _listeBases.get(i).getBaseNumber();
+                       if (basenum == -1) {
+                               basenum = i + 1;
+                       }
+                       ModeleBase mb = _listeBases.get(i);
+                       if (this.isNumberDrawn(mb, conf._numPeriod)) {
+                               out.setColor(mb.getStyleBase()
+                                               .getBaseNumberColor());
+                               x0 = coords[i].x;
+                               y0 = coords[i].y;
+                               x1 = centers[i].x;
+                               y1 = centers[i].y;
+                               dx = x1 - x0;
+                               dy = y1 - y0;
+                               norm = Math.sqrt(dx * dx + dy * dy);
+                               dx /= norm;
+                               dy /= norm;
+                               Point2D.Double vn = VARNAPanel.computeExcentricUnitVector(i,coords,centers);
+                               
+                               out.drawLine((x0 + 1.5 * BASE_RADIUS * vn.x), (y0 + 1.5
+                                               * BASE_RADIUS * vn.y), (x0 + 2.5 * BASE_RADIUS * vn.x),
+                                               (y0 + 2.5 * BASE_RADIUS * vn.y), 1);
+                               out.drawText(
+                                               (x0 + (conf._distNumbers + 1.0) * BASE_RADIUS * vn.x),
+                                               (y0 + (conf._distNumbers + 1.0) * BASE_RADIUS * vn.y), mb.getLabel());
+                       }
+               }
+               renderAnnotations(out, minX, minY, conf);
+
+               // Draw color map
+               if (conf._drawColorMap) {
+                       drawColorMap(conf, out);
+               }
+
+               // Drawing Title
+               Rectangle2D.Double currentBBox = out.getBoundingBox();
+               double titleFontSize = (2.0 * conf._titleFont.getSize());
+               out.setColor(conf._titleColor);
+               out.setFont(PSExport.FONT_HELVETICA, titleFontSize);
+               double yTitle = currentBBox.y - titleFontSize / 2.0;
+               if (!getName().equals("")) {
+                       out.drawText((maxX - minX) / 2.0, yTitle, getName());
+               }
+
+               OutputStreamWriter fout;
+
+               try {
+                       fout = new OutputStreamWriter(new FileOutputStream(path), "UTF-8");
+
+                       fout.write(out.export());
+                       fout.close();
+               } catch (IOException e) {
+                       throw new ExceptionWritingForbidden(e.getMessage());
+               }
+       }
+
+       Point2D.Double buildCaptionPosition(ModeleBase mb, double heightEstimate,
+                       VARNAConfig conf) {
+               double radius = 2.0;
+               if (isNumberDrawn(mb, conf._numPeriod)) {
+                       radius += (conf._distNumbers + 1.0);
+               }
+               Point2D.Double center = mb.getCenter();
+               Point2D.Double p = mb.getCoords();
+               double realDistance = BASE_RADIUS * radius + heightEstimate;
+               return new Point2D.Double(center.getX() + (p.getX() - center.getX())
+                               * ((p.distance(center) + realDistance) / p.distance(center)),
+                               center.getY()
+                                               + (p.getY() - center.getY())
+                                               * ((p.distance(center) + realDistance) / p
+                                                               .distance(center)));
+       }
+
+       public double getBPHeightIncrement() {
+               return this._bpHeightIncrement;
+       }
+
+       public void setBPHeightIncrement(double d) {
+               _bpHeightIncrement = d;
+       }
+
+       private void drawChemProbAnnotation(SecStrDrawingProducer out,
+                       ChemProbAnnotation cpa, Point2D.Double anchor, double minX,
+                       double minY) {
+               out.setColor(cpa.getColor());
+               Point2D.Double v = cpa.getDirVector();
+               Point2D.Double vn = cpa.getNormalVector();
+               Point2D.Double base = new Point2D.Double((anchor.x + CHEM_PROB_DIST
+                               * v.x), (anchor.y + CHEM_PROB_DIST * v.y));
+               Point2D.Double edge = new Point2D.Double(
+                               (base.x + CHEM_PROB_BASE_LENGTH * cpa.getIntensity() * v.x),
+                               (base.y + CHEM_PROB_BASE_LENGTH * cpa.getIntensity() * v.y));
+               double thickness = CHEM_PROB_ARROW_THICKNESS * cpa.getIntensity();
+               switch (cpa.getType()) {
+               case ARROW: {
+                       Point2D.Double arrowTip1 = new Point2D.Double(
+                                       (base.x + cpa.getIntensity()
+                                                       * (CHEM_PROB_ARROW_WIDTH * vn.x + CHEM_PROB_ARROW_HEIGHT
+                                                                       * v.x)),
+                                       (base.y + cpa.getIntensity()
+                                                       * (CHEM_PROB_ARROW_WIDTH * vn.y + CHEM_PROB_ARROW_HEIGHT
+                                                                       * v.y)));
+                       Point2D.Double arrowTip2 = new Point2D.Double(
+                                       (base.x + cpa.getIntensity()
+                                                       * (-CHEM_PROB_ARROW_WIDTH * vn.x + CHEM_PROB_ARROW_HEIGHT
+                                                                       * v.x)),
+                                       (base.y + cpa.getIntensity()
+                                                       * (-CHEM_PROB_ARROW_WIDTH * vn.y + CHEM_PROB_ARROW_HEIGHT
+                                                                       * v.y)));
+                       out.drawLine(base.x - minX, minY - base.y, edge.x - minX, minY
+                                       - edge.y, thickness);
+                       out.drawLine(base.x - minX, minY - base.y, arrowTip1.x - minX, minY
+                                       - arrowTip1.y, thickness);
+                       out.drawLine(base.x - minX, minY - base.y, arrowTip2.x - minX, minY
+                                       - arrowTip2.y, thickness);
+               }
+                       break;
+               case PIN: {
+                       Point2D.Double side1 = new Point2D.Double(
+                                       (edge.x - cpa.getIntensity()
+                                                       * (CHEM_PROB_PIN_SEMIDIAG * v.x)),
+                                       (edge.y - cpa.getIntensity()
+                                                       * (CHEM_PROB_PIN_SEMIDIAG * v.y)));
+                       Point2D.Double side2 = new Point2D.Double(
+                                       (edge.x - cpa.getIntensity()
+                                                       * (CHEM_PROB_PIN_SEMIDIAG * vn.x)),
+                                       (edge.y - cpa.getIntensity()
+                                                       * (CHEM_PROB_PIN_SEMIDIAG * vn.y)));
+                       Point2D.Double side3 = new Point2D.Double(
+                                       (edge.x + cpa.getIntensity()
+                                                       * (CHEM_PROB_PIN_SEMIDIAG * v.x)),
+                                       (edge.y + cpa.getIntensity()
+                                                       * (CHEM_PROB_PIN_SEMIDIAG * v.y)));
+                       Point2D.Double side4 = new Point2D.Double(
+                                       (edge.x + cpa.getIntensity()
+                                                       * (CHEM_PROB_PIN_SEMIDIAG * vn.x)),
+                                       (edge.y + cpa.getIntensity()
+                                                       * (CHEM_PROB_PIN_SEMIDIAG * vn.y)));
+                       GeneralPath p2 = new GeneralPath();
+                       p2.moveTo((float) (side1.x - minX), (float) (minY - side1.y));
+                       p2.lineTo((float) (side2.x - minX), (float) (minY - side2.y));
+                       p2.lineTo((float) (side3.x - minX), (float) (minY - side3.y));
+                       p2.lineTo((float) (side4.x - minX), (float) (minY - side4.y));
+                       p2.closePath();
+                       out.fillPolygon(p2, cpa.getColor());
+                       out.drawLine(base.x - minX, minY - base.y, edge.x - minX, minY
+                                       - edge.y, thickness);
+               }
+                       break;
+               case TRIANGLE: {
+                       Point2D.Double arrowTip1 = new Point2D.Double(
+                                       (edge.x + cpa.getIntensity()
+                                                       * (CHEM_PROB_TRIANGLE_WIDTH * vn.x)),
+                                       (edge.y + cpa.getIntensity()
+                                                       * (CHEM_PROB_TRIANGLE_WIDTH * vn.y)));
+                       Point2D.Double arrowTip2 = new Point2D.Double(
+                                       (edge.x + cpa.getIntensity()
+                                                       * (-CHEM_PROB_TRIANGLE_WIDTH * vn.x)),
+                                       (edge.y + cpa.getIntensity()
+                                                       * (-CHEM_PROB_TRIANGLE_WIDTH * vn.y)));
+                       GeneralPath p2 = new GeneralPath();
+                       p2.moveTo((float) (base.x - minX), (float) (minY - base.y));
+                       p2.lineTo((float) (arrowTip1.x - minX),
+                                       (float) (minY - arrowTip1.y));
+                       p2.lineTo((float) (arrowTip2.x - minX),
+                                       (float) (minY - arrowTip2.y));
+                       p2.closePath();
+                       out.fillPolygon(p2, cpa.getColor());
+               }
+                       break;
+               case DOT: {
+                       Double radius = CHEM_PROB_DOT_RADIUS * cpa.getIntensity();
+                       Point2D.Double center = new Point2D.Double((base.x + radius * v.x)
+                                       - minX, minY - (base.y + radius * v.y));
+                       out.fillCircle(center.x, center.y, radius, thickness,
+                                       cpa.getColor());
+               }
+                       break;
+               }
+       }
+
+       private void renderAnnotations(SecStrDrawingProducer out, double minX,
+                       double minY, VARNAConfig conf) {
+               for (TextAnnotation textAnnotation : getAnnotations()) {
+                       out.setColor(textAnnotation.getColor());
+                       out.setFont(PSExport.FONT_HELVETICA_BOLD, 2.0 * textAnnotation
+                                       .getFont().getSize());
+                       Point2D.Double position = textAnnotation.getCenterPosition();
+                       if (textAnnotation.getType() == TextAnnotation.AnchorType.BASE) {
+                               ModeleBase mb = (ModeleBase) textAnnotation.getAncrage();
+                               double fontHeight = Math.ceil(textAnnotation.getFont()
+                                               .getSize());
+                               position = buildCaptionPosition(mb, fontHeight, conf);
+
+                       }
+                       out.drawText(position.x - minX, -(position.y - minY),
+                                       textAnnotation.getTexte());
+               }
+               for (ChemProbAnnotation cpa : getChemProbAnnotations()) {
+                       Point2D.Double anchor = cpa.getAnchorPosition();
+                       drawChemProbAnnotation(out, cpa, anchor, minX, minY);
+               }
+       }
+
+       public boolean isNumberDrawn(ModeleBase mb, int numPeriod) {
+               if (numPeriod <= 0)
+                       return false;
+               return ((mb.getIndex() == 0) || ((mb.getBaseNumber()) % numPeriod == 0) || (mb
+                               .getIndex() == get_listeBases().size() - 1));
+       }
+
+       public void saveRNAEPS(String path, VARNAConfig conf)
+                       throws ExceptionWritingForbidden {
+               PSExport out = new PSExport();
+               saveRNA(path, conf, 0.4, out);
+       }
+
+       public void saveRNAXFIG(String path, VARNAConfig conf)
+                       throws ExceptionWritingForbidden {
+               XFIGExport out = new XFIGExport();
+               saveRNA(path, conf, 20, out);
+       }
+
+       public void saveRNATIKZ(String path, VARNAConfig conf)
+                       throws ExceptionWritingForbidden {
+               TikzExport out = new TikzExport();
+               saveRNA(path, conf, 0.15, out);
+       }
+
+       public void saveRNASVG(String path, VARNAConfig conf)
+                       throws ExceptionWritingForbidden {
+               SVGExport out = new SVGExport();
+               saveRNA(path, conf, 0.5, out);
+       }
+
+       public Rectangle2D.Double getBBox() {
+               Rectangle2D.Double result = new Rectangle2D.Double(10, 10, 10, 10);
+               double minx, maxx, miny, maxy;
+               minx = Double.MAX_VALUE;
+               miny = Double.MAX_VALUE;
+               maxx = -Double.MAX_VALUE;
+               maxy = -Double.MAX_VALUE;
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       minx = Math.min(
+                                       _listeBases.get(i).getCoords().getX() - BASE_RADIUS, minx);
+                       miny = Math.min(
+                                       _listeBases.get(i).getCoords().getY() - BASE_RADIUS, miny);
+                       maxx = Math.max(
+                                       _listeBases.get(i).getCoords().getX() + BASE_RADIUS, maxx);
+                       maxy = Math.max(
+                                       _listeBases.get(i).getCoords().getY() + BASE_RADIUS, maxy);
+               }
+               result.x = minx;
+               result.y = miny;
+               result.width = Math.max(maxx - minx, 1);
+               result.height = Math.max(maxy - miny, 1);
+               if (_drawMode == RNA.DRAW_MODE_LINEAR) {
+                       double realHeight = _bpHeightIncrement * result.width / 2.0;
+                       result.height += realHeight;
+                       result.y -= realHeight;
+               }
+               return result;
+       }
+
+       public void setCoord(int index, Point2D.Double p) {
+               setCoord(index, p.x, p.y);
+       }
+
+       public void setCoord(int index, double x, double y) {
+               if (index < _listeBases.size()) {
+                       _listeBases.get(index).setCoords(new Point2D.Double(x, y));
+               }
+       }
+
+       public Point2D.Double getCoords(int i) {
+               if (i < _listeBases.size() && i >= 0) {
+                       return _listeBases.get(i).getCoords();
+               }
+               return new Point2D.Double();
+       }
+
+       public String getBaseContent(int i) {
+               if ((i >= 0) && (i < _listeBases.size())) {
+                       return _listeBases.get(i).getContent();
+               }
+               return "";
+       }
+
+       public int getBaseNumber(int i) {
+               if ((i >= 0) && (i < _listeBases.size())) {
+                       return _listeBases.get(i).getBaseNumber();
+               }
+               return -1;
+       }
+
+       public Point2D.Double getCenter(int i) {
+               if (i < _listeBases.size()) {
+                       return _listeBases.get(i).getCenter();
+               }
+
+               return new Point2D.Double();
+       }
+
+       public void setCenter(int i, double x, double y) {
+               setCenter(i, new Point2D.Double(x, y));
+       }
+
+       public void setCenter(int i, Point2D.Double p) {
+               if (i < _listeBases.size()) {
+                       _listeBases.get(i).setCenter(p);
+               }
+       }
+
+       public void drawRNACircle(VARNAConfig conf) {
+               _drawn = true;
+               _drawMode = DRAW_MODE_CIRCULAR;
+               int radius = (int) ((3 * (_listeBases.size() + 1) * BASE_RADIUS) / (2 * Math.PI));
+               double angle;
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       angle = -((((double) -(i + 1)) * 2.0 * Math.PI)
+                                       / ((double) (_listeBases.size() + 1)) - Math.PI / 2.0);
+                       _listeBases
+                                       .get(i)
+                                       .setCoords(
+                                                       new Point2D.Double(
+                                                                       (radius * Math.cos(angle) * conf._spaceBetweenBases),
+                                                                       (radius * Math.sin(angle) * conf._spaceBetweenBases)));
+                       _listeBases.get(i).setCenter(new Point2D.Double(0, 0));
+               }
+       }
+
+       public void drawRNAVARNAView(VARNAConfig conf) {
+               _drawn = true;
+               _drawMode = DRAW_MODE_VARNA_VIEW;
+               VARNASecDraw vs = new VARNASecDraw();
+               vs.drawRNA(1, this);
+       }
+
+       public void drawRNALine(VARNAConfig conf) {
+               _drawn = true;
+               _drawMode = DRAW_MODE_LINEAR;
+               for (int i = 0; i < get_listeBases().size(); i++) {
+                       get_listeBases().get(i).setCoords(
+                                       new Point2D.Double(i * conf._spaceBetweenBases * 20, 0));
+                       get_listeBases().get(i).setCenter(
+                                       new Point2D.Double(i * conf._spaceBetweenBases * 20, -10));
+               }
+       }
+
+       public RNATemplateMapping drawRNATemplate(RNATemplate template, boolean straightBulges,
+                       VARNAConfig conf) throws RNATemplateDrawingAlgorithmException {
+               return drawRNATemplate(template, conf,
+                               DrawRNATemplateMethod.getDefault(),
+                               DrawRNATemplateCurveMethod.getDefault(), straightBulges);
+       }
+
+       public RNATemplateMapping drawRNATemplate(RNATemplate template,
+                       VARNAConfig conf, DrawRNATemplateMethod helixLengthAdjustmentMethod, 
+                       boolean straightBulges)
+                       throws RNATemplateDrawingAlgorithmException {
+               return drawRNATemplate(template, conf, helixLengthAdjustmentMethod,
+                               DrawRNATemplateCurveMethod.getDefault(),straightBulges);
+       }
+
+       public RNATemplateMapping drawRNATemplate(RNATemplate template,
+                       VARNAConfig conf,
+                       DrawRNATemplateMethod helixLengthAdjustmentMethod,
+                       DrawRNATemplateCurveMethod curveMethod,
+                       boolean straightBulges)
+                       throws RNATemplateDrawingAlgorithmException {
+               _drawn = true;
+               _drawMode = DRAW_MODE_TEMPLATE;
+
+               DrawRNATemplate drawRNATemplate = new DrawRNATemplate(this);
+               drawRNATemplate.drawRNATemplate(template, conf,
+                               helixLengthAdjustmentMethod, curveMethod, 
+                               straightBulges);
+               return drawRNATemplate.getMapping();
+       }
+
+       private static double objFun(int n1, int n2, double r, double bpdist,
+                       double multidist) {
+               return (((double) n1) * 2.0 * Math.asin(((double) bpdist) / (2.0 * r))
+                               + ((double) n2) * 2.0
+                               * Math.asin(((double) multidist) / (2.0 * r)) - (2.0 * Math.PI));
+       }
+
+       public double determineRadius(int nbHel, int nbUnpaired, double startRadius) {
+               return determineRadius(nbHel, nbUnpaired, startRadius,
+                               BASE_PAIR_DISTANCE, MULTILOOP_DISTANCE);
+       }
+
+       public static double determineRadius(int nbHel, int nbUnpaired,
+                       double startRadius, double bpdist, double multidist) {
+               double xmin = bpdist / 2.0;
+               double xmax = 3.0 * multidist + 1;
+               double x = (xmin + xmax) / 2.0;
+               double y = 10000.0;
+               double ymin = -1000.0;
+               double ymax = 1000.0;
+               int numIt = 0;
+               double precision = 0.00001;
+               while ((Math.abs(y) > precision) && (numIt < 10000)) {
+                       x = (xmin + xmax) / 2.0;
+                       y = objFun(nbHel, nbUnpaired, x, bpdist, multidist);
+                       ymin = objFun(nbHel, nbUnpaired, xmax, bpdist, multidist);
+                       ymax = objFun(nbHel, nbUnpaired, xmin, bpdist, multidist);
+                       if (ymin > 0.0) {
+                               xmax = xmax + (xmax - xmin);
+                       } else if ((y <= 0.0) && (ymax > 0.0)) {
+                               xmax = x;
+                       } else if ((y >= 0.0) && (ymin < 0.0)) {
+                               xmin = x;
+                       } else if (ymax < 0.0) {
+                               xmin = Math.max(xmin - (x - xmin),
+                                               Math.max(bpdist / 2.0, multidist / 2.0));
+                               xmax = x;
+                       }
+                       numIt++;
+               }
+               return x;
+       }
+
+       public void drawRNA(VARNAConfig conf) throws ExceptionNAViewAlgorithm {
+               drawRNA(RNA.DEFAULT_DRAW_MODE, conf);
+       }
+
+       public void drawRNA(int mode, VARNAConfig conf)
+                       throws ExceptionNAViewAlgorithm {
+               _drawMode = mode;
+               switch (get_drawMode()) {
+               case RNA.DRAW_MODE_RADIATE:
+                       drawRNARadiate(conf);
+                       break;
+               case RNA.DRAW_MODE_LINEAR:
+                       drawRNALine(conf);
+                       break;
+               case RNA.DRAW_MODE_CIRCULAR:
+                       drawRNACircle(conf);
+                       break;
+               case RNA.DRAW_MODE_NAVIEW:
+                       drawRNANAView(conf);
+                       break;
+               case RNA.DRAW_MODE_VARNA_VIEW:
+                       drawRNAVARNAView(conf);
+                       break;
+               default:
+                       break;
+               }
+
+       }
+
+       public int getDrawMode() {
+               return _drawMode;
+       }
+       
+       public static double HYSTERESIS_EPSILON = .15;
+       public static final double[] HYSTERESIS_ATTRACTORS = {0.,Math.PI/4.,Math.PI/2.,3.*Math.PI/4.,Math.PI,5.*(Math.PI)/4.,3.*(Math.PI)/2,7.*(Math.PI)/4.};
+       
+       public static double normalizeAngle(double angle)
+       {
+               return normalizeAngle(angle,0.);
+       }
+       
+       public static double normalizeAngle(double angle, double fromVal)
+       {
+               double toVal = fromVal +2.*Math.PI;
+               double result = angle;
+               while(result<fromVal)
+               {
+                       result += 2.*Math.PI;
+               }
+               while(result >= toVal)
+               {
+                       result -= 2.*Math.PI;
+               }
+               return result;          
+       }
+       
+       public static double correctHysteresis(double angle)
+       {
+               double result = normalizeAngle(angle);
+               
+               for (int i=0;i<HYSTERESIS_ATTRACTORS.length;i++)
+               {
+                       double att = HYSTERESIS_ATTRACTORS[i];
+                       if (Math.abs(normalizeAngle(att-result,-Math.PI))<HYSTERESIS_EPSILON)
+                       {
+                               result = att;
+                       }
+               }
+               return result;
+       }
+       
+
+       
+       private void distributeUnpaired(
+                       double radius,
+                       double angle, 
+                       double pHel, 
+                       double base,
+                       Point2D.Double center,
+                       Vector<Integer> bases)
+       {
+                       double mydist = Math.abs(radius*(angle / (bases.size() + 1)));
+                       double addedRadius= 0.;
+                       Point2D.Double PA = new Point2D.Double(center.x + radius * Math.cos(base + pHel),
+                                       center.y + radius * Math.sin(base + pHel));
+                       Point2D.Double PB = new Point2D.Double(center.x + radius * Math.cos(base + pHel+angle),
+                                               center.y + radius * Math.sin(base + pHel+angle));
+                       double dist = PA.distance(PB);
+                       Point2D.Double VN = new Point2D.Double((PB.y-PA.y)/dist,(-PB.x+PA.x)/dist);
+                       if (mydist<2*BASE_RADIUS)
+                       {
+                               addedRadius=Math.min(1.0,(2*BASE_RADIUS-mydist)/4)*computeRadius(mydist, 2.29*(bases.size() + 1)*BASE_RADIUS-mydist);
+                       }
+                       
+                       
+                       ArrayList<Point2D.Double> pos = computeNewAngles(bases.size(),center,VN, angle,base + pHel,radius,addedRadius);
+                       for (int i = 0; i < bases.size(); i++) 
+                       {
+                               int k = bases.get(i);
+                               setCoord(k, pos.get(i));
+                       }                               
+               
+       }
+
+       private double computeRadius(double b, double pobj)
+       {
+               double a=b, aL=a, aU=Double.POSITIVE_INFINITY;
+               double h = (a-b)*(a-b)/((a+b)*(a+b));
+               double p = Math.PI*(a+b)*(1+h/4.+h*h/64.+h*h*h/256.+25.*h*h*h*h/16384.)/2.0;
+               double aold = a+1.;
+               while ((Math.abs(p-pobj)>10e-4)&&(aold!=a)){
+                       aold = a;
+                       if (p<pobj)
+                       {
+                               aL = a;
+                               if (aU==Double.POSITIVE_INFINITY)
+                               {a *= 2.;}
+                               else
+                               { a = (a+aU)/2.; }
+                       }
+                       else
+                       {
+                               aU = a;
+                               a = (a+aL)/2.0;
+                       }
+                       h = (a-b)*(a-b)/((a+b)*(a+b));
+                       p = (Math.PI*(a+b)*(1+h/4.+h*h/64.+h*h*h/256.+25.*h*h*h*h/16384.))/2.0;
+               }
+               return a;
+       }
+       
+       public static double computeAngle(Point2D.Double center, Point2D.Double p) {
+               double dist = center.distance(p);
+               double angle = Math.asin((p.y - center.y) / dist);
+               if (p.x - center.x < 0) {
+                       angle = Math.PI - angle;
+               }
+               return angle;
+       }
+       
+       private Point2D.Double rotatePoint(Point2D.Double center, Point2D.Double p,
+                       double angle) {
+               double dist = p.distance(center);
+               double oldAngle = Math.asin((p.y - center.y) / dist);
+
+               if (p.x - center.x < 0) {
+                       oldAngle = Math.PI - oldAngle;
+               }
+
+               double newX = (center.x + dist * Math.cos(oldAngle + angle));
+               double newY = (center.y + dist * Math.sin(oldAngle + angle));
+
+               return new Point2D.Double(newX, newY);
+       }
+
+
+       
+       private void rotateHelix(Point2D.Double center, int i, int j, double angle) {
+               for (int k = i; k <= j; k++) {
+                       Point2D.Double oldp = getCoords(k);
+                       Point2D.Double newp = rotatePoint(center, oldp, angle);
+                       setCoord(k, newp);
+                       if ((k != i) && (k != j)) {
+
+                               Point2D.Double oldc = get_listeBases().get(k)
+                                               .getCenter();
+                               Point2D.Double newc = rotatePoint(center, oldc, angle);
+                               setCenter(k,newc);
+                       }
+               }
+       }
+       
+
+
+       private void fixUnpairedPositions(boolean isDirect, 
+                       double angleRightPartner, 
+                       double angleLimitLeft, double angleLimitRight, double angleLeftPartner, 
+                       double radius, double base, Point2D.Double center,Vector<Integer> prevBases,Vector<Integer> nextBases)
+       {
+               if (isDirect) {
+                       double anglePrev = normalizeAngle(angleLimitLeft - angleRightPartner);
+                       double angleNext = normalizeAngle(angleLeftPartner - angleLimitRight);
+                       distributeUnpaired(radius,anglePrev, angleRightPartner, base,
+                                       center,prevBases);
+                       distributeUnpaired(radius,-angleNext, angleLeftPartner, base,
+                                       center,nextBases);
+               } else {
+                       double anglePrev = normalizeAngle(angleLeftPartner - angleLimitRight);
+                       double angleNext = normalizeAngle(angleLimitLeft - angleRightPartner);
+                       distributeUnpaired(radius,-anglePrev, angleLeftPartner, base,
+                                       center,prevBases);                      
+                       distributeUnpaired(radius,angleNext, angleRightPartner, base,
+                                       center,nextBases);
+               }
+       
+       }
+       
+       private static Point2D.Double getPoint(double angleLine, double angleBulge, Point2D.Double center,  
+                       Point2D.Double VN,double radius, double addedRadius, double dirBulge)
+       {
+               return new Point2D.Double(
+                               center.x + radius * Math.cos(angleLine)+
+                               dirBulge*addedRadius*Math.sin(angleBulge)*VN.x,
+                               center.y + radius * Math.sin(angleLine)+
+                               dirBulge*addedRadius*Math.sin(angleBulge)*VN.y);
+       }
+       
+
+       private ArrayList<Point2D.Double> computeNewAngles(int numPoints, Point2D.Double center,  
+                       Point2D.Double VN, double angle, double angleBase, double radius, double addedRadius)
+       {
+               ArrayList<Point2D.Double> result = new ArrayList<Point2D.Double>();
+               if (numPoints>0)
+               {
+               ArrayList<Double> factors = new ArrayList<Double>();
+               
+
+               Point2D.Double prevP = new Point2D.Double(
+                               center.x + radius * Math.cos(angleBase),
+                               center.y + radius * Math.sin(angleBase));
+               
+               
+               double fact = 0.;
+               
+               double angleBulge = 0.;
+               double dirBulge = (angle<0)?-1.:1.;
+               double dtarget =2.*BASE_RADIUS; 
+               
+               for (int i = 0; i < numPoints; i++) 
+               {
+                               double lbound = fact;
+                               double ubound = 1.0;
+                               double angleLine = angleBase + angle*fact;
+                               angleBulge = Math.PI*fact;
+                               Point2D.Double currP = getPoint(angleLine, angleBulge, center,VN,radius, addedRadius, dirBulge);
+
+                               int numIter = 0;
+                               while ((Math.abs(currP.distance(prevP)-dtarget)>0.01)&& (numIter<100))
+                               {
+                                       if (currP.distance(prevP)> dtarget)
+                                       {
+                                               ubound = fact;
+                                               fact = (fact+lbound)/2.0;
+                                       }
+                                       else
+                                       {
+                                               lbound = fact;
+                                               fact = (fact+ubound)/2.0;                                       
+                                       }                               
+                                       angleLine = angleBase + angle*fact;
+                                       angleBulge = Math.PI*fact;
+                                       currP = getPoint(angleLine, angleBulge, center,VN,radius, addedRadius, dirBulge);
+                                       numIter++;
+                               }
+                               factors.add(fact);
+                               prevP = currP;
+               }
+               
+               
+               double rescale = 1.0/(factors.get(factors.size()-1)+factors.get(0));
+
+               for(int j=0;j<factors.size();j++)
+               {
+                       factors.set(j,factors.get(j)*rescale);
+               }
+               
+                
+               if (addedRadius>0)
+               {
+                       prevP =  getPoint(angleBase, 0, center,VN,radius, addedRadius, dirBulge);
+                       double totDist = 0.0;
+                       for(int j=0;j<factors.size();j++)
+                       {
+                               double newfact = factors.get(j);
+                               double angleLine = angleBase + angle*newfact;
+                               angleBulge = Math.PI*newfact;
+                               Point2D.Double currP = getPoint(angleLine, angleBulge, center,VN,radius, addedRadius, dirBulge); 
+                               totDist += currP.distance(prevP);
+                               prevP = currP;
+                       }
+                       totDist += getPoint(angleBase+angle, Math.PI, center,VN,radius, addedRadius, dirBulge).distance(prevP);
+                       dtarget = totDist/(numPoints+1);
+                       fact = 0.0;
+                       factors=new ArrayList<Double>();
+                       prevP = new Point2D.Double(
+                                       center.x + radius * Math.cos(angleBase),
+                                       center.y + radius * Math.sin(angleBase));
+                       for (int i = 0; i < numPoints; i++) 
+                       {
+                                       double lbound = fact;
+                                       double ubound = 1.5;
+                                       double angleLine = angleBase + angle*fact;
+                                       angleBulge = Math.PI*fact;
+                                       Point2D.Double currP = getPoint(angleLine, angleBulge, center,VN,radius, addedRadius, dirBulge);
+
+                                       int numIter = 0;
+                                       while ((Math.abs(currP.distance(prevP)-dtarget)>0.01)&& (numIter<100))
+                                       {
+                                               if (currP.distance(prevP)> dtarget)
+                                               {
+                                                       ubound = fact;
+                                                       fact = (fact+lbound)/2.0;
+                                               }
+                                               else
+                                               {
+                                                       lbound = fact;
+                                                       fact = (fact+ubound)/2.0;                                       
+                                               }                               
+                                               angleLine = angleBase + angle*fact;
+                                               angleBulge = Math.PI*fact;
+                                               currP = getPoint(angleLine, angleBulge, center,VN,radius, addedRadius, dirBulge);
+                                               numIter++;
+                                       }
+                                       factors.add(fact);
+                                       prevP = currP;
+                       }
+                       rescale = 1.0/(factors.get(factors.size()-1)+factors.get(0));
+                               for(int j=0;j<factors.size();j++)
+                       {
+                               factors.set(j,factors.get(j)*rescale);
+                       }
+               }       
+
+               for(int j=0;j<factors.size();j++)
+               {
+                       double newfact = factors.get(j);
+                       double angleLine = angleBase + angle*newfact;
+                       angleBulge = Math.PI*newfact;
+                       result.add(getPoint(angleLine, angleBulge, center,VN,radius, addedRadius, dirBulge));                   
+               }
+               }       
+               return result;
+       }
+       
+       
+       
+       void drawLoop(int i, int j, double x, double y, double dirAngle,
+                       Point2D.Double[] coords, Point2D.Double[] centers, double[] angles, 
+                       boolean straightBulges) {
+               if (i > j) {
+                       return;
+               }
+
+               // BasePaired
+               if (_listeBases.get(i).getElementStructure() == j) {
+                       double normalAngle = Math.PI / 2.0;
+                       centers[i] = new Point2D.Double(x, y);
+                       centers[j] = new Point2D.Double(x, y);
+                       coords[i].x = (x + BASE_PAIR_DISTANCE
+                                       * Math.cos(dirAngle - normalAngle) / 2.0);
+                       coords[i].y = (y + BASE_PAIR_DISTANCE
+                                       * Math.sin(dirAngle - normalAngle) / 2.0);
+                       coords[j].x = (x + BASE_PAIR_DISTANCE
+                                       * Math.cos(dirAngle + normalAngle) / 2.0);
+                       coords[j].y = (y + BASE_PAIR_DISTANCE
+                                       * Math.sin(dirAngle + normalAngle) / 2.0);
+                       drawLoop(i + 1, j - 1, x + LOOP_DISTANCE * Math.cos(dirAngle), y
+                                       + LOOP_DISTANCE * Math.sin(dirAngle), dirAngle, coords,
+                                       centers, angles, straightBulges);
+               } else {
+                       int k = i;
+                       Vector<Integer> basesMultiLoop = new Vector<Integer>();
+                       Vector<Integer> helices = new Vector<Integer>();
+                       int l;
+                       while (k <= j) {
+                               l = _listeBases.get(k).getElementStructure();
+                               if (l > k) {
+                                       basesMultiLoop.add(new Integer(k));
+                                       basesMultiLoop.add(new Integer(l));
+                                       helices.add(new Integer(k));
+                                       k = l + 1;
+                               } else {
+                                       basesMultiLoop.add(new Integer(k));
+                                       k++;
+                               }
+                       }
+                       int mlSize = basesMultiLoop.size() + 2;
+                       int numHelices = helices.size() + 1;
+                       double totalLength = MULTILOOP_DISTANCE * (mlSize - numHelices)
+                                       + BASE_PAIR_DISTANCE * numHelices;
+                       double multiLoopRadius;
+                       double angleIncrementML;
+                       double angleIncrementBP;
+                       if (mlSize > 3) {
+                               multiLoopRadius = determineRadius(numHelices, mlSize
+                                               - numHelices, (totalLength) / (2.0 * Math.PI),
+                                               BASE_PAIR_DISTANCE, MULTILOOP_DISTANCE);
+                               angleIncrementML = -2.0
+                                               * Math.asin(((float) MULTILOOP_DISTANCE)
+                                                               / (2.0 * multiLoopRadius));
+                               angleIncrementBP = -2.0
+                                               * Math.asin(((float) BASE_PAIR_DISTANCE)
+                                                               / (2.0 * multiLoopRadius));
+                       } 
+                       else {
+                               multiLoopRadius = 35.0;
+                               angleIncrementBP = -2.0
+                                               * Math.asin(((float) BASE_PAIR_DISTANCE)
+                                                               / (2.0 * multiLoopRadius));
+                               angleIncrementML = (-2.0 * Math.PI - angleIncrementBP) / 2.0;
+                       }
+                       // System.out.println("MLr:"+multiLoopRadius+" iBP:"+angleIncrementBP+" iML:"+angleIncrementML);
+
+                       double centerDist = Math.sqrt(Math.max(Math.pow(multiLoopRadius, 2)
+                                       - Math.pow(BASE_PAIR_DISTANCE / 2.0, 2), 0.0))
+                                       - LOOP_DISTANCE;
+                       Point2D.Double mlCenter = new Point2D.Double(
+                                       (x + (centerDist * Math.cos(dirAngle))),
+                                       (y + (centerDist * Math.sin(dirAngle))));
+
+                       // Base directing angle for (multi|hairpin) loop, from the center's
+                       // perspective
+                       double baseAngle = dirAngle
+                                       // U-turn
+                                       + Math.PI
+                                       // Account for already drawn supporting base-pair
+                                       + 0.5 * angleIncrementBP
+                                       // Base cannot be paired twice, so next base is at
+                                       // "unpaired base distance"
+                                       + 1.0 * angleIncrementML;
+                       
+                       ArrayList<Integer> currUnpaired = new ArrayList<Integer>();
+                       Couple<Double,Double> currInterval = new Couple<Double,Double>(0.,baseAngle-1.0 * angleIncrementML);
+                       ArrayList<Couple<ArrayList<Integer>,Couple<Double,Double>>> intervals = new ArrayList<Couple<ArrayList<Integer>,Couple<Double,Double>>>();
+                       
+                       for (k = basesMultiLoop.size() - 1; k >= 0; k--) {
+                               l = basesMultiLoop.get(k).intValue();
+                               //System.out.println(l+" ");
+                               centers[l] = mlCenter;
+                               boolean isPaired = (_listeBases.get(l).getElementStructure() != -1);
+                               boolean isPaired3 = isPaired && (_listeBases.get(l).getElementStructure() < l);
+                               boolean isPaired5 = isPaired && !isPaired3;
+                               if (isPaired3) {
+                                       if ((numHelices == 2) && straightBulges)
+                                       {
+                                               baseAngle = dirAngle-angleIncrementBP/2.;
+                                       }
+                                       else
+                                       {
+                                               baseAngle = correctHysteresis(baseAngle+angleIncrementBP/2.)-angleIncrementBP/2.;
+                                       }
+                                       currInterval.first = baseAngle;
+                                       intervals.add(new Couple<ArrayList<Integer>,Couple<Double,Double>>(currUnpaired,currInterval));
+                                       currInterval = new Couple<Double,Double>(-1.,-1.);  
+                                       currUnpaired = new ArrayList<Integer>();
+                               }
+                               else if (isPaired5)
+                               {
+                                       currInterval.second = baseAngle;
+                               }
+                               else
+                               {
+                                       currUnpaired.add(l);
+                               }
+
+                               angles[l] = baseAngle;
+                               if (isPaired3)
+                               { 
+                                       baseAngle += angleIncrementBP;
+                               }
+                               else {
+                                       baseAngle += angleIncrementML;
+                               }
+                       }
+                       currInterval.first = dirAngle
+                                       - Math.PI
+                                       - 0.5 * angleIncrementBP;
+                       intervals.add(new Couple<ArrayList<Integer>,Couple<Double,Double>>(currUnpaired,currInterval));
+                       //System.out.println("Inc. ML:"+angleIncrementML+" BP:"+angleIncrementBP);
+                       
+                       for(Couple<ArrayList<Integer>,Couple<Double,Double>> inter: intervals)
+                       {
+                               //double mid = inter.second.second;
+                               double mina = inter.second.first;
+                               double maxa = normalizeAngle(inter.second.second,mina);
+                               //System.out.println(""+mina+" " +maxa);
+                               
+                               for (int n=0;n<inter.first.size();n++)
+                               {
+                                       double ratio = (1.+n)/(1.+inter.first.size());
+                                       int b = inter.first.get(n);
+                                       angles[b] = mina + (1.-ratio)*(maxa-mina);
+                               }
+                       }
+                       
+                       
+                       for (k = basesMultiLoop.size() - 1; k >= 0; k--) {
+                               l = basesMultiLoop.get(k).intValue();
+                               coords[l].x = mlCenter.x + multiLoopRadius
+                                               * Math.cos(angles[l]);
+                               coords[l].y = mlCenter.y + multiLoopRadius
+                                               * Math.sin(angles[l]);
+                       }       
+                       
+                       // System.out.println("n1:"+n1+" n2:"+n2);
+                       double newAngle;
+                       int m, n;
+                       for (k = 0; k < helices.size(); k++) {
+                               m = helices.get(k).intValue();
+                               n = _listeBases.get(m).getElementStructure();
+                               newAngle = (angles[m] + angles[n]) / 2.0;
+                               drawLoop(m + 1, n - 1, (LOOP_DISTANCE * Math.cos(newAngle))
+                                               + (coords[m].x + coords[n].x) / 2.0,
+                                               (LOOP_DISTANCE * Math.sin(newAngle))
+                                                               + (coords[m].y + coords[n].y) / 2.0, newAngle,
+                                               coords, centers, angles, straightBulges);
+                       }
+               }
+       }
+
+       private Vector<Integer> getPreviousUnpaired(Point h)
+       {
+               Vector<Integer> prevBases = new Vector<Integer>();
+               boolean over = false;
+               int i = h.y + 1;
+               while (!over) {
+                       if (i >=get_listeBases().size()) {
+                               over = true;
+                       } else {
+                               if (get_listeBases().get(i)
+                                               .getElementStructure() == -1) {
+                                       prevBases.add(new Integer(i));
+                               } else {
+                                       over = true;
+                               }
+                       }
+                       i++;
+               }
+               return prevBases;
+       }
+
+       private Vector<Integer> getNextUnpaired(Point h)
+       {
+               boolean over = false;
+               int i = h.x - 1;
+               Vector<Integer> nextBases = new Vector<Integer>();
+               while (!over) {
+                       if (i < 0) {
+                               over = true;
+                       } else {
+                               if (get_listeBases().get(i)
+                                               .getElementStructure() == -1) {
+                                       nextBases.add(new Integer(i));
+                               } else {
+                                       over = true;
+                               }
+                       }
+                       i--;
+               }
+               return nextBases;
+       }
+
+       
+       public void rotateEverything(double delta, double base, double pLimL, double pLimR, Point h, Point ml, Hashtable<Integer,Point2D.Double> backupPos)
+       {
+               boolean isDirect = testDirectionality(ml.x, ml.y, h.x);
+               Point2D.Double center = get_listeBases().get(h.x).getCenter();
+               for(int k=h.x;k<=h.y;k++)
+               { backupPos.put(k, getBaseAt(k).getCoords()); }
+               rotateHelix(center, h.x, h.y, delta);
+               
+               // Re-assigns unpaired atoms
+               Point2D.Double helixStart = getCoords(h.x);
+               Point2D.Double helixStop = getCoords(h.y);
+               double pHelR,pHelL;
+               if (isDirect) {
+                       pHelR = computeAngle(center, helixStop) - base;
+                       pHelL = computeAngle(center, helixStart) - base;
+               } else {
+                       pHelL = computeAngle(center, helixStop) - base;
+                       pHelR = computeAngle(center, helixStart) - base;
+               }
+
+               Vector<Integer> prevBases = getPreviousUnpaired(h);
+               Vector<Integer> nextBases = getNextUnpaired(h);
+               
+               double radius = center.distance(helixStart);
+
+               for (int j = 0; j < prevBases.size(); j++) 
+               {
+                       int k = prevBases.get(j);
+                       backupPos.put(k, getCoords(k));
+               }
+               for (int j = 0; j < nextBases.size(); j++) 
+               {
+                       int k = nextBases.get(j);
+                       backupPos.put(k, getCoords(k));
+               }
+               fixUnpairedPositions(isDirect, pHelR, pLimL, pLimR, pHelL, radius, base,center,prevBases,nextBases);            
+       }
+       
+       
+       
+       public void drawRNARadiate() {
+               drawRNARadiate(-1.0, VARNAConfig.DEFAULT_SPACE_BETWEEN_BASES, true, true);
+       }
+
+       public void drawRNARadiate(VARNAConfig conf) {
+               drawRNARadiate(-1.0, conf._spaceBetweenBases, conf._flatExteriorLoop, false);
+       }
+
+       public static final double FLAT_RECURSIVE_INCREMENT = 20.;
+       
+       public void drawRNARadiate(double dirAngle, double _spaceBetweenBases,
+                       boolean flatExteriorLoop, boolean straightBulges) {
+               _drawn = true;
+               straightBulges = true;
+               _drawMode = DRAW_MODE_RADIATE;
+               Point2D.Double[] coords = new Point2D.Double[_listeBases.size()];
+               Point2D.Double[] centers = new Point2D.Double[_listeBases.size()];
+               double[] angles = new double[_listeBases.size()];
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       coords[i] = new Point2D.Double(0, 0);
+                       centers[i] = new Point2D.Double(0, 0);
+               }
+               if (flatExteriorLoop) {
+                       dirAngle += 1.0 - Math.PI / 2.0;
+                       int i = 0;
+                       double x = 0.0;
+                       double y = 0.0;
+                       double vx = -Math.sin(dirAngle);
+                       double vy = Math.cos(dirAngle);
+                       while (i < _listeBases.size()) {
+                               coords[i].x = x;
+                               coords[i].y = y;
+                               centers[i].x = x + BASE_PAIR_DISTANCE * vy;
+                               centers[i].y = y - BASE_PAIR_DISTANCE * vx;
+                               int j = _listeBases.get(i).getElementStructure();
+                               if (j > i) {
+                                       double increment = 0.;
+                                       if (i+1<_listeBases.size())
+                                       {
+                                               if (_listeBases.get(i+1).getElementStructure()==-1)
+                                               {
+                                                       //increment = -FLAT_RECURSIVE_INCREMENT;
+                                               }
+                                       }
+                                       drawLoop(i, j, x + (BASE_PAIR_DISTANCE * vx / 2.0), y
+                                                       + (BASE_PAIR_DISTANCE * vy / 2.0)+increment, dirAngle,
+                                                       coords, centers, angles, straightBulges);
+                                       centers[i].x = coords[i].x + BASE_PAIR_DISTANCE * vy;
+                                       centers[i].y = y - BASE_PAIR_DISTANCE * vx;
+                                       i = j;
+                                       x += BASE_PAIR_DISTANCE * vx;
+                                       y += BASE_PAIR_DISTANCE * vy;
+                                       centers[i].x = coords[i].x + BASE_PAIR_DISTANCE * vy;
+                                       centers[i].y = y - BASE_PAIR_DISTANCE * vx;
+                               }
+                               x += MULTILOOP_DISTANCE * vx;
+                               y += MULTILOOP_DISTANCE * vy;
+                               i += 1;
+                       }
+               } else {
+                       drawLoop(0, _listeBases.size() - 1, 0, 0, dirAngle, coords, centers, angles, straightBulges);
+               }
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       _listeBases.get(i).setCoords(
+                                       new Point2D.Double(coords[i].x * _spaceBetweenBases,
+                                                       coords[i].y * _spaceBetweenBases));
+                       _listeBases.get(i).setCenter(
+                                       new Point2D.Double(centers[i].x * _spaceBetweenBases,
+                                                       centers[i].y * _spaceBetweenBases));
+               }
+
+               // TODO
+               // change les centres des bases de la premiere helice vers la boucle la
+               // plus proche
+       }
+
+       public void drawRNANAView(VARNAConfig conf) throws ExceptionNAViewAlgorithm {
+               _drawMode = DRAW_MODE_NAVIEW;
+               _drawn = true;
+
+               ArrayList<Double> X = new ArrayList<Double>(_listeBases.size());
+               ArrayList<Double> Y = new ArrayList<Double>(_listeBases.size());
+               ArrayList<Short> pair_table = new ArrayList<Short>(_listeBases.size());
+
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       pair_table.add(Short.valueOf(String.valueOf(_listeBases.get(i)
+                                       .getElementStructure())));
+               }
+               NAView naView = new NAView();
+               naView.naview_xy_coordinates(pair_table, X, Y);
+
+               // Updating individual base positions
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       _listeBases.get(i).setCoords(
+                                       new Point2D.Double(
+                                                       X.get(i) * 2.5 * conf._spaceBetweenBases, Y.get(i)
+                                                                       * 2.5 * conf._spaceBetweenBases));
+               }
+
+               // Updating centers
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       int indicePartner = _listeBases.get(i).getElementStructure();
+                       if (indicePartner != -1) {
+                               Point2D.Double base = _listeBases.get(i).getCoords();
+                               Point2D.Double partner = _listeBases.get(indicePartner)
+                                               .getCoords();
+                               _listeBases.get(i).setCenter(
+                                               new Point2D.Double((base.x + partner.x) / 2.0,
+                                                               (base.y + partner.y) / 2.0));
+                       } else {
+                               Vector<Integer> loop = getLoopBases(i);
+                               double tmpx = 0.0;
+                               double tmpy = 0.0;
+                               for (int j = 0; j < loop.size(); j++) {
+                                       int partner = loop.elementAt(j);
+                                       Point2D.Double loopmember = _listeBases.get(partner)
+                                                       .getCoords();
+                                       tmpx += loopmember.x;
+                                       tmpy += loopmember.y;
+                               }
+                               _listeBases.get(i).setCenter(
+                                               new Point2D.Double(tmpx / loop.size(), tmpy
+                                                               / loop.size()));
+                       }
+               }
+       }
+
+       /*
+        * public void drawMOTIFView() { _drawn = true; _drawMode =
+        * DRAW_MODE_MOTIFVIEW; int spaceBetweenStrand =0; Motif motif = new
+        * Motif(this,get_listeBases()); motif.listStrand(); for (int i = 0; i <
+        * motif.getListStrand().sizeStruct(); i++ ){ for (int j = 0; j <
+        * motif.getListStrand().getStrand(i).sizeStrand(); j++ ){ int indice =
+        * motif.getListStrand().getStrand(i).getMB(j).getIndex();
+        * get_listeBases().get(indice).setCoords( new Point2D.Double(0,0));
+        * get_listeBases().get(indice).setCenter( new Point2D.Double(0, 0));
+        * 
+        * } } //Recherche du brin central int centralStrand =
+        * motif.getCentralStrand();
+        * 
+        * //Cas o? l'on a un motif en ?toile if(centralStrand!=-1){ //On positionne
+        * le brin central motif.positionneSpecificStrand(centralStrand,
+        * spaceBetweenStrand);
+        * 
+        * //On place les autres brins par rapport a ce brin central
+        * motif.orderStrands(centralStrand); }
+        * 
+        * else { centralStrand = 0; motif.positionneStrand(); motif.ajusteStrand();
+        * } motif.reajustement(); motif.deviationBasePair();
+        * motif.setCenterMotif(); }
+        */
+
+       public ArrayList<ModeleBase> getAllPartners(int indice) {
+               ArrayList<ModeleBase> result = new ArrayList<ModeleBase>();
+               ModeleBase me = this.getBaseAt(indice);
+               int i = me.getElementStructure();
+               if (i != -1) {
+                       result.add(getBaseAt(i));
+               }
+               ArrayList<ModeleBP> msbps = getAuxBPs(indice);
+               for (ModeleBP m : msbps) {
+                       result.add(m.getPartner(me));
+               }
+               return result;
+       }
+
+       public int get_drawMode() {
+               return _drawMode;
+       }
+
+       public void setDrawMode(int drawMode) {
+               _drawMode = drawMode;
+       }
+
+       public Set<Integer> getSeparatorPositions(String s) {
+               HashSet<Integer> result = new HashSet<Integer>();
+               int index = s.indexOf(DBNStrandSep);
+               while (index >= 0) {
+                       result.add(index);
+                       index = s.indexOf(DBNStrandSep, index + 1);
+               }
+               return result;
+       }
+
+       public static String DBNStrandSep = "&";
+
+       public void setRNA(String seq, String str)
+                       throws ExceptionFileFormatOrSyntax,
+                       ExceptionUnmatchedClosingParentheses {
+               ArrayList<String> al = RNA.explodeSequence(seq);
+               Set<Integer> sepPos = getSeparatorPositions(str);
+               ArrayList<String> alRes = new ArrayList<String>();
+               Set<Integer> resSepPos = new HashSet<Integer>();
+               String strRes = "";
+               for (int i = 0; i < al.size(); i++) {
+                       if (sepPos.contains(i) && al.get(i).equals(DBNStrandSep)) {
+                               resSepPos.add(alRes.size() - 1);
+                       } else {
+                               alRes.add(al.get(i));
+                               if (i<str.length())
+                               {
+                                       strRes += str.charAt(i);
+                               }
+                               else
+                               {
+                                       strRes += '.';
+                               }
+                       }
+               }
+               for (int i = al.size(); i < str.length(); i++) {
+                       alRes.add(" ");
+                       strRes += str.charAt(i);
+               }
+               setRNA(alRes, strRes);
+               for (int i : resSepPos) {
+                       _backbone.addElement(new ModeleBackboneElement(i,
+                                       BackboneType.DISCONTINUOUS_TYPE));
+               }
+       }
+
+       public void setRNA(String seq) {
+               ArrayList<String> s = RNA.explodeSequence(seq);
+               int[] str = new int[s.size()];
+               for (int i = 0; i < str.length; i++) {
+                       str[i] = -1;
+               }
+               try {
+                       setRNA(s, str);
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+       }
+
+       public void setRNA(String seq, int[] str)
+                       throws ExceptionFileFormatOrSyntax,
+                       ExceptionUnmatchedClosingParentheses {
+               setRNA(RNA.explodeSequence(seq), str);
+       }
+
+       public void setRNA(String[] seq, int[] str)
+                       throws ExceptionFileFormatOrSyntax {
+               setRNA(seq, str, 1);
+       }
+
+       public void setRNA(List<String> seq, int[] str)
+                       throws ExceptionFileFormatOrSyntax {
+               setRNA(seq.toArray(new String[seq.size()]), str, 1);
+       }
+
+       public void setRNA(List<String> seq, int[] str, int baseIndex)
+                       throws ExceptionFileFormatOrSyntax {
+               setRNA(seq.toArray(new String[seq.size()]), str, baseIndex);
+       }
+
+       public void setRNA(String[] seq, int[] str, int baseIndex)
+                       throws ExceptionFileFormatOrSyntax {
+               clearAnnotations();
+               _listeBases = new ArrayList<ModeleBase>();
+               if (seq.length != str.length) {
+                       warningEmition("Sequence length " + seq.length
+                                       + " differs from that of secondary structure " + str.length
+                                       + ". \nAdapting sequence length ...");
+                       if (seq.length < str.length) {
+                               String[] nseq = new String[str.length];
+                               for (int i = 0; i < seq.length; i++) {
+                                       nseq[i] = seq[i];
+                               }
+                               for (int i = seq.length; i < nseq.length; i++) {
+                                       nseq[i] = "";
+                               }
+                               seq = nseq;
+                       } else {
+                               String[] seqTmp = new String[str.length];
+                               for (int i = 0; i < str.length; i++) {
+                                       seqTmp[i] = seq[i];
+                               }
+                               seq = seqTmp;
+                       }
+               }
+               for (int i = 0; i < str.length; i++) {
+                       _listeBases.add(new ModeleBaseNucleotide(seq[i], i, baseIndex + i));
+               }
+               applyStruct(str);
+       }
+
+       /**
+        * Sets the RNA to be drawn. Uses when comparison mode is on. Will draw the
+        * super-structure passed in parameters and apply specials styles to the
+        * bases owning by each RNA alignment and both.
+        * 
+        * @param seq
+        *            - The sequence of the super-structure This sequence shall be
+        *            designed like this:
+        *            <code>firstRNA1stBaseSecondRNA1stBaseFirstRNA2ndBaseSecondRNA2ndBase [...]</code>
+        * <br>
+        *            <b>Example:</b> <code>AAC-GUAGA--UGG</code>
+        * @param struct
+        *            - The super-structure
+        * @param basesOwn
+        *            - The RNA owning bases array (each index will be:0 when common
+        *            base, 1 when first RNA alignment base, 2 when second RNA
+        *            alignment base)
+        * @throws ExceptionUnmatchedClosingParentheses
+        * @throws ExceptionFileFormatOrSyntax
+        */
+       public void setRNA(String seq, String struct, ArrayList<Integer> basesOwn)
+                       throws ExceptionUnmatchedClosingParentheses,
+                       ExceptionFileFormatOrSyntax {
+               clearAnnotations();
+               _listeBases = new ArrayList<ModeleBase>();
+               // On "parse" la structure (repérage des points, tiret et couples
+               // parentheses ouvrante/fermante)
+               int[] array_struct = parseStruct(struct);
+               int size = struct.length();
+               int j = 0;
+               for (int i = 0; i < size; i++) {
+                       ModeleBase mb;
+                       if (seq.charAt(j) != seq.charAt(j + 1)) {
+                               ModeleBasesComparison mbc = new ModeleBasesComparison(
+                                               seq.charAt(j), seq.charAt(j + 1), i);
+                               mbc.set_appartenance(basesOwn.get(i));
+                               mbc.setBaseNumber(i + 1);
+                               mb = mbc;
+                       } else {
+                               mb = new ModeleBaseNucleotide("" + seq.charAt(j), i, i + 1);
+
+                       }
+                       _listeBases.add(mb);
+                       j += 2;
+               }
+               for (int i = 0; i < size; i++) {
+                       if (array_struct[i] != -1) {
+                               this.addBPNow(i, array_struct[i]);
+                       }
+
+                       j += 2;
+               }
+       }
+
+       public void setRNA(List<String> seq, String dbnStr)
+                       throws ExceptionUnmatchedClosingParentheses,
+                       ExceptionFileFormatOrSyntax {
+               clearAnnotations();
+               int[] finStr = RNAFactory.parseSecStr(dbnStr);
+               setRNA(seq, finStr);
+       }
+
+       public static ArrayList<String> explodeSequence(String seq) {
+               ArrayList<String> analyzedSeq = new ArrayList<String>();
+               int i = 0;
+               while (i < seq.length()) {
+                       if (seq.charAt(i) == '{') {
+                               boolean found = false;
+                               String buf = "";
+                               i++;
+                               while (!found & (i < seq.length())) {
+                                       if (seq.charAt(i) != '}') {
+                                               buf += seq.charAt(i);
+                                               i++;
+                                       } else {
+                                               found = true;
+                                       }
+                               }
+                               analyzedSeq.add(buf);
+                       } else {
+                               analyzedSeq.add("" + seq.charAt(i));
+                       }
+                       i++;
+               }
+               return analyzedSeq;
+       }
+
+       public int[] parseStruct(String str)
+                       throws ExceptionUnmatchedClosingParentheses,
+                       ExceptionFileFormatOrSyntax {
+               int[] result = new int[str.length()];
+               int unexpectedChar = -1;
+               Stack<Integer> p = new Stack<Integer>();
+               for (int i = 0; i < str.length(); i++) {
+                       char c = str.charAt(i);
+                       if (c == '(') {
+                               p.push(new Integer(i));
+                       } else if (c == '.' || c == '-' || c == ':') {
+                               result[i] = -1;
+                       } else if (c == ')') {
+                               if (p.size() == 0) {
+                                       throw new ExceptionUnmatchedClosingParentheses(i + 1);
+                               }
+                               int j = p.pop().intValue();
+                               result[i] = j;
+                               result[j] = i;
+                       } else {
+                               if (unexpectedChar == -1)
+                                       unexpectedChar = i;
+                               break;
+                       }
+               }
+
+               if (unexpectedChar != -1) {
+                       // warningEmition("Unexpected Character at index:" +
+                       // unexpectedChar);
+               }
+
+               if (p.size() != 0) {
+                       throw new ExceptionUnmatchedClosingParentheses(
+                                       p.pop().intValue() + 1);
+               }
+
+               return result;
+       }
+
+       public Point getHelixInterval(int index) {
+               if ((index < 0) || (index >= _listeBases.size())) {
+                       return new Point(index, index);
+               }
+               int j = _listeBases.get(index).getElementStructure();
+               if (j != -1) {
+                       int minH = index;
+                       int maxH = index;
+                       if (j > index) {
+                               maxH = j;
+                       } else {
+                               minH = j;
+                       }
+                       boolean over = false;
+                       while (!over) {
+                               if ((minH < 0) || (maxH >= _listeBases.size())) {
+                                       over = true;
+                               } else {
+                                       if (_listeBases.get(minH).getElementStructure() == maxH) {
+                                               minH--;
+                                               maxH++;
+                                       } else {
+                                               over = true;
+                                       }
+                               }
+                       }
+                       minH++;
+                       maxH--;
+                       return new Point(minH, maxH);
+               }
+               return new Point(0, 0);
+       }
+
+       public Point getExteriorHelix(int index) {
+               Point h = getHelixInterval(index);
+               int a = h.x;
+               int b = h.y;            
+               while (!((h.x==0)))
+               {                       
+                       a = h.x;
+                       b = h.y;                
+                       h = getHelixInterval(a-1);
+               }
+               return new Point(a, b);
+       }
+       
+       
+       public ArrayList<Integer> getHelix(int index) {
+               ArrayList<Integer> result = new ArrayList<Integer>();
+               if ((index < 0) || (index >= _listeBases.size())) {
+                       return result;
+               }
+               Point p = getHelixInterval(index);
+               for (int i = p.x; i <= p.y; i++) {
+                       result.add(i);
+                       result.add(this._listeBases.get(i).getElementStructure());
+               }
+               return result;
+       }
+
+       public Point getMultiLoop(int index) {
+               if ((index < 0) || (index >= _listeBases.size())) {
+                       return new Point(index, index);
+               }
+               Point h = getHelixInterval(index);
+               int minH = h.x - 1;
+               int maxH = h.y + 1;
+               boolean over = false;
+               while (!over) {
+                       if (minH < 0) {
+                               over = true;
+                               minH = 0;
+                       } else {
+                               if (_listeBases.get(minH).getElementStructure() == -1) {
+                                       minH--;
+                               } else if (_listeBases.get(minH).getElementStructure() < minH) {
+                                       minH = _listeBases.get(minH).getElementStructure() - 1;
+                               } else {
+                                       over = true;
+                               }
+                       }
+               }
+               over = false;
+               while (!over) {
+                       if (maxH > _listeBases.size() - 1) {
+                               over = true;
+                               maxH = _listeBases.size() - 1;
+                       } else {
+                               if (_listeBases.get(maxH).getElementStructure() == -1) {
+                                       maxH++;
+                               } else if (_listeBases.get(maxH).getElementStructure() > maxH) {
+                                       maxH = _listeBases.get(maxH).getElementStructure() + 1;
+                               } else {
+                                       over = true;
+                               }
+                       }
+               }
+               return new Point(minH, maxH);
+       }
+
+       public Vector<Integer> getLoopBases(int startIndex) {
+               Vector<Integer> result = new Vector<Integer>();
+
+               if ((startIndex < 0) || (startIndex >= _listeBases.size())) {
+                       return result;
+               }
+               int index = startIndex;
+               result.add(startIndex);
+               if (_listeBases.get(index).getElementStructure() <= index) {
+                       index = (index + 1) % _listeBases.size();
+               } else {
+                       index = _listeBases.get(index).getElementStructure();
+                       result.add(index);
+                       index = (index + 1) % _listeBases.size();
+               }
+
+               while (index != startIndex) {
+                       result.add(index);
+                       if (_listeBases.get(index).getElementStructure() == -1) {
+                               index = (index + 1) % _listeBases.size();
+                       } else {
+                               index = _listeBases.get(index).getElementStructure();
+                               result.add(index);
+                               index = (index + 1) % _listeBases.size();
+                       }
+               }
+               return result;
+       }
+
+       /**
+        * Returns the RNA secondary structure displayed by this panel as a
+        * well-parenthesized word, accordingly to the DBN format
+        * 
+        * @return This panel's secondary structure
+        */
+       public String getStructDBN() {
+               String result = "";
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       int j = _listeBases.get(i).getElementStructure();
+                       if (j == -1) {
+                               result += ".";
+                       } else if (i > j) {
+                               result += ")";
+                       } else {
+                               result += "(";
+                       }
+               }
+               return addStrandSeparators(result);
+       }
+
+       private ArrayList<ModeleBP> getNonCrossingSubset(
+                       ArrayList<ArrayList<ModeleBP>> rankedBPs) {
+               ArrayList<ModeleBP> currentBPs = new ArrayList<ModeleBP>();
+               Stack<Integer> pile = new Stack<Integer>();
+               for (int i = 0; i < rankedBPs.size(); i++) {
+                       ArrayList<ModeleBP> lbp = rankedBPs.get(i);
+                       if (!lbp.isEmpty()) {
+                               ModeleBP bp = lbp.get(0);
+                               boolean ok = true;
+                               if (!pile.empty()) {
+                                       int x = pile.peek();
+                                       if ((bp.getIndex3() >= x)) {
+                                               ok = false;
+                                       }
+                               }
+                               if (ok) {
+                                       lbp.remove(0);
+                                       currentBPs.add(bp);
+                                       pile.add(bp.getIndex3());
+                               }
+                       }
+                       if (!pile.empty() && (i == pile.peek())) {
+                               pile.pop();
+                       }
+               }
+               return currentBPs;
+       }
+
+       public ArrayList<int[]> paginateStructure() {
+               ArrayList<int[]> result = new ArrayList<int[]>();
+               // Mumbo jumbo to sort the basepair list
+               ArrayList<ModeleBP> bps = this.getAllBPs();
+               ModeleBP[] mt = new ModeleBP[bps.size()];
+               bps.toArray(mt);
+               Arrays.sort(mt, new Comparator<ModeleBP>() {
+                       public int compare(ModeleBP arg0, ModeleBP arg1) {
+                               if (arg0.getIndex5() != arg1.getIndex5())
+                                       return arg0.getIndex5() - arg1.getIndex5();
+                               else
+                                       return arg0.getIndex3() - arg1.getIndex3();
+
+                       }
+               });
+               ArrayList<ArrayList<ModeleBP>> rankedBps = new ArrayList<ArrayList<ModeleBP>>();
+               for (int i = 0; i < getSize(); i++) {
+                       rankedBps.add(new ArrayList<ModeleBP>());
+               }
+               for (int i = 0; i < mt.length; i++) {
+                       rankedBps.get(mt[i].getIndex5()).add(mt[i]);
+               }
+
+               while (!bps.isEmpty()) {
+                       //System.out.println("Page: " + result.size());
+                       ArrayList<ModeleBP> currentBPs = getNonCrossingSubset(rankedBps);
+                       int[] ss = new int[this.getSize()];
+                       for (int i = 0; i < ss.length; i++) {
+                               ss[i] = -1;
+                       }
+
+                       for (int i = 0; i < currentBPs.size(); i++) {
+                               ModeleBP mbp = currentBPs.get(i);
+                               ss[mbp.getIndex3()] = mbp.getIndex5();
+                               ss[mbp.getIndex5()] = mbp.getIndex3();
+                       }
+                       bps.removeAll(currentBPs);
+                       result.add(ss);
+               }
+               return result;
+       }
+
+       private void showBasic(int[] res) {
+               for (int i = 0; i < res.length; i++) {
+                       System.out.print(res[i] + ",");
+               }
+               System.out.println();
+
+       }
+       
+       public int[] getStrandShifts()
+       {
+               int[] result = new int[getSize()];
+               int acc = 0;
+               for (int i=0;i<getSize();i++)
+               {
+                       if (_backbone.getTypeBefore(i)==BackboneType.DISCONTINUOUS_TYPE)
+                       {
+                               acc++;
+                       }
+                       result[i] = acc;
+               }
+               return result;
+               
+       }
+       
+       public String addStrandSeparators(String s)
+       {
+               String res = "";
+               for (int i=0;i<s.length();i++)
+               {
+                       res += s.charAt(i);
+                       if (_backbone.getTypeAfter(i)==BackboneType.DISCONTINUOUS_TYPE)
+                       {
+                               res += DBNStrandSep;
+                       }
+               }
+               return res;
+       }
+       
+
+       public String getStructDBN(boolean includeMostPKs) {
+               String result = getStructDBN();
+               if (includeMostPKs) {
+                       ArrayList<int[]> pages = paginateStructure();
+                       char[] res = new char[getSize()];
+                       for (int i = 0; i < res.length; i++) {
+                               res[i] = '.';
+                       }
+                       char[] open = { '(', '[', '{', '<', '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'};
+                       
+                       char[] close = new char[open.length];
+                       close[0] = ')';
+                       close[1] = ']';
+                       close[2] = '}';
+                       close[3] = '>';
+                       for (int i=4; i<open.length;i++)
+                       {
+                               close[i] = Character.toLowerCase(open[i]);
+                       }
+                       
+                       for (int p = 0; p < Math.min(pages.size(), open.length); p++) {
+                               int[] page = pages.get(p);
+                               //showBasic(page);
+                               for (int i = 0; i < res.length; i++) {
+                                       if (page[i] != -1 && page[i] > i && res[i] == '.'
+                                                       && res[page[i]] == '.') {
+                                               res[i] = open[p];
+                                               res[page[i]] = close[p];
+                                       }
+                               }
+                       }
+                       result = "";
+                       for (int i = 0; i < res.length; i++) {
+                               result += res[i];
+                       }
+
+               }
+               return addStrandSeparators(result);
+
+       }
+
+       public String getStructDBN(int[] str) {
+               String result = "";
+               for (int i = 0; i < str.length; i++) {
+                       if (str[i] == -1) {
+                               result += ".";
+                       } else if (str[i] > i) {
+                               result += "(";
+                       } else {
+                               result += ")";
+                       }
+               }
+               return addStrandSeparators(result);
+       }
+
+       /**
+        * Returns the raw nucleotides sequence for the displayed RNA
+        * 
+        * @return The RNA sequence
+        */
+       public String getSeq() {
+               String result = "";
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       result += ((ModeleBase) _listeBases.get(i)).getContent();
+               }
+               return addStrandSeparators(result);
+       }
+
+       public String getStructBPSEQ() {
+               String result = "";
+               int[] str = getNonOverlappingStruct();
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       result += (i + 1) + " "
+                                       + ((ModeleBaseNucleotide) _listeBases.get(i)).getContent()
+                                       + " " + (str[i] + 1) + "\n";
+               }
+               return result;
+       }
+
+       public int[] getNonCrossingStruct() {
+               int[] result = new int[_listeBases.size()];
+               // Adding "planar" base-pairs
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       result[i] = _listeBases.get(i).getElementStructure();
+               }
+               return result;
+       }
+
+       public int[] getNonOverlappingStruct() {
+               int[] result = getNonCrossingStruct();
+               // Adding additional base pairs when possible (No more than one
+               // base-pair per base)
+               for (int i = 0; i < _structureAux.size(); i++) {
+                       ModeleBP msbp = _structureAux.get(i);
+                       ModeleBase mb5 = msbp.getPartner5();
+                       ModeleBase mb3 = msbp.getPartner3();
+                       int j5 = mb5.getIndex();
+                       int j3 = mb3.getIndex();
+                       if ((result[j3] == -1) && (result[j5] == -1)) {
+                               result[j3] = j5;
+                               result[j5] = j3;
+                       }
+               }
+               return result;
+       }
+
+       public String getStructCT() {
+               String result = "";
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       result += (i + 1) + " "
+                                       + ((ModeleBase) _listeBases.get(i)).getContent() + " " + i
+                                       + " " + (i + 2) + " "
+                                       + (_listeBases.get(i).getElementStructure() + 1) + " "
+                                       + (i + 1) + "\n";
+               }
+               return result;
+       }
+
+       public void saveAsBPSEQ(String path, String title)
+                       throws ExceptionExportFailed, ExceptionPermissionDenied {
+               try {
+                       FileWriter f = new FileWriter(path);
+                       f.write("# " + title + "\n");
+                       f.write(this.getStructBPSEQ() + "\n");
+                       f.close();
+               } catch (IOException e) {
+                       throw new ExceptionExportFailed(e.getMessage(), path);
+               }
+       }
+
+       public void saveAsCT(String path, String title)
+                       throws ExceptionExportFailed, ExceptionPermissionDenied {
+               try {
+                       FileWriter f = new FileWriter(path);
+                       f.write("" + _listeBases.size() + " " + title + "\n");
+                       f.write(this.getStructCT() + "\n");
+                       f.close();
+               } catch (IOException e) {
+                       throw new ExceptionExportFailed(e.getMessage(), path);
+               }
+       }
+
+       public void saveAsDBN(String path, String title)
+                       throws ExceptionExportFailed, ExceptionPermissionDenied {
+               try {
+                       FileWriter f = new FileWriter(path);
+                       f.write("> " + title + "\n");
+                       f.write(getListeBasesToString() + "\n");
+                       f.write(getStructDBN() + "\n");
+                       f.close();
+               } catch (IOException e) {
+                       throw new ExceptionExportFailed(e.getMessage(), path);
+               }
+       }
+
+       public String getListeBasesToString() {
+               String s = new String();
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       s += ((ModeleBaseNucleotide) _listeBases.get(i)).getContent();
+               }
+               return addStrandSeparators(s);
+       }
+
+       public void applyBPs(ArrayList<ModeleBP> allbps) {
+               ArrayList<ModeleBP> planar = new ArrayList<ModeleBP>();
+               ArrayList<ModeleBP> others = new ArrayList<ModeleBP>();
+               // System.err.println("Sequence: "+this.getSeq());
+               RNAMLParser.planarize(allbps, planar, others, getSize());
+               // System.err.println("All:"+allbps);
+               // System.err.println("=> Planar: "+planar);
+               // System.err.println("=> Others: "+others);
+
+               for (ModeleBP mb : planar) {
+                       addBPnow(mb.getPartner5().getIndex(), mb.getPartner3().getIndex(),
+                                       mb);
+               }
+
+               for (ModeleBP mb : others) {
+                       addBPAux(mb.getPartner5().getIndex(), mb.getPartner3().getIndex(),
+                                       mb);
+               }
+       }
+
+       public void set_listeBases(ArrayList<ModeleBase> _liste) {
+               this._listeBases = _liste;
+       }
+
+       public void addVARNAListener(InterfaceVARNAListener rl) {
+               _listeVARNAListener.add(rl);
+       }
+
+       public void warningEmition(String warningMessage) {
+               for (int i = 0; i < _listeVARNAListener.size(); i++) {
+                       _listeVARNAListener.get(i).onWarningEmitted(warningMessage);
+               }
+       }
+
+       public void applyStyleOnBases(ArrayList<Integer> basesList,
+                       ModelBaseStyle style) {
+               for (int i = 1; i < basesList.size(); i++) {
+                       _listeBases.get(basesList.get(i)).setStyleBase(style);
+               }
+       }
+
+       private int[] correctReciprocity(int[] str) {
+               int[] result = new int[str.length];
+               for (int i = 0; i < str.length; i++) {
+                       if (str[i] != -1) {
+                               if (i == str[str[i]]) {
+                                       result[i] = str[i];
+                               } else {
+                                       str[str[i]] = i;
+                               }
+                       } else {
+                               result[i] = -1;
+                       }
+               }
+               return result;
+       }
+
+       private void applyStruct(int[] str) throws ExceptionFileFormatOrSyntax {
+               str = correctReciprocity(str);
+
+               int[] planarSubset = RNAMLParser.planarize(str);
+               _structureAux.clear();
+
+               for (int i = 0; i < planarSubset.length; i++) {
+                       if (str[i] > i) {
+                               if (planarSubset[i] > i) {
+                                       addBPNow(i, planarSubset[i]);
+                               } else if ((planarSubset[i] != str[i])) {
+                                       addBPAux(i, str[i]);
+                               }
+                       }
+               }
+
+       }
+
+       public ArrayList<ModeleBase> get_listeBases() {
+               return _listeBases;
+       }
+
+       public int getSize() {
+               return _listeBases.size();
+       }
+
+       public ArrayList<Integer> findAll() {
+               ArrayList<Integer> listAll = new ArrayList<Integer>();
+               for (int i = 0; i < get_listeBases().size(); i++) {
+                       listAll.add(i);
+               }
+               return listAll;
+       }
+
+       public ArrayList<Integer> findBulge(int index) {
+               ArrayList<Integer> listUp = new ArrayList<Integer>();
+               if (get_listeBases().get(index).getElementStructure() == -1) {
+                       int i = index;
+                       boolean over = false;
+                       while ((i < get_listeBases().size()) && !over) {
+                               int j = get_listeBases().get(i).getElementStructure();
+                               if (j == -1) {
+                                       listUp.add(i);
+                                       i++;
+                               } else {
+                                       over = true;
+                               }
+                       }
+                       i = index - 1;
+                       over = false;
+                       while ((i >= 0) && !over) {
+                               int j = get_listeBases().get(i).getElementStructure();
+                               if (j == -1) {
+                                       listUp.add(i);
+                                       i--;
+                               } else {
+                                       over = true;
+                               }
+                       }
+               }
+               return listUp;
+       }
+
+       public ArrayList<Integer> findStem(int index) {
+               ArrayList<Integer> listUp = new ArrayList<Integer>();
+               int i = index;
+               do {
+                       listUp.add(i);
+                       int j = get_listeBases().get(i).getElementStructure();
+                       if (j == -1) {
+                               i = (i + 1) % getSize();
+                       } else {
+                               if ((j < i) && (index <= i) && (j <= index)) {
+                                       i = j;
+                               } else {
+                                       i = (i + 1) % getSize();
+                               }
+                       }
+               } while (i != index);
+               return listUp;
+       }
+
+       public int getHelixCountOnLoop(int indice) {
+               int cptHelice = 0;
+               if (indice < 0 || indice >= get_listeBases().size())
+                       return cptHelice;
+               int i = indice;
+               int j = get_listeBases().get(i).getElementStructure();
+               // Only way to distinguish "supporting base-pair" from others
+               boolean justJumped = false;
+               if ((j != -1) && (j < i)) {
+                       i = j + 1;
+                       indice = i;
+               }
+               do {
+                       j = get_listeBases().get(i).getElementStructure();
+                       if ((j != -1) && (!justJumped)) {
+                               i = j;
+                               justJumped = true;
+                               cptHelice++;
+                       } else {
+                               i = (i + 1) % get_listeBases().size();
+                               justJumped = false;
+                       }
+               } while (i != indice);
+               return cptHelice;
+       }
+
+       public ArrayList<Integer> findLoop(int indice) {
+               return findLoopForward(indice);
+       }
+
+       public ArrayList<Integer> findLoopForward(int indice) {
+               ArrayList<Integer> base = new ArrayList<Integer>();
+               if (indice < 0 || indice >= get_listeBases().size())
+                       return base;
+               int i = indice;
+               int j = get_listeBases().get(i).getElementStructure();
+               // Only way to distinguish "supporting base-pair" from others
+               boolean justJumped = false;
+               if (j != -1) {
+                       i = Math.min(i, j) + 1;
+                       indice = i;
+               }
+               do {
+                       base.add(i);
+                       j = get_listeBases().get(i).getElementStructure();
+                       if ((j != -1) && (!justJumped)) {
+                               i = j;
+                               justJumped = true;
+                       } else {
+                               i = (i + 1) % get_listeBases().size();
+                               justJumped = false;
+                       }
+               } while (i != indice);
+               return base;
+       }
+
+       public ArrayList<Integer> findPair(int indice) {
+               ArrayList<Integer> base = new ArrayList<Integer>();
+               int j = get_listeBases().get(indice).getElementStructure();
+               if (j != -1) {
+                       base.add(Math.min(indice, j));
+                       base.add(Math.max(indice, j));
+               }
+
+               return base;
+
+       }
+
+       public ArrayList<Integer> findLoopBackward(int indice) {
+               ArrayList<Integer> base = new ArrayList<Integer>();
+               if (indice < 0 || indice >= get_listeBases().size())
+                       return base;
+               int i = indice;
+               int j = get_listeBases().get(i).getElementStructure();
+               // Only way to distinguish "supporting base-pair" from others
+               boolean justJumped = false;
+               if (j != -1) {
+                       i = Math.min(i, j) - 1;
+                       indice = i;
+               }
+               if (i < 0) {
+                       return base;
+               }
+               do {
+                       base.add(i);
+                       j = get_listeBases().get(i).getElementStructure();
+                       if ((j != -1) && (!justJumped)) {
+                               i = j;
+                               justJumped = true;
+                       } else {
+                               i = (i + get_listeBases().size() - 1) % get_listeBases().size();
+                               justJumped = false;
+                       }
+               } while (i != indice);
+               return base;
+       }
+
+       public ArrayList<Integer> findHelix(int indice) {
+               ArrayList<Integer> list = new ArrayList<Integer>();
+               if (get_listeBases().get(indice).getElementStructure() != -1) {
+                       list.add(indice);
+                       list.add(get_listeBases().get(indice).getElementStructure());
+                       int i = 1, prec = get_listeBases().get(indice)
+                                       .getElementStructure();
+                       while (indice + i < get_listeBases().size()
+                                       && get_listeBases().get(indice + i).getElementStructure() != -1
+                                       && get_listeBases().get(indice + i).getElementStructure() == prec - 1) {
+                               list.add(indice + i);
+                               list.add(get_listeBases().get(indice + i).getElementStructure());
+                               prec = get_listeBases().get(indice + i).getElementStructure();
+                               i++;
+                       }
+                       i = -1;
+                       prec = get_listeBases().get(indice).getElementStructure();
+                       while (indice + i >= 0
+                                       && get_listeBases().get(indice + i).getElementStructure() != -1
+                                       && get_listeBases().get(indice + i).getElementStructure() == prec + 1) {
+                               list.add(indice + i);
+                               list.add(get_listeBases().get(indice + i).getElementStructure());
+                               prec = get_listeBases().get(indice + i).getElementStructure();
+                               i--;
+                       }
+               }
+               return list;
+       }
+
+       public ArrayList<Integer> find3Prime(int indice) {
+               ArrayList<Integer> list = new ArrayList<Integer>();
+               boolean over = false;
+               while ((indice >= 0) && !over) {
+                       over = (get_listeBases().get(indice).getElementStructure() != -1);
+                       indice--;
+               }
+               indice++;
+               if (over) {
+                       indice++;
+               }
+               for (int i = indice; i < get_listeBases().size(); i++) {
+                       list.add(i);
+                       if (get_listeBases().get(i).getElementStructure() != -1) {
+                               return new ArrayList<Integer>();
+                       }
+               }
+               return list;
+       }
+
+       public ArrayList<Integer> find5Prime(int indice) {
+               ArrayList<Integer> list = new ArrayList<Integer>();
+               for (int i = 0; i <= indice; i++) {
+                       list.add(i);
+                       if (get_listeBases().get(i).getElementStructure() != -1) {
+                               return new ArrayList<Integer>();
+                       }
+               }
+               return list;
+       }
+
+       public static Double angle(Point2D.Double p1, Point2D.Double p2,
+                       Point2D.Double p3) {
+               Double alpha = Math.atan2(p1.y - p2.y, p1.x - p2.x);
+               Double beta = Math.atan2(p3.y - p2.y, p3.x - p2.x);
+               Double angle = (beta - alpha);
+
+               // Correction de l'angle pour le resituer entre 0 et 2PI
+               while (angle < 0.0 || angle > 2 * Math.PI) {
+                       if (angle < 0.0)
+                               angle += 2 * Math.PI;
+                       else if (angle > 2 * Math.PI)
+                               angle -= 2 * Math.PI;
+               }
+               return angle;
+       }
+
+       public ArrayList<Integer> findNonPairedBaseGroup(Integer get_nearestBase) {
+               // detection 3', 5', bulge
+               ArrayList<Integer> list = new ArrayList<Integer>();
+               int indice = get_nearestBase;
+               boolean nonpairedUp = true, nonpairedDown = true;
+               while (indice < get_listeBases().size() && nonpairedUp) {
+                       if (get_listeBases().get(indice).getElementStructure() == -1) {
+                               list.add(indice);
+                               indice++;
+                       } else {
+                               nonpairedUp = false;
+                       }
+               }
+               indice = get_nearestBase - 1;
+               while (indice >= 0 && nonpairedDown) {
+                       if (get_listeBases().get(indice).getElementStructure() == -1) {
+                               list.add(indice);
+                               indice--;
+                       } else {
+                               nonpairedDown = false;
+                       }
+               }
+               return list;
+       }
+
+       /*
+        * public boolean getDrawn() { return _drawn; }
+        */
+
+       public ArrayList<ModeleBP> getStructureAux() {
+               return _structureAux;
+       }
+
+       /**
+        * Translates a base number into its corresponding index. Although both
+        * should be unique, base numbers are not necessarily contiguous, and
+        * indices should be preferred for any reasonably complex algorithmic
+        * treatment.
+        * 
+        * @param num
+        *            The base number
+        * @return The first index whose associated Base model has base number
+        *         <code>num</code>, <code>-1</code> of no such base model exists.
+        */
+
+       public int getIndexFromBaseNumber(int num) {
+               for (int i = 0; i < this._listeBases.size(); i++) {
+                       if (_listeBases.get(i).getBaseNumber() == num) {
+                               return i;
+                       }
+               }
+               return -1;
+       }
+
+       /**
+        * Adds a base pair to this RNA's structure. Tries to add it to the
+        * secondary structure first, eventually adding it to the 'tertiary'
+        * interactions if it clashes with the current secondary structure.
+        * 
+        * @param baseNumber5
+        *            - Base number of the origin of this base pair
+        * @param baseNumber3
+        *            - Base number of the destination of this base pair
+        */
+
+       public void addBPToStructureUsingNumbers(int baseNumber5, int baseNumber3) {
+               int i = getIndexFromBaseNumber(baseNumber5);
+               int j = getIndexFromBaseNumber(baseNumber3);
+               addBP(i, j);
+       }
+
+       /**
+        * Adds a base pair to this RNA's structure. Tries to add it to the
+        * secondary structure first, possibly adding it to the 'tertiary'
+        * interactions if it clashes with the current secondary structure.
+        * 
+        * @param number5
+        *            - Base number of the origin of this base pair
+        * @param number3
+        *            - Base number of the destination of this base pair
+        */
+
+       public void addBPToStructureUsingNumbers(int number5, int number3,
+                       ModeleBP msbp) {
+               addBP(getIndexFromBaseNumber(number5), getIndexFromBaseNumber(number3),
+                               msbp);
+       }
+
+       public void addBP(int index5, int index3) {
+               int i = index5;
+               int j = index3;
+               ModeleBase part5 = _listeBases.get(i);
+               ModeleBase part3 = _listeBases.get(j);
+               ModeleBP msbp = new ModeleBP(part5, part3);
+               addBP(i, j, msbp);
+       }
+
+       public void addBP(int index5, int index3, ModeleBP msbp) {
+               int i = index5;
+               int j = index3;
+
+               if (j < i) {
+                       int k = j;
+                       j = i;
+                       i = k;
+               }
+               if (i != -1) {
+                       for (int k = i; k <= j; k++) {
+                               ModeleBase tmp = _listeBases.get(k);
+                               int l = tmp.getElementStructure();
+                               if (l != -1) {
+                                       if ((l <= i) || (l >= j)) {
+                                               addBPAux(i, j, msbp);
+                                               return;
+                                       }
+                               }
+                       }
+                       addBPnow(i, j, msbp);
+               }
+       }
+
+       public void removeBP(ModeleBP ms) {
+               if (_structureAux.contains(ms)) {
+                       _structureAux.remove(ms);
+               } else {
+                       ModeleBase m5 = ms.getPartner5();
+                       ModeleBase m3 = ms.getPartner3();
+                       int i = m5.getIndex();
+                       int j = m3.getIndex();
+                       if ((m5.getElementStructure() == m3.getIndex())
+                                       && (m3.getElementStructure() == m5.getIndex())) {
+                               m5.removeElementStructure();
+                               m3.removeElementStructure();
+                       }
+               }
+       }
+
+       /**
+        * Register base-pair, no question asked. More precisely, this function will
+        * not try to determine if the base-pairs crosses any other.
+        * 
+        * @param i
+        * @param j
+        * @param msbp
+        */
+       private void addBPNow(int i, int j) {
+               if (j < i) {
+                       int k = j;
+                       j = i;
+                       i = k;
+               }
+
+               ModeleBase part5 = _listeBases.get(i);
+               ModeleBase part3 = _listeBases.get(j);
+               ModeleBP msbp = new ModeleBP(part5, part3);
+               addBPnow(i, j, msbp);
+       }
+
+       /**
+        * Register base-pair, no question asked. More precisely, this function will
+        * not try to determine if the base-pairs crosses any other.
+        * 
+        * @param i
+        * @param j
+        * @param msbp
+        */
+       private void addBPnow(int i, int j, ModeleBP msbp) {
+               if (j < i) {
+                       int k = j;
+                       j = i;
+                       i = k;
+               }
+               ModeleBase part5 = _listeBases.get(i);
+               ModeleBase part3 = _listeBases.get(j);
+               msbp.setPartner5(part5);
+               msbp.setPartner3(part3);
+               part5.setElementStructure(j, msbp);
+               part3.setElementStructure(i, msbp);
+       }
+
+       public void addBPAux(int i, int j) {
+               ModeleBase part5 = _listeBases.get(i);
+               ModeleBase part3 = _listeBases.get(j);
+               ModeleBP msbp = new ModeleBP(part5, part3);
+               addBPAux(i, j, msbp);
+       }
+
+       public void addBPAux(int i, int j, ModeleBP msbp) {
+               if (j < i) {
+                       int k = j;
+                       j = i;
+                       i = k;
+               }
+               ModeleBase part5 = _listeBases.get(i);
+               ModeleBase part3 = _listeBases.get(j);
+               msbp.setPartner5(part5);
+               msbp.setPartner3(part3);
+               _structureAux.add(msbp);
+       }
+
+       public ArrayList<ModeleBP> getBPsAt(int i) {
+               ArrayList<ModeleBP> result = new ArrayList<ModeleBP>();
+               if (_listeBases.get(i).getElementStructure() != -1) {
+                       result.add(_listeBases.get(i).getStyleBP());
+               }
+               for (int k = 0; k < _structureAux.size(); k++) {
+                       ModeleBP bp = _structureAux.get(k);
+                       if ((bp.getPartner5().getIndex() == i)
+                                       || (bp.getPartner3().getIndex() == i)) {
+                               result.add(bp);
+                       }
+               }
+               return result;
+
+       }
+
+       public ModeleBP getBPStyle(int i, int j) {
+               ModeleBP result = null;
+               if (i > j) {
+                       int k = j;
+                       j = i;
+                       i = k;
+               }
+               if (_listeBases.get(i).getElementStructure() == j) {
+                       result = _listeBases.get(i).getStyleBP();
+               }
+               for (int k = 0; k < _structureAux.size(); k++) {
+                       ModeleBP bp = _structureAux.get(k);
+                       if ((bp.getPartner5().getIndex() == i)
+                                       && (bp.getPartner3().getIndex() == j)) {
+                               result = bp;
+                       }
+               }
+               return result;
+       }
+
+       public ArrayList<ModeleBP> getSecStrBPs() {
+               ArrayList<ModeleBP> result = new ArrayList<ModeleBP>();
+               for (int i = 0; i < this.getSize(); i++) {
+                       ModeleBase mb = _listeBases.get(i);
+                       int k = mb.getElementStructure();
+                       if ((k != -1) && (k > i)) {
+                               result.add(mb.getStyleBP());
+                       }
+               }
+               return result;
+       }
+
+       public ArrayList<ModeleBP> getAuxBPs() {
+               ArrayList<ModeleBP> result = new ArrayList<ModeleBP>();
+               for (ModeleBP bp : _structureAux) {
+                       result.add(bp);
+               }
+               return result;
+       }
+
+       public ArrayList<ModeleBP> getAllBPs() {
+               ArrayList<ModeleBP> result = new ArrayList<ModeleBP>();
+               result.addAll(getSecStrBPs());
+               result.addAll(getAuxBPs());
+               return result;
+       }
+
+       public ArrayList<ModeleBP> getAuxBPs(int i) {
+               ArrayList<ModeleBP> result = new ArrayList<ModeleBP>();
+               for (ModeleBP bp : _structureAux) {
+                       if ((bp.getPartner5().getIndex() == i)
+                                       || (bp.getPartner3().getIndex() == i)) {
+                               result.add(bp);
+                       }
+               }
+               return result;
+       }
+
+       public void setBaseInnerColor(Color c) {
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       ModeleBase mb = _listeBases.get(i);
+                       mb.getStyleBase().setBaseInnerColor(c);
+               }
+       }
+
+       public void setBaseNumbersColor(Color c) {
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       ModeleBase mb = _listeBases.get(i);
+                       mb.getStyleBase().setBaseNumberColor(c);
+               }
+       }
+
+       public void setBaseNameColor(Color c) {
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       ModeleBase mb = _listeBases.get(i);
+                       mb.getStyleBase().setBaseNameColor(c);
+               }
+       }
+
+       public void setBaseOutlineColor(Color c) {
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       ModeleBase mb = _listeBases.get(i);
+                       mb.getStyleBase().setBaseOutlineColor(c);
+               }
+       }
+
+       public String getName() {
+               return _name;
+       }
+
+       public void setName(String n) {
+               _name = n;
+       }
+
+       public ArrayList<TextAnnotation> getAnnotations() {
+               return _listeAnnotations;
+       }
+
+       public boolean removeAnnotation(TextAnnotation t) {
+               return _listeAnnotations.remove(t);
+       }
+
+       public void addAnnotation(TextAnnotation t) {
+               _listeAnnotations.add(t);
+       }
+
+       public void removeAnnotation(String filter) {
+               ArrayList<TextAnnotation> condamne = new ArrayList<TextAnnotation>();
+               for (TextAnnotation t : _listeAnnotations) {
+                       if (t.getTexte().contains(filter)) {
+                               condamne.add(t);
+                       }
+               }
+               for (TextAnnotation t : condamne) {
+                       _listeAnnotations.remove(t);
+               }
+       }
+
+       public void clearAnnotations() {
+               _listeAnnotations.clear();
+       }
+
+       private boolean _strandEndsAnnotated = false;
+
+       public void autoAnnotateStrandEnds() {
+               if (!_strandEndsAnnotated) {
+                       int tailleListBases = _listeBases.size();
+                       boolean endAnnotate = false;
+                       addAnnotation(new TextAnnotation("5'", _listeBases.get(0)));
+                       for (int i = 0; i < _listeBases.size() - 1; i++) {
+                               int realposA = _listeBases.get(i).getBaseNumber();
+                               int realposB = _listeBases.get(i + 1).getBaseNumber();
+                               if (realposB - realposA != 1) {
+                                       addAnnotation(new TextAnnotation("3'", _listeBases.get(i)));
+                                       addAnnotation(new TextAnnotation("5'",
+                                                       _listeBases.get(i + 1)));
+                                       if (i + 1 == _listeBases.size() - 1) {
+                                               endAnnotate = true;
+                                       }
+                               }
+                       }
+                       if (!endAnnotate) {
+                               addAnnotation(new TextAnnotation("3'",
+                                               _listeBases.get(tailleListBases - 1)));
+                       }
+                       _strandEndsAnnotated = true;
+               } else {
+                       removeAnnotation("3'");
+                       removeAnnotation("5'");
+                       _strandEndsAnnotated = false;
+               }
+       }
+
+       public void autoAnnotateHelices() {
+               Stack<Integer> p = new Stack<Integer>();
+               p.push(0);
+               int nbH = 1;
+               while (!p.empty()) {
+                       int i = p.pop();
+                       if (i < _listeBases.size()) {
+                               ModeleBase mb = _listeBases.get(i);
+                               int j = mb.getElementStructure();
+                               if (j == -1) {
+                                       p.push(i + 1);
+                               } else {
+                                       if (j > i) {
+                                               ModeleBase mbp = _listeBases.get(j);
+                                               p.push(j + 1);
+                                               ArrayList<ModeleBase> h = new ArrayList<ModeleBase>();
+                                               int k = 1;
+                                               while (mb.getElementStructure() == mbp.getIndex()) {
+                                                       h.add(mb);
+                                                       h.add(mbp);
+                                                       mb = _listeBases.get(i + k);
+                                                       mbp = _listeBases.get(j - k);
+
+                                                       k++;
+                                               }
+                                               try {
+                                                       addAnnotation(new TextAnnotation("H" + nbH++, h,
+                                                                       TextAnnotation.AnchorType.HELIX));
+                                               } catch (Exception e) {
+                                                       e.printStackTrace();
+                                               }
+                                               p.push(i + k);
+                                       }
+                               }
+                       }
+               }
+       }
+
+       public void autoAnnotateTerminalLoops() {
+               Stack<Integer> p = new Stack<Integer>();
+               p.push(0);
+               int nbT = 1;
+               while (!p.empty()) {
+                       int i = p.pop();
+                       if (i < _listeBases.size()) {
+                               ModeleBase mb = _listeBases.get(i);
+                               int j = mb.getElementStructure();
+                               if (j == -1) {
+                                       int k = 1;
+                                       ArrayList<ModeleBase> t = new ArrayList<ModeleBase>();
+                                       while ((i + k < getSize())
+                                                       && (mb.getElementStructure() == -1)) {
+                                               t.add(mb);
+                                               mb = _listeBases.get(i + k);
+                                               k++;
+                                       }
+                                       if (mb.getElementStructure() != -1) {
+                                               if (mb.getElementStructure() == i - 1) {
+                                                       try {
+                                                               t.add(_listeBases.get(i - 1));
+                                                               t.add(_listeBases.get(i + k - 1));
+                                                               addAnnotation(new TextAnnotation("T" + nbT++,
+                                                                               t, TextAnnotation.AnchorType.LOOP));
+                                                       } catch (Exception e) {
+                                                               e.printStackTrace();
+                                                       }
+                                               }
+                                               p.push(i + k - 1);
+                                       }
+
+                               } else {
+                                       if (j > i) {
+                                               p.push(j + 1);
+                                               p.push(i + 1);
+                                       }
+                               }
+                       }
+               }
+       }
+
+       public void autoAnnotateInteriorLoops() {
+               Stack<Integer> p = new Stack<Integer>();
+               p.push(0);
+               int nbT = 1;
+               while (!p.empty()) {
+                       int i = p.pop();
+                       if (i < _listeBases.size()) {
+                               ModeleBase mb = _listeBases.get(i);
+                               int j = mb.getElementStructure();
+                               if (j == -1) {
+                                       int k = i + 1;
+                                       ArrayList<ModeleBase> t = new ArrayList<ModeleBase>();
+                                       boolean terminal = true;
+                                       while ((k < getSize())
+                                                       && ((mb.getElementStructure() >= i) || (mb
+                                                                       .getElementStructure() == -1))) {
+                                               t.add(mb);
+                                               mb = _listeBases.get(k);
+                                               if ((mb.getElementStructure() == -1)
+                                                               || (mb.getElementStructure() < k))
+                                                       k++;
+                                               else {
+                                                       p.push(k);
+                                                       terminal = false;
+                                                       k = mb.getElementStructure();
+                                               }
+                                       }
+                                       if (mb.getElementStructure() != -1) {
+                                               if ((mb.getElementStructure() == i - 1) && !terminal) {
+                                                       try {
+                                                               t.add(_listeBases.get(i - 1));
+                                                               t.add(_listeBases.get(k - 1));
+                                                               addAnnotation(new TextAnnotation("I" + nbT++,
+                                                                               t, TextAnnotation.AnchorType.LOOP));
+                                                       } catch (Exception e) {
+                                                               e.printStackTrace();
+                                                       }
+                                                       p.push(k - 1);
+                                               }
+                                       }
+                               } else {
+                                       if (j > i) {
+                                               p.push(i + 1);
+                                       }
+                               }
+                       }
+               }
+       }
+
+       @SuppressWarnings("unchecked")
+       public TextAnnotation getAnnotation(TextAnnotation.AnchorType type,
+                       ModeleBase base) {
+               TextAnnotation result = null;
+               for (TextAnnotation t : _listeAnnotations) {
+                       if (t.getType() == type) {
+                               switch (type) {
+                               case BASE:
+                                       if (base == (ModeleBase) t.getAncrage())
+                                               return t;
+                                       break;
+                               case HELIX:
+                               case LOOP: {
+                                       ArrayList<ModeleBase> mbl = (ArrayList<ModeleBase>) t
+                                                       .getAncrage();
+                                       if (mbl.contains(base))
+                                               return t;
+                               }
+                                       break;
+                               }
+                       }
+               }
+               return result;
+       }
+
+       public void addChemProbAnnotation(ChemProbAnnotation cpa) {
+               //System.err.println(cpa.isOut());
+               _chemProbAnnotations.add(cpa);
+       }
+
+       public ArrayList<ChemProbAnnotation> getChemProbAnnotations() {
+               return _chemProbAnnotations;
+       }
+
+       public void setColorMapValues(Double[] values, ModeleColorMap cm) {
+               setColorMapValues(values, cm, false);
+       }
+
+       public void adaptColorMapToValues(ModeleColorMap cm) {
+               double min = Double.MAX_VALUE;
+               double max = Double.MIN_VALUE;
+               for (int i = 0; i < Math.min(_listeBases.size(), _listeBases.size()); i++) {
+                       ModeleBase mb = _listeBases.get(i);
+                       max = Math.max(max, mb.getValue());
+                       min = Math.min(min, mb.getValue());
+               }
+               cm.rescale(min, max);
+       }
+       
+       
+       private ArrayList<Double> loadDotPlot(StreamTokenizer st)
+       {
+               ArrayList<Double> result = new ArrayList<Double>();
+               try {
+                       boolean inSeq = false;
+                       String sequence = "";
+                       ArrayList<Double> accumulator = new ArrayList<Double>();
+                       int type = st.nextToken();
+                       Hashtable<Couple<Integer,Integer>,Double> BP = new Hashtable<Couple<Integer,Integer>,Double>();
+                       while (type != StreamTokenizer.TT_EOF) {
+                               switch (type) {
+                                       case (StreamTokenizer.TT_NUMBER):
+                                               accumulator.add(st.nval);
+                                               break;
+                                       case (StreamTokenizer.TT_EOL):
+                                               break;
+                                       case (StreamTokenizer.TT_WORD):
+                                               if (st.sval.equals("/sequence"))
+                                               {
+                                                       inSeq = true;
+                                               }
+                                               else if (st.sval.equals("ubox"))
+                                               {
+                                                       int i = accumulator.get(accumulator.size()-3).intValue()-1;
+                                                       int j = accumulator.get(accumulator.size()-2).intValue()-1;
+                                                       double val = accumulator.get(accumulator.size()-1);
+                                                       //System.err.println((char) type);                      
+                                                       BP.put(new Couple<Integer, Integer>(Math.min(i, j), Math.max(i, j)),val*val);
+                                                       accumulator.clear();
+                                               }
+                                               else if (inSeq)
+                                               {
+                                                       sequence += st.sval;
+                                               }
+                                               break;
+                                       case ')':
+                                               inSeq = false;
+                                       break;
+                               }
+                               type = st.nextToken();
+                       }
+                       for (int i = 0; i < getSize(); i++) {
+                               int j = getBaseAt(i).getElementStructure();
+                               if (j != -1) {
+                                       Couple<Integer, Integer> coor = new Couple<Integer, Integer>(
+                                                       Math.min(i, j), Math.max(i, j));
+                                       if (BP.containsKey(coor)) {
+                                               result.add(BP.get(coor));
+                                       } else {
+                                               result.add(0.);
+                                       }
+                               } else {
+                                       double acc = 1.0;
+                                       for (int k = 0; k < getSize(); k++) {
+                                               Couple<Integer, Integer> coor = new Couple<Integer, Integer>(
+                                                               Math.min(i, k), Math.max(i, k));
+                                               if (BP.containsKey(coor)) {
+                                                       acc -= BP.get(coor);
+                                               }
+                                       }
+                                       result.add(acc);
+                               }
+                       }
+               } catch (IOException e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+               return result;
+       }
+
+       public void readValues(Reader r, ModeleColorMap cm) {
+               try {
+                       StreamTokenizer st = new StreamTokenizer(r);
+                       st.eolIsSignificant(true);
+                       st.wordChars('/', '/');
+                       st.parseNumbers();
+                       ArrayList<Double> vals = new ArrayList<Double>();
+                       ArrayList<Double> curVals = new ArrayList<Double>();
+                       int type = st.nextToken();
+                       boolean isDotPlot = false;
+                       if (type=='%')
+                       {
+                               vals = loadDotPlot(st);
+                               isDotPlot = true;
+                       }
+                       else
+                       {       
+                               while (type != StreamTokenizer.TT_EOF) {
+                                       switch (type) {
+                                       case (StreamTokenizer.TT_NUMBER):
+                                               curVals.add(st.nval);
+                                               break;
+                                       case (StreamTokenizer.TT_EOL):
+                                               if (curVals.size() > 0) {
+                                                       vals.add(curVals.get(curVals.size()-1));
+                                                       curVals = new ArrayList<Double>();
+                                               }
+                                               break;
+                                       }
+                                       type = st.nextToken();
+                               }
+                               if (curVals.size() > 0)
+                                       vals.add(curVals.get(curVals.size()-1));
+                       }
+
+                       Double[] v = new Double[vals.size()];
+                       for (int i = 0; i < Math.min(vals.size(), getSize()); i++) {
+                               v[i] = vals.get(i);
+                       }
+                       setColorMapValues(v, cm, true);
+                       if (isDotPlot)
+                       {
+                               cm.setMinValue(0.0);
+                               cm.setMaxValue(1.0);
+                       }
+               } catch (IOException e) {
+                       e.printStackTrace();
+               }
+       }
+
+       public void setColorMapValues(Double[] values, ModeleColorMap cm,
+                       boolean rescaleColorMap) {
+               if (values.length > 0) {
+                       for (int i = 0; i < Math.min(values.length, _listeBases.size()); i++) {
+                               ModeleBase mb = _listeBases.get(i);
+                               mb.setValue(values[i]);
+                       }
+                       if (rescaleColorMap) {
+                               adaptColorMapToValues(cm);
+                       }
+               }
+       }
+
+       public Double[] getColorMapValues() {
+               Double[] values = new Double[_listeBases.size()];
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       values[i] = _listeBases.get(i).getValue();
+               }
+               return values;
+       }
+
+       public void rescaleColorMap(ModeleColorMap cm) {
+               Double max = Double.MIN_VALUE;
+               Double min = Double.MAX_VALUE;
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       Double value = _listeBases.get(i).getValue();
+                       max = Math.max(max, value);
+                       min = Math.min(min, value);
+               }
+               cm.rescale(min, max);
+       }
+
+       public void addBase(ModeleBase mb) {
+               _listeBases.add(mb);
+       }
+
+       public void setSequence(String s) {
+               setSequence(RNA.explodeSequence(s));
+       }
+
+       public void setSequence(List<String> s) {
+               int i = 0;
+               int j = 0;
+               while ((i < s.size()) && (j < _listeBases.size())) {
+                       ModeleBase mb = _listeBases.get(j);
+                       if (mb instanceof ModeleBaseNucleotide) {
+                               ((ModeleBaseNucleotide) mb).setBase(s.get(i));
+                               i++;
+                               j++;
+                       } else if (mb instanceof ModeleBasesComparison) {
+                               ((ModeleBasesComparison) mb)
+                                               .setBase1(((s.get(i).length() > 0) ? s.get(i).charAt(0)
+                                                               : ' '));
+                               ((ModeleBasesComparison) mb)
+                                               .setBase2(((s.get(i + 1).length() > 0) ? s.get(i + 1)
+                                                               .charAt(0) : ' '));
+                               i += 2;
+                               j++;
+                       } else
+                               j++;
+               }
+               for (i = _listeBases.size(); i < s.size(); i++) {
+                       _listeBases.add(new ModeleBaseNucleotide(s.get(i), i));
+               }
+       }
+
+       public void eraseSequence() {
+               int j = 0;
+               while ((j < _listeBases.size())) {
+                       ModeleBase mb = _listeBases.get(j);
+                       if (mb instanceof ModeleBaseNucleotide) {
+                               ((ModeleBaseNucleotide) mb).setBase("");
+                               j++;
+                       } else if (mb instanceof ModeleBasesComparison) {
+                               ((ModeleBasesComparison) mb).setBase1(' ');
+                               ((ModeleBasesComparison) mb).setBase2(' ');
+                               j++;
+                       } else
+                               j++;
+               }
+       }
+
+       public RNA clone() {
+               try {
+                       ByteArrayOutputStream out = new ByteArrayOutputStream();
+                       ObjectOutputStream oout = new ObjectOutputStream(out);
+                       oout.writeObject(this);
+
+                       ObjectInputStream in = new ObjectInputStream(
+                                       new ByteArrayInputStream(out.toByteArray()));
+                       return (RNA) in.readObject();
+               } catch (Exception e) {
+                       throw new RuntimeException("cannot clone class ["
+                                       + this.getClass().getName() + "] via serialization: "
+                                       + e.toString());
+               }
+       }
+
+       /**
+        * Returns the base at index <code>index</code>. Indices are contiguous in
+        * the sequence over an interval <code>[0,this.getSize()-1]</code>, where
+        * <code>n</code> is the length of the sequence.
+        * 
+        * @param index
+        *            The index, <code>0 &le; index < this.getSize()</code>, of the
+        *            base model
+        * @return The base model of index <code>index</code>
+        */
+       public ModeleBase getBaseAt(int index) {
+               return this._listeBases.get(index);
+       }
+
+       /**
+        * Returns the set of bases of indices in <code>indices</code>. Indices are
+        * contiguous in the sequence, and belong to an interval
+        * <code>[0,n-1]</code>, where <code>n</code> is the length of the sequence.
+        * 
+        * @param indices
+        *            A Collection of indices <code>i</code>,
+        *            <code>0 &le; index < this.getSize()</code>, where some base
+        *            models are found.
+        * @return A list of base model of indices in <code>indices</code>
+        */
+       public ArrayList<ModeleBase> getBasesAt(
+                       Collection<? extends Integer> indices) {
+               ArrayList<ModeleBase> mbs = new ArrayList<ModeleBase>();
+               for (int i : indices) {
+                       mbs.add(getBaseAt(i));
+               }
+               return mbs;
+       }
+
+       public ArrayList<ModeleBase> getBasesBetween(int from, int to) {
+               ArrayList<ModeleBase> mbs = new ArrayList<ModeleBase>();
+               int bck = Math.min(from, to);
+               to = Math.max(from, to);
+               from = bck;
+               for (int i = from; i <= to; i++) {
+                       mbs.add(getBaseAt(i));
+               }
+               return mbs;
+       }
+
+       public void addHighlightRegion(HighlightRegionAnnotation n) {
+               _listeRegionHighlights.add(n);
+       }
+
+       public void removeHighlightRegion(HighlightRegionAnnotation n) {
+               _listeRegionHighlights.remove(n);
+       }
+
+       public void removeChemProbAnnotation(ChemProbAnnotation a) {
+               _chemProbAnnotations.remove(a);
+       }
+
+       public void clearChemProbAnnotations() {
+               _chemProbAnnotations.clear();
+       }
+
+       public void addHighlightRegion(int from, int to, Color fill, Color outline,
+                       double radius) {
+               _listeRegionHighlights.add(new HighlightRegionAnnotation(
+                               getBasesBetween(from, to), fill, outline, radius));
+       }
+
+       public void addHighlightRegion(int from, int to) {
+               _listeRegionHighlights.add(new HighlightRegionAnnotation(
+                               getBasesBetween(from, to)));
+       }
+
+       public ArrayList<HighlightRegionAnnotation> getHighlightRegion() {
+               return _listeRegionHighlights;
+       }
+
+       /**
+        * Rotates the RNA coordinates by a certain angle
+        * 
+        * @param angleDegres
+        *            Rotation angle, in degrees
+        */
+       public void globalRotation(Double angleDegres) {
+               if (_listeBases.size() > 0) {
+
+                       // angle en radian
+                       Double angle = angleDegres * Math.PI / 180;
+
+                       // initialisation du minimum et dumaximum
+                       Double maxX = _listeBases.get(0).getCoords().x;
+                       Double maxY = _listeBases.get(0).getCoords().y;
+                       Double minX = _listeBases.get(0).getCoords().x;
+                       Double minY = _listeBases.get(0).getCoords().y;
+                       // mise a jour du minimum et du maximum
+                       for (int i = 0; i < _listeBases.size(); i++) {
+                               if (_listeBases.get(i).getCoords().getX() < minX)
+                                       minX = _listeBases.get(i).getCoords().getX();
+                               if (_listeBases.get(i).getCoords().getY() < minY)
+                                       minY = _listeBases.get(i).getCoords().getY();
+                               if (_listeBases.get(i).getCoords().getX() > maxX)
+                                       maxX = _listeBases.get(i).getCoords().getX();
+                               if (_listeBases.get(i).getCoords().getX() > maxY)
+                                       maxY = _listeBases.get(i).getCoords().getY();
+                       }
+                       // creation du point central
+                       Point2D.Double centre = new Point2D.Double((maxX - minX) / 2,
+                                       (maxY - minY) / 2);
+                       Double x, y;
+                       for (int i = 0; i < _listeBases.size(); i++) {
+                               // application de la rotation au centre de chaque base
+                               // x' = cos(theta)*(x-xc) - sin(theta)*(y-yc) + xc
+                               x = Math.cos(angle)
+                                               * (_listeBases.get(i).getCenter().getX() - centre.x)
+                                               - Math.sin(angle)
+                                               * (_listeBases.get(i).getCenter().getY() - centre.y)
+                                               + centre.x;
+                               // y' = sin(theta)*(x-xc) + cos(theta)*(y-yc) + yc
+                               y = Math.sin(angle)
+                                               * (_listeBases.get(i).getCenter().getX() - centre.x)
+                                               + Math.cos(angle)
+                                               * (_listeBases.get(i).getCenter().getY() - centre.y)
+                                               + centre.y;
+                               _listeBases.get(i).setCenter(new Point2D.Double(x, y));
+
+                               // application de la rotation au coordonnees de chaque
+                               // base
+                               // x' = cos(theta)*(x-xc) - sin(theta)*(y-yc) + xc
+                               x = Math.cos(angle)
+                                               * (_listeBases.get(i).getCoords().getX() - centre.x)
+                                               - Math.sin(angle)
+                                               * (_listeBases.get(i).getCoords().getY() - centre.y)
+                                               + centre.x;
+                               // y' = sin(theta)*(x-xc) + cos(theta)*(y-yc) + yc
+                               y = Math.sin(angle)
+                                               * (_listeBases.get(i).getCoords().getX() - centre.x)
+                                               + Math.cos(angle)
+                                               * (_listeBases.get(i).getCoords().getY() - centre.y)
+                                               + centre.y;
+                               _listeBases.get(i).setCoords(new Point2D.Double(x, y));
+                       }
+               }
+       }
+       
+       private static double MIN_DISTANCE = 10.;
+       
+       
+       /**
+        * Flip an helix around its supporting base
+        */
+       public void flipHelix(Point h) {
+               if (h.x!=-1 && h.y!=-1 && h.x!=h.y)
+               {
+                       int hBeg=h.x;
+                       int hEnd=h.y;
+                       Point2D.Double A = getCoords(hBeg);
+                       Point2D.Double B = getCoords(hEnd);
+                       Point2D.Double AB = new Point2D.Double(B.x - A.x, B.y - A.y);
+                       double normAB = Math.sqrt(AB.x * AB.x + AB.y * AB.y);
+                       // Creating a coordinate system centered on A and having
+                       // unit x-vector Ox.
+                       Point2D.Double O = A;
+                       Point2D.Double Ox = new Point2D.Double(AB.x / normAB, AB.y / normAB);
+                       Hashtable<Integer,Point2D.Double> old = new Hashtable<Integer,Point2D.Double>(); 
+                       for (int i = hBeg + 1; i < hEnd; i++) {
+                               Point2D.Double P = getCoords(i);
+                               Point2D.Double nP = project(O, Ox, P);
+                               old.put(i, nP);
+                               setCoord(i, nP);
+                               Point2D.Double Center = getCenter(i);
+                               setCenter(i, project(O, Ox, Center));
+                       }
+               }
+       }
+
+       public static Point2D.Double project(Point2D.Double O, Point2D.Double Ox,
+                       Point2D.Double C) {
+               Point2D.Double OC = new Point2D.Double(C.x - O.x, C.y - O.y);
+               // Projection of OC on OI => OX
+               double normOX = (Ox.x * OC.x + Ox.y * OC.y);
+               Point2D.Double OX = new Point2D.Double((normOX * Ox.x), (normOX * Ox.y));
+               // Portion of OC orthogonal to Ox => XC
+               Point2D.Double XC = new Point2D.Double(OC.x - OX.x, OC.y - OX.y);
+               // Reflexive image of C with respect to Ox => CP
+               Point2D.Double OCP = new Point2D.Double(OX.x - XC.x, OX.y - XC.y);
+               Point2D.Double CP = new Point2D.Double(O.x + OCP.x, O.y + OCP.y);
+               return CP;
+       }
+
+
+       public boolean testDirectionality(int i, int j, int k) {
+
+               // Which direction are we heading toward?
+               Point2D.Double pi = getCoords(i);
+               Point2D.Double pj = getCoords(j);
+               Point2D.Double pk = getCoords(k);
+               return testDirectionality(pi, pj, pk);
+       }
+
+       public static boolean testDirectionality(Point2D.Double pi,
+                       Point2D.Double pj, Point2D.Double pk) {
+
+               // Which direction are we heading toward?
+               double test = (pj.x - pi.x) * (pk.y - pj.y) - (pj.y - pi.y)
+                               * (pk.x - pj.x);
+               return test < 0.0;
+       }
+
+       public double getOrientation() {
+               double maxDist = Double.MIN_VALUE;
+               double angle = 0;
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       ModeleBase b1 = _listeBases.get(i);
+                       for (int j = i + 1; j < _listeBases.size(); j++) {
+                               ModeleBase b2 = _listeBases.get(j);
+                               Point2D.Double p1 = b1._coords.toPoint2D();
+                               Point2D.Double p2 = b2._coords.toPoint2D();
+                               double dist = p1.distance(p2);
+                               if (dist > maxDist) {
+                                       maxDist = dist;
+                                       angle = computeAngle(p1, p2);
+                               }
+                       }
+               }
+               return angle;
+       }
+
+       public boolean hasVirtualLoops() {
+               boolean consecutiveBPs = false;
+               for (int i = 0; i < _listeBases.size(); i++) {
+                       int j = _listeBases.get(i).getElementStructure();
+                       if (j == i + 1) {
+                               consecutiveBPs = true;
+                       }
+
+               }
+               return ((_drawMode != DRAW_MODE_LINEAR)
+                               && (_drawMode != DRAW_MODE_CIRCULAR) && (consecutiveBPs));
+       }
+
+       public String getHTMLDescription() {
+               String result = "<table>";
+               result += "<tr><td><b>Name:</b></td><td>" + this._name + "</td></tr>";
+               result += "<tr><td><b>Length:</b></td><td>" + this.getSize()
+                               + " nts</td></tr>";
+               result += "<tr><td><b>Base-pairs:</b></td><td>"
+                               + this.getAllBPs().size() + " </td></tr>";
+               return result + "</table>";
+       }
+
+       public String getID() {
+               return _id;
+       }
+
+       public void setID(String id) {
+               _id = id;
+       }
+
+       public static ArrayList<Integer> getGapPositions(String gapString) {
+               ArrayList<Integer> result = new ArrayList<Integer>();
+               for (int i = 0; i < gapString.length(); i++) {
+                       char c = gapString.charAt(i);
+                       if (c == '.' || c == ':') {
+                               result.add(i);
+                       }
+               }
+               return result;
+       }
+
+       public RNA restrictTo(String gapString) {
+               return restrictTo(getGapPositions(gapString));
+       }
+
+       public RNA restrictTo(ArrayList<Integer> positions) {
+               RNA result = new RNA();
+               String oldSeq = this.getSeq();
+               String newSeq = "";
+               HashSet<Integer> removedPos = new HashSet<Integer>(positions);
+               int[] matching = new int[oldSeq.length()];
+               int j = 0;
+               for (int i = 0; i < oldSeq.length(); i++) {
+                       matching[i] = j;
+                       if (!removedPos.contains(i)) {
+                               newSeq += oldSeq.charAt(i);
+                               j++;
+                       }
+               }
+               result.setRNA(newSeq);
+               for (ModeleBP m : getAllBPs()) {
+                       if (removedPos.contains(m.getIndex5())
+                                       || removedPos.contains(m.getIndex3())) {
+                               int i5 = matching[m.getIndex5()];
+                               int i3 = matching[m.getIndex3()];
+                               ModeleBP msbp = new ModeleBP(result.getBaseAt(i5),
+                                               result.getBaseAt(i3), m.getEdgePartner5(),
+                                               m.getEdgePartner3(), m.getStericity());
+                               result.addBP(i5, i3, msbp);
+                       }
+               }
+               return result;
+       }
+
+       public void rescale(double d) {
+               for (ModeleBase mb : _listeBases) {
+                       mb._coords.x *= d;
+                       mb._coords.y *= d;
+                       mb._center.x *= d;
+                       mb._center.y *= d;
+               }
+       }
+
+       /**
+        * Necessary for DrawRNATemplate (which is why the method is
+        * package-visible).
+        */
+       ArrayList<ModeleBase> getListeBases() {
+               return _listeBases;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/StructureTemp.java b/src2/fr/orsay/lri/varna/models/rna/StructureTemp.java
new file mode 100644 (file)
index 0000000..40063ba
--- /dev/null
@@ -0,0 +1,43 @@
+package fr.orsay.lri.varna.models.rna;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+public class StructureTemp  implements Serializable{
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -436852923461989105L;
+       private ArrayList<ModeleStrand> _struct = new ArrayList<ModeleStrand>();
+       
+       public StructureTemp(){
+               
+       }
+       
+       public void addStrand(ModeleStrand ms){
+               this._struct.add(ms);
+               
+       }
+       
+       public int sizeStruct() {
+               return this._struct.size();
+       }
+       
+       public ModeleStrand getStrand(int a) {
+               return this._struct.get(a);
+       }
+
+       public ArrayList<ModeleStrand> getListStrands() {
+               return _struct;
+       }
+
+       public void clearListStrands() {
+               this._struct.clear();
+       }
+       
+       public boolean isEmpty() {
+               return this._struct.isEmpty();
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/VARNAPoint.java b/src2/fr/orsay/lri/varna/models/rna/VARNAPoint.java
new file mode 100644 (file)
index 0000000..8929642
--- /dev/null
@@ -0,0 +1,74 @@
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.geom.Point2D;
+import java.awt.geom.Point2D.Double;
+import java.io.Serializable;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+public class VARNAPoint implements Serializable {
+
+       private static final long serialVersionUID = 8815373295131046029L;
+       
+       public double x = 0.0;
+       public double y = 0.0;
+       
+       public void toXML(TransformerHandler hd) throws SAXException
+       {
+               toXML(hd,"");
+       }       
+       
+
+       public static String XML_ELEMENT_NAME = "p";
+       public static String XML_VAR_ROLE_NAME = "r";
+       public static String XML_VAR_X_NAME = "x";
+       public static String XML_VAR_Y_NAME = "y";
+
+       public void toXML(TransformerHandler hd, String role) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               if (!role.equals(""))
+               {
+                       atts.addAttribute("","",XML_VAR_ROLE_NAME,"CDATA",""+role);
+               }
+               atts.addAttribute("","",XML_VAR_X_NAME,"CDATA",""+x);
+               atts.addAttribute("","",XML_VAR_Y_NAME,"CDATA",""+y);
+               hd.startElement("","",XML_ELEMENT_NAME,atts);
+               hd.endElement("","",XML_ELEMENT_NAME);
+       }       
+
+       public VARNAPoint()
+       { this(0.0,0.0); }
+       
+       public VARNAPoint(double px, double py)
+    {
+       x = px; y = py;
+    }
+    public VARNAPoint(Point2D.Double p)
+    {
+       this(p.x,p.y);
+    }
+    public double getX()
+    {
+       return x;
+    }
+    
+    public double getY()
+    {
+       return y;
+    }
+    
+    public Point2D.Double toPoint2D()
+    {
+       return new Point2D.Double(x,y);
+    }
+    
+    public String toString()
+    {
+       return "("+x+","+y+")" ;
+    }
+}
diff --git a/src2/fr/orsay/lri/varna/models/rna/VARNASecDraw.java b/src2/fr/orsay/lri/varna/models/rna/VARNASecDraw.java
new file mode 100644 (file)
index 0000000..8a9e06e
--- /dev/null
@@ -0,0 +1,896 @@
+package fr.orsay.lri.varna.models.rna;
+
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Area;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.PathIterator;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.Random;
+import java.util.Stack;
+import java.util.Vector;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+public class VARNASecDraw {
+       public static VARNAPanel _vp = null;
+
+       
+       public abstract class Portion
+       {
+               public abstract ArrayList<Integer> getBaseList();
+               public abstract int getNumBases();
+               public abstract GeneralPath getOutline(RNA r);
+               
+       };
+       
+       public class UnpairedPortion extends Portion
+       {
+               int _pos;
+               int _len;
+               public UnpairedPortion(int pos, int len)
+               {
+                       _len = len;
+                       _pos = pos;
+               }
+               @Override
+               public ArrayList<Integer> getBaseList() {
+                       // TODO Auto-generated method stub
+                       return null;
+               }               
+               public String toString()
+               {
+                       return "U["+_pos+","+(_pos+_len-1)+"]";
+               }
+
+               public int getNumBases() {
+                       return _len;
+               }
+
+               
+               public GeneralPath getOutline(RNA r) {
+                       
+                       GeneralPath gp = new GeneralPath();
+                       ArrayList<ModeleBase> l = r.get_listeBases();
+                       Point2D.Double p0 = l.get(_pos).getCoords();
+                       gp.moveTo((float)p0.x, (float)p0.y);
+                       for (int i=1;i<_len;i++)
+                       {
+                               Point2D.Double p = l.get(_pos+i).getCoords();
+                               gp.lineTo((float)p.x, (float)p.y);
+                       }
+                       return gp;
+               }
+       };
+       
+       public class PairedPortion extends Portion
+       {
+               int _pos1;
+               int _pos2;
+               int _len;
+               RNATree _r;
+               
+               public PairedPortion(int pos1,int pos2, int len, RNATree r)
+               {
+                       _pos1 = pos1;
+                       _pos2 = pos2;
+                       _len = len;
+                       _r =r;
+               }
+
+               @Override
+               public ArrayList<Integer> getBaseList() {
+                       // TODO Auto-generated method stub
+                       return null;
+               }
+               
+               public String toString()
+               {
+                       return "H["+_pos1+","+(_pos1+_len-1)+"]["+(_pos2-_len+1)+","+(_pos2)+"]\n"+_r.toString();
+               }
+
+               @Override
+               public int getNumBases() {
+                       return 2*_len;
+               }
+
+               public GeneralPath getLocalOutline(RNA r) {
+                       GeneralPath gp = new GeneralPath();
+                       if (_len>0)
+                       {
+                               ArrayList<ModeleBase> l = r.get_listeBases();
+                               Point2D.Double p1 = l.get(_pos1).getCoords();
+                               Point2D.Double p2 = l.get(_pos1+_len-1).getCoords();
+                               Point2D.Double p3 = l.get(_pos2-_len+1).getCoords();
+                               Point2D.Double p4 = l.get(_pos2).getCoords();
+                               gp.moveTo((float)p1.x, (float)p1.y);
+                               gp.lineTo((float)p2.x, (float)p2.y);
+                               gp.lineTo((float)p3.x, (float)p3.y);
+                               gp.lineTo((float)p4.x, (float)p4.y);
+                       }
+                       return gp;
+               }
+
+
+               public GeneralPath getOutline(RNA r) {
+                       return getOutline(r,false);
+               }
+
+               public GeneralPath getOutline(RNA r, boolean local) {
+                       ArrayList<ModeleBase> l = r.get_listeBases();
+                       Point2D.Double p1 = l.get(_pos1).getCoords();
+                       Point2D.Double p2 = l.get(_pos1+_len-1).getCoords();
+                       Point2D.Double p3 = l.get(_pos2-_len+1).getCoords();
+                       Point2D.Double p4 = l.get(_pos2).getCoords();
+                       GeneralPath gp = new GeneralPath();
+                       gp.moveTo((float)p1.x, (float)p1.y);
+                       gp.lineTo((float)p2.x, (float)p2.y);
+                       if (!local)
+                               gp.append(_r.getOutline(r), true);
+                       gp.lineTo((float)p3.x, (float)p3.y);
+                       gp.lineTo((float)p4.x, (float)p4.y);
+                       
+                       return gp;
+                       
+               }
+       };
+       public  int   _depth = 0;
+
+       
+       public class RNATree
+       {
+               ArrayList<Portion> _portions = new ArrayList<Portion>();
+               int _numPairedPortions=0;
+               public RNATree()
+               {
+                       
+               }
+               
+               
+               public void addPortion(Portion p)
+               {
+                       _portions.add(p);
+                       if (p instanceof PairedPortion)
+                       {
+                               _numPairedPortions++;
+                       }
+               }
+
+               public int getNumPortions()
+               {
+                       return _portions.size();
+               }
+
+               public Portion getPortion(int i)
+               {
+                       return _portions.get(i);
+               }
+               
+               public String toString()
+               {
+                       String result = "";
+                       _depth++;
+                       for (int i=0;i<_portions.size();i++ )
+                       {
+                               result += String.format("%1$#" + _depth + "s", ' ');
+                               result += _portions.get(i).toString();
+                               if (i<_portions.size()-1)
+                                 result += "\n";
+                       }
+                       _depth--;
+                       return result;
+               }
+
+               public GeneralPath getOutline(RNA r) {
+                       GeneralPath result = new GeneralPath();
+                       for (int i=0;i<_portions.size();i++)
+                       {
+                               result.append(_portions.get(i).getOutline(r),true);
+                       }
+                       return result;
+               }
+       };
+       
+       
+       private void buildTree(int i, int j, RNATree parent,  RNA r) 
+       {
+               //LinkedList<BuildTreeArgs> s = new LinkedList<BuildTreeArgs>();
+               //s.add(new BuildTreeArgs(xi, xj, xparent,xr));
+               //while(s.size()!=0)
+               //{
+                       
+                       //BuildTreeArgs a = s.removeLast();
+                       if (i >= j) {
+                               parent.addPortion(new UnpairedPortion(i,j-i+1));
+                       }
+                       // BasePaired
+                       if (r.get_listeBases().get(i).getElementStructure() == j) 
+                       {
+                               int i1 = i;
+                               int j1 = j;
+                               boolean over = false;
+                               while( (i+1<r.get_listeBases().size())  &&  (j-1>=0)&&  (i+1<=j-1) && !over)
+                               {
+                                       if (r.get_listeBases().get(i).getElementStructure() != j)
+                                       { over = true; }
+                                       else
+                                       { i++;j--; }
+                               }
+                               int i2 = i;
+                               int j2 = j;
+                               RNATree t = new RNATree();
+                               if (i<j-1)
+                                 buildTree(i2,j2,t,r);
+                               PairedPortion p = new PairedPortion(i1,j1,i2-i1,t);
+                               parent.addPortion(p);
+                       } else 
+                       {
+                               int k = i;
+                               int l;
+                               int start = k;
+                               int len = 0;
+                               while (k <= j) {
+                                       l = r.get_listeBases().get(k).getElementStructure();
+                                       if (l != -1) 
+                                       {
+                                               if (len>0)
+                                               { parent.addPortion(new UnpairedPortion(start,len)); }
+                                               buildTree(k, l, parent,  r);
+                                               k = l + 1;
+                                               start = k;
+                                               len = 0;
+                                       } else {
+                                               len++;
+                                               k++;
+                                       }
+                               }
+                               if (len>0)
+                               {
+                                       parent.addPortion(new UnpairedPortion(start,len));
+                               }
+                       }
+               }
+
+       /*
+       public void drawTree(double x0, double y0, RNATree t, double dir, RNA r, double straightness)
+       {
+               boolean collision = true;
+               double x=x0;
+               double y=y0;
+               double multRadius = 1.0;
+               double initCirc = r.BASE_PAIR_DISTANCE+r.LOOP_DISTANCE;
+               for (int i=0;i<t.getNumPortions();i++ )
+               {
+                       Portion p = t.getPortion(i);
+                       if (p instanceof PairedPortion)
+                       {
+                               initCirc += (r.BASE_PAIR_DISTANCE+r.LOOP_DISTANCE);                             
+                       }
+                       else
+                       {
+                               initCirc += r.LOOP_DISTANCE*(p.getNumBases());
+                       }
+               }
+               while(collision)
+               {
+                               double totCirc = r.BASE_PAIR_DISTANCE+straightness*r.LOOP_DISTANCE;
+                               for (int i=0;i<t.getNumPortions();i++ )
+                               {
+                                       Portion p = t.getPortion(i);
+                                       if (p instanceof PairedPortion)
+                                       {
+                                               totCirc += (r.BASE_PAIR_DISTANCE+r.LOOP_DISTANCE);                              
+                                       }
+                                       else
+                                       {
+                                               double mod = 1.0;
+                                               if ((i==0) || (i==t.getNumPortions()-1))
+                                                       mod = straightness;
+                                                 totCirc += mod*r.LOOP_DISTANCE*(p.getNumBases());
+                                       }
+                               }
+                               double radius = multRadius*initCirc/(2.0*Math.PI);
+                       //radius = 2.0;
+                       x = x0+radius*Math.cos(dir+Math.PI);
+                       y = y0+radius*Math.sin(dir+Math.PI);
+                       dir += 2.0*Math.PI;
+                       double angleIncr = (2.0*Math.PI)/(totCirc);
+                       double circ = r.BASE_PAIR_DISTANCE/2.0+straightness*r.LOOP_DISTANCE;
+                       double ndir;
+                       ArrayList<GeneralPath> shapes = new ArrayList<GeneralPath>(); 
+                       for (int i=0;i<t.getNumPortions();i++ )
+                       {
+                               Portion p = t.getPortion(i);
+                               if (p instanceof PairedPortion)
+                               {
+                                       circ+=r.BASE_PAIR_DISTANCE/2.0;
+                                       ndir = dir + circ*angleIncr;
+                                       PairedPortion pp = (PairedPortion) p; 
+                                       for(int j=0;j<pp._len;j++)
+                                       {
+                                               int i1 = pp._pos1+j;
+                                               int i2 = pp._pos2-j;
+                                               double vx = Math.cos(ndir);
+                                               double vy = Math.sin(ndir);
+                                               double nx = x+((j*r.LOOP_DISTANCE+radius)*vx);
+                                               double ny = y+((j*r.LOOP_DISTANCE+radius)*vy);
+                                               r.get_listeBases().get(i1).set_coords(new Point2D.Double(nx+r.BASE_PAIR_DISTANCE*vy/ 2.0,ny-r.BASE_PAIR_DISTANCE*vx/ 2.0));
+                                               r.get_listeBases().get(i2).set_coords(new Point2D.Double(nx-r.BASE_PAIR_DISTANCE*vy/ 2.0,ny+r.BASE_PAIR_DISTANCE*vx/ 2.0));
+                                       }
+                                       double nx = x+(((pp._len-1)*r.LOOP_DISTANCE+radius)*Math.cos(ndir));
+                                       double ny = y+(((pp._len-1)*r.LOOP_DISTANCE+radius)*Math.sin(ndir));
+                                       drawTree(nx, ny, pp._r, ndir+Math.PI, r, straightness);
+                                       shapes.add(pp.getOutline(r));
+                                       circ += r.LOOP_DISTANCE + r.BASE_PAIR_DISTANCE/2.0;
+                               }
+                               else if (p instanceof UnpairedPortion)
+                               {
+                                       UnpairedPortion up = (UnpairedPortion) p;
+                                       double mod = 1.0;
+                                       if ((i==0) || (i==t.getNumPortions()-1))
+                                                 mod = straightness;
+                                       for(int j=0;j<up._len;j++)
+                                       {
+                                               ndir = dir + circ*angleIncr;
+                                               double vx = Math.cos(ndir);
+                                               double vy = Math.sin(ndir);
+                                               double nx = x+((radius)*vx);
+                                               double ny = y+((radius)*vy);
+                                               r.get_listeBases().get(up._pos+j).set_coords(new Point2D.Double(nx,ny));
+                                               circ += mod*r.LOOP_DISTANCE;
+                                       }
+                               }
+                               //System.out.println(dir);
+                       }
+                       circ += r.BASE_PAIR_DISTANCE/2.0;
+                       System.out.println(""+circ+"/"+totCirc);
+                       if(shapes.size()>0)
+                       {
+                               collision = false;
+                               for (int i=0;(i<shapes.size()) && !collision;i++)
+                               {       
+                                       Area a1 = new Area(shapes.get(i));
+                                       for (int j=i+1;(j<shapes.size())&& !collision;j++)
+                                       {       
+                                               Area a2 = new Area(shapes.get(j));
+                                               a1.intersect(a2);
+                                               if (!a1.isEmpty())
+                                               {
+                                                       collision = true;
+                                               }
+                                       }
+                               }
+                               if (collision)
+                               {
+                                       straightness *= 1.2;
+                                       multRadius *= 1.5;
+                               }
+                                       
+                       }
+                       else 
+                       {
+                               collision = false;
+                       }
+               }
+       }
+       */
+       
+       public int[] nextPlacement(int[] p) throws Exception
+       {
+                //System.out.println(Arrays.toString(p));
+               int i=p.length-1;
+               int prev = MAX_NUM_DIR;
+               boolean stop = false;
+               while((i>=0) && !stop)
+               {
+                       if (p[i]==prev-1)
+                       { 
+                               prev = p[i]; 
+                               i--; 
+                       }
+                       else
+                       { stop = true; }
+               }
+               if (i<0)
+                       throw new Exception("No more placement available"); 
+               p[i]++;
+               i++;
+               while(i<p.length)
+               {
+                       p[i] = p[i-1]+1;
+                       i++;
+               }
+                //System.out.println(Arrays.toString(p));              
+               return p;
+       }
+       
+       
+       public void drawTree(double x0, double y0, RNATree t, double dir, RNA r) throws Exception
+       {
+               boolean collision = true;
+               double x=x0;
+               double y=y0;
+               int numHelices = 0;
+               int nbHel = 1;
+               int nbUn = 0;
+               double totCirc = r.BASE_PAIR_DISTANCE+r.LOOP_DISTANCE;
+               for (int i=0;i<t.getNumPortions();i++ )
+               {
+                       Portion p = t.getPortion(i);
+                       if (p instanceof PairedPortion)
+                       {
+                               totCirc += (r.BASE_PAIR_DISTANCE+r.LOOP_DISTANCE);
+                               nbHel += 1;
+                       }
+                       else
+                       {
+                               totCirc += r.LOOP_DISTANCE*(p.getNumBases());
+                               nbUn += p.getNumBases()+1;
+                       }
+               }
+               double radius = r.determineRadius(nbHel, nbUn, totCirc/(2.0*Math.PI));
+
+               for (int i=0;i<t.getNumPortions();i++ )
+               {
+                       Portion p = t.getPortion(i);
+                       if (p instanceof PairedPortion)
+                       {
+                               numHelices++;                           
+                       }
+               }
+               int[] placement = new int[numHelices];
+               double inc = ((double)MAX_NUM_DIR)/((double)numHelices+1);
+               double val = inc;
+               for (int i=0;i<numHelices;i++ )
+               {
+                       placement[i] = (int)Math.round(val);
+                       val += inc;
+               }
+               System.out.println();
+               double angleIncr = 2.0*Math.PI/(double)MAX_NUM_DIR;
+               while(collision)
+               {
+                       x = x0+radius*Math.cos(dir+Math.PI);
+                       y = y0+radius*Math.sin(dir+Math.PI);
+                       ArrayList<GeneralPath> shapes = new ArrayList<GeneralPath>();
+                       int curH = 0;
+                       for (int i=0;i<t.getNumPortions();i++ )
+                       {
+                               Portion p = t.getPortion(i);
+                               if (p instanceof PairedPortion)
+                               {
+                                       double ndir = dir + placement[curH]*angleIncr;
+                                       curH++;
+                                       PairedPortion pp = (PairedPortion) p; 
+                                       for(int j=0;j<pp._len;j++)
+                                       {
+                                               int i1 = pp._pos1+j;
+                                               int i2 = pp._pos2-j;
+                                               double vx = Math.cos(ndir);
+                                               double vy = Math.sin(ndir);
+                                               double nx = x+(((j)*r.LOOP_DISTANCE+radius)*vx);
+                                               double ny = y+(((j)*r.LOOP_DISTANCE+radius)*vy);
+                                               r.get_listeBases().get(i1).setCoords(new Point2D.Double(nx+r.BASE_PAIR_DISTANCE*vy/ 2.0,ny-r.BASE_PAIR_DISTANCE*vx/ 2.0));
+                                               r.get_listeBases().get(i2).setCoords(new Point2D.Double(nx-r.BASE_PAIR_DISTANCE*vy/ 2.0,ny+r.BASE_PAIR_DISTANCE*vx/ 2.0));
+                                       }
+                                       double nx = x+(((pp._len-1)*r.LOOP_DISTANCE+radius)*Math.cos(ndir));
+                                       double ny = y+(((pp._len-1)*r.LOOP_DISTANCE+radius)*Math.sin(ndir));
+                                       drawTree(nx, ny, pp._r, ndir+Math.PI, r);
+                                       shapes.add(pp.getOutline(r));
+                               }
+                               else if (p instanceof UnpairedPortion)
+                               {
+                                       UnpairedPortion up = (UnpairedPortion) p;
+                                       for(int j=0;j<up._len;j++)
+                                       {
+                                               /*ndir = dir + circ*angleIncr;
+                                                       double vx = Math.cos(ndir);
+                                                       double vy = Math.sin(ndir);
+                                                       double nx = x+((radius)*vx);
+                                                       double ny = y+((radius)*vy);
+                                                       r.get_listeBases().get(up._pos+j).set_coords(new Point2D.Double(nx,ny));
+                                                       circ += mod*r.LOOP_DISTANCE;*/
+                                               r.get_listeBases().get(up._pos+j).setCoords(new Point2D.Double(x,y));
+                                       }
+                               }
+                               //System.out.println(dir);
+                       }
+                       if(shapes.size()>0)
+                       {
+                               collision = false;
+                               for (int i=0;(i<shapes.size()) && !collision;i++)
+                               {       
+                                       Area a1 = new Area(shapes.get(i));
+                                       for (int j=i+1;(j<shapes.size())&& !collision;j++)
+                                       {       
+                                               Area a2 = new Area(shapes.get(j));
+                                               a1.intersect(a2);
+                                               if (!a1.isEmpty())
+                                               {
+                                                       collision = true;
+                                               }
+                                       }
+                               }
+                               if (collision)
+                               {
+                                       placement = nextPlacement(placement);
+                               }
+                                       
+                       }
+                       else 
+                       {
+                               collision = false;
+                       }
+               }
+       }
+
+
+       private class HelixEmbedding
+       {
+               private GeneralPath _clip;
+               Point2D.Double _support;
+               ArrayList<HelixEmbedding> _children = new ArrayList<HelixEmbedding>();
+               ArrayList<Integer> _indices = new ArrayList<Integer>();
+               PairedPortion _p;
+               RNA _r;
+               HelixEmbedding _parent;
+               
+               public HelixEmbedding(Point2D.Double support, PairedPortion p, RNA r, HelixEmbedding parent)
+               {
+                       _support = support;
+                       _clip = p.getLocalOutline(r);
+                       _p = p;
+                       _r = r;
+                       _parent = parent;
+               }
+               
+               public void addHelixEmbedding(HelixEmbedding h, int index)
+               {
+                       _children.add(h);
+                       _indices.add(index);
+               }
+               
+               public GeneralPath getShape()
+               {
+                       return _clip;
+               }
+               
+               
+               public int chooseNextMove()
+               {
+                       int i = _parent._children.indexOf(this);
+                       int min;
+                       int max;
+                       if (_parent._children.size()<VARNASecDraw.MAX_NUM_DIR-1)
+                       {
+                               if (_parent._children.size()==1)
+                               { min=1;max=VARNASecDraw.MAX_NUM_DIR-1; }
+                               else 
+                               {
+                                       if (i==0)
+                                       { min = 1; }
+                                       else
+                                       { min = _parent._indices.get(i-1)+1;}
+                                       if (i==_parent._children.size()-1)
+                                       { max = VARNASecDraw.MAX_NUM_DIR-1; }
+                                       else
+                                       { max = _parent._indices.get(i+1)-1;}
+                               }
+                               int prevIndex = _parent._indices.get(i);
+                               int newIndex = min+_rnd.nextInt(max+1-min);
+                               double rot = ((double)(newIndex-prevIndex)*Math.PI*2.0)/MAX_NUM_DIR;
+                               _parent._indices.set(i, newIndex);
+                               rotate(rot);
+                               return newIndex-prevIndex;
+                       }
+                       return 0;
+               }
+               
+               public void cancelMove(int delta)
+               {
+                       int i = _parent._children.indexOf(this);
+                       int prevIndex = _parent._indices.get(i);
+                       double rot = ((double)(-delta)*Math.PI*2.0)/MAX_NUM_DIR;
+                       _parent._indices.set(i, prevIndex-delta);
+                       rotate(rot);
+               }
+               
+               public void rotate(double angle)
+               {
+                       transform(AffineTransform.getRotateInstance(angle, _support.x, _support.y));
+               }
+               
+               private void transform(AffineTransform a)
+               {
+                       _clip.transform(a);
+                       Point2D p = a.transform(_support, null);
+                       _support.setLocation(p.getX(), p.getY());
+                       for (int i=0;i<_children.size();i++)
+                       {
+                               _children.get(i).transform(a);
+                       }
+               }
+               
+               public void reflectCoordinates()
+               {
+                       ArrayList<ModeleBase> mbl = _r.get_listeBases();
+
+                       if (_p._len>0)
+                       {
+                               PathIterator pi = _clip.getPathIterator(AffineTransform.getRotateInstance(0.0));
+                               ArrayList<Point2D.Double> p = new ArrayList<Point2D.Double>(); 
+                               while(!pi.isDone())
+                               {
+                                       double[] args = new double[6];
+                                       int type= pi.currentSegment(args);
+                                       if ((type == PathIterator.SEG_MOVETO)  || (type == PathIterator.SEG_LINETO))
+                                       {
+
+                                               Point2D.Double np = new Point2D.Double(args[0],args[1]); 
+                                               p.add(np);
+                                               System.out.println(Arrays.toString(args));
+                                       }
+                                       pi.next();
+                               }
+                               if (p.size()<4)
+                               { return; }
+                               
+                               Point2D.Double startLeft = p.get(0);
+                               Point2D.Double endLeft = p.get(1);
+                               Point2D.Double endRight = p.get(2);
+                               Point2D.Double startRight = p.get(3);
+                               
+                               double d = startLeft.distance(endLeft);
+                               double vx = endLeft.x-startLeft.x;
+                               double vy = endLeft.y-startLeft.y;
+                               double interval = 0.0;
+                               if (_p._len>1)
+                               {
+                                       vx/=d;
+                                       vy/=d;
+                                       interval = d/((double)_p._len-1);
+                                       System.out.println("DELTA: "+interval+" "+_r.LOOP_DISTANCE);
+                               }
+                               for (int n=0;n<_p._len;n++)
+                               {
+                                       int i = _p._pos1 + n;
+                                       int j = _p._pos2 - n;
+                                       ModeleBase mbLeft = mbl.get(i);
+                                       mbLeft.setCoords(new Point2D.Double(startLeft.x+n*vx*interval, startLeft.y+n*vy*interval));
+                                       ModeleBase mbRight = mbl.get(j);
+                                       mbRight.setCoords(new Point2D.Double(startRight.x+n*vx*interval, startRight.y+n*vy*interval));
+                               }
+                       }
+                       for (int i=0;i<_children.size();i++)
+                       {
+                               _children.get(i).reflectCoordinates();
+                       }
+                       if (_children.size()>0)
+                       {
+                               Point2D.Double center = _children.get(0)._support;
+                               for (int i=0;i<_p._r.getNumPortions();i++)
+                               {
+                                       Portion p = _p._r.getPortion(i);
+                                       if (p instanceof UnpairedPortion)
+                                       {
+                                               UnpairedPortion up = (UnpairedPortion) p;
+                                               for (int j=0;j<up._len;j++)
+                                               {
+                                                       int n = up._pos + j;
+                                                       ModeleBase mbLeft = mbl.get(n);
+                                                       mbLeft.setCoords(center);
+                                               }
+                                       }
+                               }       
+                       }
+                       else
+                       {
+                               placeTerminalLoop(mbl,_r);
+                       }
+               }
+               
+               private void placeTerminalLoop(ArrayList<ModeleBase> mbl, RNA r)
+               {
+                       if ((_children.size()==0)&&(_p._r.getNumPortions()==1))
+                       {
+                               Portion p = _p._r.getPortion(0);
+                               if (p instanceof UnpairedPortion)
+                               {
+                                       UnpairedPortion up = (UnpairedPortion) p;
+                                       double rad = determineRadius(1,up.getNumBases(),_r);
+                                       int a = _p._pos1+_p._len-1;
+                                       int b = _p._pos2-(_p._len-1);
+                                       ModeleBase mbLeft = mbl.get(a);
+                                       ModeleBase mbRight = mbl.get(b);
+                                       Point2D.Double pl = mbLeft.getCoords();
+                                       Point2D.Double pr = mbRight.getCoords();
+                                       Point2D.Double pm = new Point2D.Double((pl.x+pr.x)/2.0,(pl.y+pr.y)/2.0);
+                                       double vx = (pl.x-pr.x)/pl.distance(pr);
+                                       double vy = (pl.y-pr.y)/pl.distance(pr);
+                                       double vnx = -vy, vny = vx;
+                                       Point2D.Double pc = new Point2D.Double(pm.x+rad*vnx,pm.y+rad*vny);
+                                       double circ = r.LOOP_DISTANCE*(1.0+up.getNumBases())+r.BASE_PAIR_DISTANCE; 
+                                       double incrLoop = Math.PI*2.0*r.LOOP_DISTANCE/circ;  
+                                       double angle = Math.PI*2.0*r.BASE_PAIR_DISTANCE/(2.0*circ);
+                                       for (int j=0;j<up._len;j++)
+                                       {
+                                               int n = up._pos + j;
+                                               ModeleBase mb = mbl.get(n);
+                                               angle += incrLoop;
+                                               double dx = -Math.cos(angle)*vnx+Math.sin(angle)*vx;
+                                               double dy = -Math.cos(angle)*vny+Math.sin(angle)*vy;
+//                                             Point2D.Double pf = new Point2D.Double(pc.x,pc.y);
+                                               Point2D.Double pf = new Point2D.Double(pc.x+rad*dx,pc.y+rad*dy);
+                                               mb.setCoords(pf);
+                                       }
+                                       
+                               }
+                       }
+               }
+               
+               
+               
+               public String toString()
+               {
+                       return "Emb.Hel.: "+_p.toString();
+               }
+       }
+       
+       public double determineRadius(int numHelices, int numUnpaired, RNA r)
+       {
+               double circ = numHelices*r.BASE_PAIR_DISTANCE+(numHelices+numUnpaired)*r.LOOP_DISTANCE;
+               return circ/(2.0*Math.PI);
+       }
+       
+       
+       public void predrawTree(double x0, double y0, RNATree t, double dir, RNA r, HelixEmbedding parent, ArrayList<HelixEmbedding> all) throws Exception
+       {
+               double x=x0;
+               double y=y0;
+               int numHelices = 0;
+               int numUBases = 0;
+               double totCirc = r.BASE_PAIR_DISTANCE+r.LOOP_DISTANCE;
+               for (int i=0;i<t.getNumPortions();i++ )
+               {
+                       Portion p = t.getPortion(i);
+                       if (p instanceof PairedPortion)
+                       {
+                               totCirc += (r.BASE_PAIR_DISTANCE+r.LOOP_DISTANCE);
+                               numHelices++;   
+                       }
+                       else
+                       {
+                                 totCirc += r.LOOP_DISTANCE*(p.getNumBases());
+                                 numUBases += p.getNumBases();
+                       }
+               }
+               double radius = determineRadius(numHelices+1,numUBases,r);
+
+               int[] placement = new int[numHelices];
+               double inc = ((double)MAX_NUM_DIR)/((double)numHelices+1);
+               double val = inc;
+               for (int i=0;i<numHelices;i++ )
+               {
+                       placement[i] = (int)Math.round(val);
+                       val += inc;
+               }
+               double angleIncr = 2.0*Math.PI/(double)MAX_NUM_DIR;
+                       x = x0+radius*Math.cos(dir+Math.PI);
+                       y = y0+radius*Math.sin(dir+Math.PI);
+                       int curH = 0;
+                       for (int i=0;i<t.getNumPortions();i++ )
+                       {
+                               Portion p = t.getPortion(i);
+                               if (p instanceof PairedPortion)
+                               {
+                                       double ndir = dir + placement[curH]*angleIncr;
+                                       PairedPortion pp = (PairedPortion) p; 
+                                       for(int j=0;j<pp._len;j++)
+                                       {
+                                               int i1 = pp._pos1+j;
+                                               int i2 = pp._pos2-j;
+                                               double vx = Math.cos(ndir);
+                                               double vy = Math.sin(ndir);
+                                               double nx = x+(((j)*r.LOOP_DISTANCE+radius)*vx);
+                                               double ny = y+(((j)*r.LOOP_DISTANCE+radius)*vy);
+                                               r.get_listeBases().get(i1).setCoords(new Point2D.Double(nx+r.BASE_PAIR_DISTANCE*vy/ 2.0,ny-r.BASE_PAIR_DISTANCE*vx/ 2.0));
+                                               r.get_listeBases().get(i2).setCoords(new Point2D.Double(nx-r.BASE_PAIR_DISTANCE*vy/ 2.0,ny+r.BASE_PAIR_DISTANCE*vx/ 2.0));
+                                       }
+                                       double nx = x+(((pp._len-1)*r.LOOP_DISTANCE+radius)*Math.cos(ndir));
+                                       double ny = y+(((pp._len-1)*r.LOOP_DISTANCE+radius)*Math.sin(ndir));
+                                       HelixEmbedding nh = new HelixEmbedding(new Point2D.Double(x,y),pp,r,parent);
+                                       parent.addHelixEmbedding(nh,placement[curH]);
+                                       all.add(nh);
+                                       predrawTree(nx, ny, pp._r, ndir+Math.PI, r, nh, all);
+                                       curH++;
+                               }
+                               else if (p instanceof UnpairedPortion)
+                               {
+                                       UnpairedPortion up = (UnpairedPortion) p;
+                                       for(int j=0;j<up._len;j++)
+                                       {
+                                               r.get_listeBases().get(up._pos+j).setCoords(new Point2D.Double(x,y));
+                                       }
+                               }
+                               //System.out.println(dir);
+                       }
+       }
+       
+       
+       public static Random _rnd = new Random();
+       
+       private static int MAX_NUM_DIR = 8;
+
+       public RNATree drawRNA(double dirAngle, RNA r) {
+               RNATree t = new RNATree();
+               buildTree(0, r.get_listeBases().size() - 1, t,  r );
+               System.out.println(t);
+               ArrayList<HelixEmbedding> all = new ArrayList<HelixEmbedding>();
+               HelixEmbedding root = null;
+               try {
+                       root = new HelixEmbedding(new Point2D.Double(0.0,0.0),new PairedPortion(0,0,0,t),r,null); 
+                       predrawTree(0,0,t,0.0,r,root,all);
+                       int steps=1000;
+                       double prevbadness = Double.MAX_VALUE;
+                       while((steps>0)&&(prevbadness>0))
+                       {
+
+                               // Generating new structure
+                               HelixEmbedding chosen = all.get(_rnd.nextInt(all.size()));
+                               int delta =  chosen.chooseNextMove();
+                               // Draw current
+                               if (_vp!=null)
+                                       { 
+                                               GeneralPath p = new GeneralPath();
+                                               for (int i=0;i<all.size();i++)
+                                               { p.append(all.get(i).getShape(),false); }
+                                               r._debugShape = p;
+                                               _vp.paintImmediately(0, 0, _vp.getWidth(), _vp.getHeight());    
+                                       }                               
+
+                               //Evaluating solution
+                               double badness = 0.0;
+                               for (int i=0;i<all.size();i++)
+                               { 
+                                       Shape s1 = all.get(i).getShape();
+                                       for (int j=i+1;j<all.size();j++)
+                                       { 
+                                               Shape s2 = all.get(j).getShape();
+                                               Area a = new Area(s1);
+                                               a.intersect(new Area(s2));
+                                               if (!a.isEmpty())
+                                               {
+                                                       badness ++;
+                                               }
+                                       }
+                               }
+
+                               if (badness-prevbadness>0)
+                               {
+                                       chosen.cancelMove(delta);
+                               }
+                               else
+                               {
+                                       prevbadness = badness;
+                               }
+
+                               System.out.println(badness);
+
+                               steps--;
+                       }
+                       if (root!=null)
+                       { root.reflectCoordinates(); }
+               } catch (Exception e) {
+                       // TODO Auto-generated catch block
+                       e.printStackTrace();
+               }
+               return t;
+       };
+       
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/templates/BatchBenchmark.java b/src2/fr/orsay/lri/varna/models/templates/BatchBenchmark.java
new file mode 100644 (file)
index 0000000..06362ca
--- /dev/null
@@ -0,0 +1,236 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.templates;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.exceptions.ExceptionXmlLoading;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+public class BatchBenchmark {
+       private VARNAConfig conf = new VARNAConfig();
+       
+       final boolean DEFAULT_STRAIGHT_BULGES = false;
+       
+       public static RNA loadRNA(File file) throws ExceptionFileFormatOrSyntax, ExceptionUnmatchedClosingParentheses, FileNotFoundException, ExceptionExportFailed, ExceptionPermissionDenied, ExceptionLoadingFailed {
+               Collection<RNA> rnas = RNAFactory.loadSecStr(file.getPath());
+               if (rnas.isEmpty()) {
+                       throw new ExceptionFileFormatOrSyntax(
+                                       "No RNA could be parsed from that source.");
+               }
+               return rnas.iterator().next();
+       }
+       
+       public void benchmarkRNA(File templatePath, File rnaPath, BufferedWriter outbuf) throws ExceptionXmlLoading, RNATemplateDrawingAlgorithmException, ExceptionFileFormatOrSyntax, ExceptionUnmatchedClosingParentheses, ExceptionExportFailed, ExceptionPermissionDenied, ExceptionLoadingFailed, ExceptionNAViewAlgorithm, IOException {
+               // load template
+               RNATemplate template = RNATemplate.fromXMLFile(templatePath);
+               
+               // load RNA
+               RNA rna = loadRNA(rnaPath);
+               
+               for (int algo=0; algo<=100; algo++) {
+                       String algoname = "";
+               
+                       // draw RNA
+                       switch (algo) {
+                       //case 0:
+                       //      rna.drawRNALine(conf);
+                       //      algoname = "Linear";
+                       //      break;
+                       //case 1:
+                       //      rna.drawRNACircle(conf);
+                       //      algoname = "Circular";
+                       //      break;
+                       case 2:
+                               rna.drawRNARadiate(conf);
+                               algoname = "Radiate";
+                               break;
+                       case 3:
+                               rna.drawRNANAView(conf);
+                               algoname = "NAView";
+                               break;
+                       case 10:
+                               algoname = "Template/noadj";
+                               rna.drawRNATemplate(template, conf, DrawRNATemplateMethod.NOADJUST, DrawRNATemplateCurveMethod.EXACTLY_AS_IN_TEMPLATE, DEFAULT_STRAIGHT_BULGES);
+                               break;
+                       case 11:
+                               algoname = "Template/noadj/ellipses";
+                               rna.drawRNATemplate(template, conf, DrawRNATemplateMethod.NOADJUST, DrawRNATemplateCurveMethod.ALWAYS_REPLACE_BY_ELLIPSES, DEFAULT_STRAIGHT_BULGES);
+                               break;
+                       case 12:
+                               algoname = "Template/noadj/smart";
+                               rna.drawRNATemplate(template, conf, DrawRNATemplateMethod.NOADJUST, DrawRNATemplateCurveMethod.SMART, DEFAULT_STRAIGHT_BULGES);
+                               break;
+                               /*
+                       case 5:
+                               algoname = "Template/maxfactor";
+                               rna.drawRNATemplate(template, conf, DrawRNATemplateMethod.MAXSCALINGFACTOR, DrawRNATemplateCurveMethod.EXACTLY_AS_IN_TEMPLATE, DEFAULT_STRAIGHT_BULGES);
+                               break;
+                               */
+                       case 6:
+                               algoname = "Template/mininter";
+                               rna.drawRNATemplate(template, conf, DrawRNATemplateMethod.NOINTERSECT, DrawRNATemplateCurveMethod.EXACTLY_AS_IN_TEMPLATE, DEFAULT_STRAIGHT_BULGES);
+                               break;
+                       case 30:
+                               algoname = "Template/translate";
+                               rna.drawRNATemplate(template, conf, DrawRNATemplateMethod.HELIXTRANSLATE, DrawRNATemplateCurveMethod.EXACTLY_AS_IN_TEMPLATE, DEFAULT_STRAIGHT_BULGES);
+                               break;
+                       case 31:
+                               algoname = "Template/translate/ellipses";
+                               rna.drawRNATemplate(template, conf, DrawRNATemplateMethod.HELIXTRANSLATE, DrawRNATemplateCurveMethod.ALWAYS_REPLACE_BY_ELLIPSES, DEFAULT_STRAIGHT_BULGES);
+                               break;
+                       case 32:
+                               algoname = "Template/translate/smart";
+                               rna.drawRNATemplate(template, conf, DrawRNATemplateMethod.HELIXTRANSLATE, DrawRNATemplateCurveMethod.SMART, DEFAULT_STRAIGHT_BULGES);
+                               break;
+                       default:
+                               continue;
+                       }
+               
+                       // benchmark
+                       Benchmark benchmark = new Benchmark(rna);
+                       
+                       // print results
+                       outbuf.write(
+                                       removeExt(rnaPath.getName())
+                                       + "\t" + algoname
+                                       + "\t" + benchmark.backboneCrossings
+                                       // averageUnpairedDistance % -> best is 100
+                                       + "\t" + (benchmark.averageUnpairedDistance / benchmark.targetConsecutiveBaseDistance *100)
+                                       + "\t" + benchmark.tooNearConsecutiveBases
+                                       + "\t" + benchmark.tooFarConsecutiveBases
+                                       + "\n");
+               }
+               
+       }
+       
+       public void runBenchmark(List<File> templates, List<File> rnas, File outfile) throws Exception {
+               if (templates.size() != rnas.size()) {
+                       throw new Error("templates and rnas list size differ");
+               }
+               
+               BufferedWriter outbuf = new BufferedWriter(new FileWriter(outfile));
+               
+               outbuf.write("RNA\tAlgorithm\tBackbone crossings\tAverage unpaired distance %\tToo near\tToo far\n");
+               
+               for (int i=0; i<templates.size(); i++) {
+                       System.out.println("Benchmarking for RNA " + removeExt(rnas.get(i).getName()));
+                       benchmarkRNA(templates.get(i), rnas.get(i), outbuf);
+               }
+               
+               outbuf.close();
+               
+               System.out.println("******* Benchmark finished. *******");
+       }
+       
+       public void runExamples() throws Exception {
+               File templatesDir = new File("templates");
+               File root = new File(templatesDir, "examples");
+               File outfile = new File(new File(templatesDir, "benchmark"), "benchmark.txt");
+               
+               String seqlist[] = {"RNase P E Coli.ct", "RNase P Synechocystis-PCC6803.ct", "RNase P M Musculus.ct"};
+               
+               List<File> templates = new ArrayList<File>();
+               List<File> rnas = new ArrayList<File>();
+               
+               for (String seq: seqlist) {
+                       templates.add(new File(root, "RNase P E Coli.xml"));
+                       rnas.add(new File(root, seq));
+               }
+               
+               runBenchmark(templates, rnas, outfile);
+       }
+       
+       public static void readFASTA(File file, List<String> seqnames, List<String> sequences) throws IOException {
+               BufferedReader buf = new BufferedReader(new FileReader(file));
+               String line = buf.readLine();
+               while (line != null) {
+                       if (line.length() != 0) {
+                               if (line.charAt(0) == '>') {
+                                       String id = line.substring(1); // remove the >
+                                       seqnames.add(id);
+                                       sequences.add("");
+                               } else {
+                                       sequences.set(sequences.size()-1, sequences.get(sequences.size()-1) + line);
+                               }
+                       }
+                       line = buf.readLine();
+               }
+               buf.close();
+       }
+       
+       
+       /**
+        * We assume given directory contains a alignemnt.fasta file,
+        * of which the first sequence is the consensus structure,
+        * and the other sequences are aligned nucleotides. 
+        * The principle is to convert it to a set of secondary structure,
+        * using the following rule:
+        * - keep the same nucleotides as in original sequence
+        * - keep base pairs where both bases of the pair are non-gaps in our sequence
+        */
+       public void benchmarkAllDir(File rootdir) throws Exception {
+               File seqdir = new File(rootdir, "sequences");
+               File templateFile = new File(rootdir, "template.xml");
+               File sequenceFiles[] = seqdir.listFiles();
+               Arrays.sort(sequenceFiles);
+               
+               List<File> templates = new ArrayList<File>();
+               List<File> rnas = new ArrayList<File>();
+               for (File seq: sequenceFiles) {
+                       if (!seq.getPath().endsWith(".dbn")) continue;
+                       rnas.add(seq);
+                       templates.add(templateFile);
+               }
+               
+               File outfile = new File(rootdir, "benchmark.txt");
+               runBenchmark(templates, rnas, outfile);
+               
+       }
+       
+       
+       public static void main(String[] args) throws Exception {
+               File templatesDir = new File("templates");
+               if (args.length < 1) {
+                       System.out.println("Command-line argument required: RNA");
+                       System.out.println("Example: RNaseP_bact_a");
+                       System.exit(1);
+               }
+               //new BatchBenchmark().runExamples();
+               for (String arg: args) {
+                       new BatchBenchmark().benchmarkAllDir(new File(templatesDir, arg));
+               }
+       }
+       
+       /**
+        * Return the given file path without the (last) extension. 
+        */
+       public static String removeExt(String path) {
+               return path.substring(0, path.lastIndexOf('.'));
+       }
+       
+       public static File removeExt(File path) {
+               return new File(removeExt(path.getPath()));
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/BatchBenchmarkPrepare.java b/src2/fr/orsay/lri/varna/models/templates/BatchBenchmarkPrepare.java
new file mode 100644 (file)
index 0000000..c3ab8ac
--- /dev/null
@@ -0,0 +1,98 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.templates;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import fr.orsay.lri.varna.factories.RNAFactory;
+
+public class BatchBenchmarkPrepare {
+
+       /**
+        * We assume given directory contains a alignemnt.fasta file,
+        * of which the first sequence is the consensus structure,
+        * and the other sequences are aligned nucleotides. 
+        * The principle is to convert it to a set of secondary structure,
+        * using the following rule:
+        * - keep the same nucleotides as in original sequence
+        * - keep base pairs where both bases of the pair are non-gaps in our sequence
+        */
+       public void benchmarkAllDir(File rootdir) throws Exception {
+               File seqdir = new File(rootdir, "sequences");
+               if (!seqdir.exists()) {
+                       seqdir.mkdir();
+               }
+               
+               File templateFile = new File(rootdir, "template.xml");
+               
+               ArrayList<String> seqnames = new ArrayList<String>();
+               ArrayList<String> sequences = new ArrayList<String>();
+               BatchBenchmark.readFASTA(new File(rootdir, "alignment.fasta"), seqnames, sequences);
+               
+               BufferedWriter outbufASS = new BufferedWriter(new FileWriter(new File(rootdir, "all_secondary_structures.fasta")));
+               
+               String consensusSecStr = sequences.get(0);
+               int[] consensusSecStrInt = RNAFactory.parseSecStr(consensusSecStr);
+               
+               List<File> templates = new ArrayList<File>();
+               for (int i=1; i<seqnames.size(); i++) {
+                       String seqname = seqnames.get(i);
+                       String sequence = sequences.get(i);
+                       String sequenceUngapped = sequence.replaceAll("[\\.-]", "");
+                       System.out.println(seqname);
+                       String ss = "";
+                       String nt = "";
+                       for (int j=0; j<sequence.length(); j++) {
+                               if (sequence.charAt(j) != '.' && sequence.charAt(j) != '-') {
+                                       if (consensusSecStr.charAt(j) == '-' || consensusSecStr.charAt(j) == '.') {
+                                               nt += sequence.charAt(j);
+                                               ss += '.';
+                                       } else {
+                                               int k = consensusSecStrInt[j];
+                                               // k is the matching base, is it aligned to a base in our sequence?
+                                               if (sequence.charAt(k) != '.' && sequence.charAt(k) != '-') {
+                                                       nt += sequence.charAt(j);
+                                                       ss += consensusSecStr.charAt(j);
+                                               } else {
+                                                       nt += sequence.charAt(j);
+                                                       ss += '.';
+                                               }
+                                       }
+                               }
+                       }
+                       
+                       if (!sequenceUngapped.equals(nt)) {
+                               System.out.println(sequenceUngapped);
+                               System.out.println(nt);
+                               throw new Error("bug");
+                       }
+                       
+                       // We now have the sequence with its secondary structure.
+                       File outfile = new File(seqdir, seqname + ".dbn");
+                       BufferedWriter outbuf = new BufferedWriter(new FileWriter(outfile));
+                       outbuf.write(">" + seqname + "\n");
+                       outbuf.write(nt + "\n");
+                       outbuf.write(ss + "\n");
+                       outbuf.close();
+                       
+                       outbufASS.write(">" + seqname + "\n");
+                       outbufASS.write(ss + "\n");
+                       
+                       templates.add(templateFile);
+               }
+               
+               outbufASS.close();
+               
+       }
+       
+       public static void main(String[] args) throws Exception {
+               new BatchBenchmarkPrepare().benchmarkAllDir(new File(new File("templates"), "RNaseP_bact_a"));
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/Benchmark.java b/src2/fr/orsay/lri/varna/models/templates/Benchmark.java
new file mode 100644 (file)
index 0000000..b3db1fd
--- /dev/null
@@ -0,0 +1,120 @@
+package fr.orsay.lri.varna.models.templates;
+
+import java.awt.geom.Line2D;
+import java.util.Arrays;
+
+import fr.orsay.lri.varna.models.geom.LinesIntersect;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+/**
+ * @author Raphael Champeimont
+ *
+ */
+public class Benchmark {
+       private RNA rna;
+       
+       // number of backbone crossings
+       public int backboneCrossings;
+       // average distance between unpaired consecutive bases
+       public double averageUnpairedDistance;
+       // median distance between consecutive bases
+       public double medianConsecutiveBaseDistance;
+       // Number of consecutive bases that are too near from each other
+       public int tooNearConsecutiveBases;
+       // Number of consecutive bases that are too far from each other
+       public int tooFarConsecutiveBases;
+       
+       
+       
+       // Parameters
+       public double targetConsecutiveBaseDistance = RNA.LOOP_DISTANCE;
+       // If consecutive bases are nearer that tooNearFactor * target distance, we call them too near.
+       public double tooNearFactor = 0.5;
+       // If consecutive bases are further that tooFarFactor * target distance, we call them too far.
+       public double tooFarFactor = 2;
+       
+       
+       
+       public Benchmark(RNA rna) {
+               this.rna = rna;
+               computeAll();
+       }
+       
+       private void computeAll() {
+               // Compute number of backbone crossings
+               {
+                       int n = rna.getSize();
+                       Line2D.Double[] lines = new Line2D.Double[n-1];
+                       for (int i=0; i<n-1; i++) {
+                               lines[i] = new Line2D.Double(rna.getCoords(i), rna.getCoords(i+1));
+                       }
+                       int intersectLines = 0;
+                       for (int i=0; i<n-1; i++) {
+                               for (int j=i+2; j<n-1; j++) {
+                                       if (LinesIntersect.linesIntersect(lines[i], lines[j])) {
+                                               intersectLines++;
+                                       }
+                               }
+                       }
+                       backboneCrossings = intersectLines;
+               }
+               
+               // Stats about distances between consecutive bases not both part of an helix
+               {
+                       int n = rna.getSize();
+                       double sum = 0;
+                       int count = 0;
+                       for (int i=0; i<n-1; i++) {
+                               int indexOfAssociatedBase1 = rna.getBaseAt(i).getElementStructure();
+                               int indexOfAssociatedBase2 = rna.getBaseAt(i+1).getElementStructure();
+                               if (indexOfAssociatedBase1 != -1 || indexOfAssociatedBase2 != -1) {
+                                       // If they are not both associated (ie. not part of an helix)
+                                       sum += rna.getBaseAt(i).getCoords().distance(rna.getBaseAt(i+1).getCoords());
+                                       count++;
+                               }
+                       }
+                       averageUnpairedDistance = sum / count;
+               }
+               
+               // Stats about base distances
+               {
+                       int n = rna.getSize();
+                       double distances[] = new double[n-1];
+                       for (int i=0; i<n-1; i++) {
+                               // If they are not both associated (ie. not part of an helix)
+                               distances[i] = rna.getBaseAt(i).getCoords().distance(rna.getBaseAt(i+1).getCoords());
+                       }
+                       Arrays.sort(distances);
+                       double median = distances[distances.length/2];
+                       medianConsecutiveBaseDistance = median;
+                       
+                       // We take the median as target distance, and count
+                       // the number of consecutive bases with a distance too different
+                       tooNearConsecutiveBases = 0;
+                       tooFarConsecutiveBases = 0;
+                       for (int i=0; i<n-1; i++) {
+                               if (distances[i] < tooNearFactor*targetConsecutiveBaseDistance) {
+                                       tooNearConsecutiveBases++;
+                               }
+                               if (distances[i] > tooFarFactor*targetConsecutiveBaseDistance) {
+                                       tooFarConsecutiveBases++;
+                               }
+                       }
+               }
+       }
+       
+       @SuppressWarnings("unused")
+       private int percent(int a, int b) {
+               return (int) Math.round((double) a / (double) b * 100.0);
+       }
+
+       public void printAll() {
+               System.out.println("Benchmark:");
+               System.out.println("\tBackbone crossings = " + backboneCrossings);
+               System.out.println("\tAverage unpaired distance = " + averageUnpairedDistance);
+               System.out.println("\tMedian of consecutive base distance = " + medianConsecutiveBaseDistance);
+               System.out.println("\tNumber of too near consecutive bases = " + tooNearConsecutiveBases); // + " ie. " + percent(tooNearConsecutiveBases, rna.getSize()-1) + " %");
+               System.out.println("\tNumber of too far consecutive bases = " + tooFarConsecutiveBases); // + " ie. " + percent(tooFarConsecutiveBases, rna.getSize()-1) + " %");
+       }
+}
+
diff --git a/src2/fr/orsay/lri/varna/models/templates/DrawRNATemplateCurveMethod.java b/src2/fr/orsay/lri/varna/models/templates/DrawRNATemplateCurveMethod.java
new file mode 100644 (file)
index 0000000..b1796f7
--- /dev/null
@@ -0,0 +1,33 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.templates;
+
+/**
+ * @author Raphael Champeimont
+ * How should we draw unpaired regions?
+ */
+public enum DrawRNATemplateCurveMethod {
+        // use what is in the template
+       EXACTLY_AS_IN_TEMPLATE("Bezier"),
+       // use ellipses, ignoring Bezier parameters from template (useful mostly for debugging ellipses)
+       ALWAYS_REPLACE_BY_ELLIPSES("Ellipses"),
+       // replace by ellipse where it is a good idea
+       SMART("Auto-Select");
+
+       String _msg;
+       
+       private DrawRNATemplateCurveMethod(String msg){
+               _msg=msg;
+       }
+       
+       public String toString()
+       {
+               return _msg;
+       }
+       
+       public static DrawRNATemplateCurveMethod getDefault() {
+               return SMART;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/DrawRNATemplateMethod.java b/src2/fr/orsay/lri/varna/models/templates/DrawRNATemplateMethod.java
new file mode 100644 (file)
index 0000000..9fd5f67
--- /dev/null
@@ -0,0 +1,38 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.models.templates;
+
+/**
+ * What to do in case some helices are of a different length
+ * in the template and the actual helix.
+ * Possibles values are:
+ * 0 - No adjustment is done.
+ *     A longer than expected helix might bump into an other helix.
+ * 1 - Scaling factors (actual length / template length) are calculated,
+ *     the maximum scaling factor L is extracted, then all helix positions
+ *     are multiplied by L. 
+ * 2 - Same as 1, but L is computed as the minimum value such that there
+ *     are no backbone intersections.
+ */
+public enum DrawRNATemplateMethod {
+       NOADJUST("No Adjust"), MAXSCALINGFACTOR("Max Scaling"), NOINTERSECT("Non-crossing"), HELIXTRANSLATE("Helix Translation");
+       
+       String _msg;
+       
+       public static DrawRNATemplateMethod getDefault() {
+               return HELIXTRANSLATE;
+       }
+       
+
+       public String toString()
+       {
+               return _msg;
+       }
+       
+       private DrawRNATemplateMethod(String msg)
+       {
+               _msg = msg;
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNANodeValue2TemplateDistance.java b/src2/fr/orsay/lri/varna/models/templates/RNANodeValue2TemplateDistance.java
new file mode 100644 (file)
index 0000000..51e8b46
--- /dev/null
@@ -0,0 +1,93 @@
+package fr.orsay.lri.varna.models.templates;
+
+import fr.orsay.lri.varna.models.treealign.RNANodeValue;
+import fr.orsay.lri.varna.models.treealign.RNANodeValue2;
+import fr.orsay.lri.varna.models.treealign.TreeAlignLabelDistanceAsymmetric;
+
+/**
+ * Distance between an RNANodeValue2 and an RNANodeValueTemplate.
+ * 
+ * @author Raphael Champeimont
+ *
+ */
+public class RNANodeValue2TemplateDistance implements TreeAlignLabelDistanceAsymmetric<RNANodeValue2,RNANodeValueTemplate> {
+       public double delete(RNANodeValue2 v) {
+               if (v == null) {
+                       // deleting nothing costs nothing
+                       return 0;
+               } else {
+                       if (v.isSingleNode()) {
+                               if (v.getNode().getRightBasePosition() < 0) {
+                                       // delete one base (that comes from a broken base pair)
+                                       return 1;
+                               } else {
+                                       // delete a base pair
+                                       return 2;
+                               }
+                       } else {
+                               // delete a sequence
+                               return v.getNodes().size();
+                       }
+               }
+       }
+       
+       public double insert(RNANodeValueTemplate v) {
+               if (v == null) {
+                       // inserting nothing costs nothing
+                       return 0;
+               } else {
+                       if (v instanceof RNANodeValueTemplateSequence) {
+                               return ((RNANodeValueTemplateSequence) v).getSequence().getLength();
+                       } else if (v instanceof RNANodeValueTemplateBrokenBasePair) {
+                               // insert one base
+                               return 1;
+                       } else { // this is a base pair
+                               // delete the base pair
+                               return 2;
+                       }
+               }
+       }
+       
+       public double f(RNANodeValue2 v1, RNANodeValueTemplate v2) {
+               if (v1 == null) {
+                       return insert(v2);
+               } else if (v2 == null) {
+                       return delete(v1);
+               } else if (!v1.isSingleNode()) { // v1 is a sequence
+                       if (v2 instanceof RNANodeValueTemplateSequence) {
+                               // the cost is the difference between the sequence lengths
+                               return Math.abs(v1.getNodes().size() - ((RNANodeValueTemplateSequence) v2).getSequence().getLength());
+                       } else {
+                               // a sequence cannot be changed in something else
+                               return Double.POSITIVE_INFINITY;
+                       }
+               } else if (v1.getNode().getRightBasePosition() >= 0) { // v1 is a base pair
+                       if (v2 instanceof RNANodeValueTemplateBasePair) {
+                               // ok, a base pair can be mapped to a base pair
+                               return 0;
+                       } else {
+                               // a base pair cannot be changed in something else
+                               return Double.POSITIVE_INFINITY;
+                       }
+               } else { // v1 is a broken base pair
+                       if (v2 instanceof RNANodeValueTemplateBrokenBasePair) {
+                               RNANodeValueTemplateBrokenBasePair brokenBasePair = ((RNANodeValueTemplateBrokenBasePair) v2);
+                               boolean strand5onTemplateSide = brokenBasePair.getPositionInHelix() < brokenBasePair.getHelix().getLength();
+                               boolean strand3onTemplateSide = ! strand5onTemplateSide;
+                               boolean strand5onRNASide = (v1.getNode().getOrigin() == RNANodeValue.Origin.BASE_FROM_HELIX_STRAND5);
+                               boolean strand3onRNASide = (v1.getNode().getOrigin() == RNANodeValue.Origin.BASE_FROM_HELIX_STRAND3);
+                               if ((strand5onTemplateSide && strand5onRNASide)
+                                               || (strand3onTemplateSide && strand3onRNASide)) {
+                                       // Ok they can be mapped together
+                                       return 0.0;
+                               } else {
+                                       // A base on a 5' strand of an helix
+                                       // cannot be mapped to base on a 3' strand of an helix
+                                       return Double.POSITIVE_INFINITY;
+                               }
+                       } else {
+                               return Double.POSITIVE_INFINITY;
+                       }
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplate.java b/src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplate.java
new file mode 100644 (file)
index 0000000..79374ba
--- /dev/null
@@ -0,0 +1,23 @@
+package fr.orsay.lri.varna.models.templates;
+
+import fr.orsay.lri.varna.models.treealign.GraphvizDrawableNodeValue;
+
+
+/**
+ * An node from an RNA template is either a sequence of non-paired bases,
+ * a base pair originally belonging to an helix,
+ * or a single base originally belonging to an helix but which was broken
+ * in order to remove pseudoknots.
+ * 
+ * @author Raphael Champeimont
+ */
+public abstract class RNANodeValueTemplate implements GraphvizDrawableNodeValue {
+
+       public String toString() {
+               return toGraphvizNodeName();
+       }
+       
+       public abstract String toGraphvizNodeName();
+       
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateBasePair.java b/src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateBasePair.java
new file mode 100644 (file)
index 0000000..99c67b5
--- /dev/null
@@ -0,0 +1,48 @@
+package fr.orsay.lri.varna.models.templates;
+
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateHelix;
+
+
+/**
+ * See RNANodeValueTemplate.
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNANodeValueTemplateBasePair extends RNANodeValueTemplate {
+       
+       /**
+        * The original template element this node came from.
+        */
+       private RNATemplateHelix helix;
+
+       /**
+        * The position (in the 5' to 3' order)
+        * of this base pair in the original helix.
+        */
+       private int positionInHelix;
+       
+       
+       
+       public String toGraphvizNodeName() {
+               return "H[" + positionInHelix + "]";
+       }
+       
+       
+       
+       public RNATemplateHelix getHelix() {
+               return helix;
+       }
+
+       public void setHelix(RNATemplateHelix helix) {
+               this.helix = helix;
+       }
+
+       public int getPositionInHelix() {
+               return positionInHelix;
+       }
+
+       public void setPositionInHelix(int positionInHelix) {
+               this.positionInHelix = positionInHelix;
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateBrokenBasePair.java b/src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateBrokenBasePair.java
new file mode 100644 (file)
index 0000000..efa1679
--- /dev/null
@@ -0,0 +1,47 @@
+package fr.orsay.lri.varna.models.templates;
+
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateHelix;
+
+/**
+ * See RNANodeValueTemplate.
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNANodeValueTemplateBrokenBasePair extends RNANodeValueTemplate {
+       
+       /**
+        * The original template element this node came from.
+        */
+       private RNATemplateHelix helix;
+
+       /**
+        * The position (in the 5' to 3' order)
+        * of this base in the original helix.
+        */
+       private int positionInHelix;
+       
+       
+       
+       public String toGraphvizNodeName() {
+               return "BH[" + positionInHelix + "]";
+       }
+       
+       
+       
+       public RNATemplateHelix getHelix() {
+               return helix;
+       }
+
+       public void setHelix(RNATemplateHelix helix) {
+               this.helix = helix;
+       }
+
+       public int getPositionInHelix() {
+               return positionInHelix;
+       }
+
+       public void setPositionInHelix(int positionInHelix) {
+               this.positionInHelix = positionInHelix;
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateSequence.java b/src2/fr/orsay/lri/varna/models/templates/RNANodeValueTemplateSequence.java
new file mode 100644 (file)
index 0000000..0dfa53c
--- /dev/null
@@ -0,0 +1,34 @@
+package fr.orsay.lri.varna.models.templates;
+
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateUnpairedSequence;
+
+
+/**
+ * See RNANodeValueTemplate.
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNANodeValueTemplateSequence extends RNANodeValueTemplate {
+
+       /**
+        * The sequence this node came from.
+        */
+       private RNATemplateUnpairedSequence sequence;
+       
+
+       
+       public String toGraphvizNodeName() {
+               return "S(len=" + sequence.getLength() + ")";
+       }
+       
+       
+       
+
+       public RNATemplateUnpairedSequence getSequence() {
+               return sequence;
+       }
+
+       public void setSequence(RNATemplateUnpairedSequence sequence) {
+               this.sequence = sequence;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNATemplate.java b/src2/fr/orsay/lri/varna/models/templates/RNATemplate.java
new file mode 100644 (file)
index 0000000..5e2a3ce
--- /dev/null
@@ -0,0 +1,1821 @@
+package fr.orsay.lri.varna.models.templates;
+
+import java.awt.Point;
+import java.awt.geom.Point2D;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.Stack;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+import fr.orsay.lri.varna.exceptions.ExceptionEdgeEndpointAlreadyConnected;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionInvalidRNATemplate;
+import fr.orsay.lri.varna.exceptions.ExceptionXMLGeneration;
+import fr.orsay.lri.varna.exceptions.ExceptionXmlLoading;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement.EdgeEndPoint;
+import fr.orsay.lri.varna.models.treealign.Tree;
+
+
+/**
+ * A model for RNA templates.
+ * A template is a way to display an RNA secondary structure.
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNATemplate {
+       /**
+        * The list of template elements.
+        */
+       private Collection<RNATemplateElement> elements = new ArrayList<RNATemplateElement>();
+
+       /**
+        * Tells whether the template contains elements.
+        */
+       public boolean isEmpty() {
+               return elements.isEmpty();
+       }
+       
+       /**
+        * The first endpoint (in sequence order) of the template.
+        * If there are multiple connected components, the first elements of one
+        * connected component will be returned.
+        * If the template contains no elements, null is returned.
+        * If there is a cycle, an arbitrary endpoint will be returned
+        * (as it then does not make sense to define the first endpoint).
+        * Time: O(n)
+        */
+       public RNATemplateElement getFirst() {
+               return getFirstEndPoint().getElement();
+       }
+       
+       /**
+        * The first endpoint edge endpoint (in sequence order) of the template.
+        * If there are multiple connected components, the first elements of one
+        * connected component will be returned.
+        * If the template contains no elements, null is returned.
+        * If there is a cycle, an arbitrary endpoint will be returned
+        * (as it then does not make sense to define the first endpoint).
+        * Time: O(n)
+        */
+       public EdgeEndPoint getFirstEndPoint() {
+               if (elements.isEmpty()) {
+                       return null;
+               } else {
+                       Set<EdgeEndPoint> knownEndPoints = new HashSet<EdgeEndPoint>();
+                       EdgeEndPoint currentEndPoint = getAnyEndPoint();
+                       while (true) {
+                               if (knownEndPoints.contains(currentEndPoint)) {
+                                       // There is a cycle in the template, so we stop there
+                                       // to avoid looping infinitely.
+                                       return currentEndPoint;
+                               }
+                               knownEndPoints.add(currentEndPoint);
+                               EdgeEndPoint previousEndPoint = currentEndPoint.getPreviousEndPoint();
+                               if (previousEndPoint == null) {
+                                       return currentEndPoint;
+                               } else {
+                                       currentEndPoint = previousEndPoint;
+                               }
+                       }
+               }
+       }
+       
+       /**
+        * Return an arbitrary element of the template,
+        * null if empty.
+        * Time: O(1)
+        */
+       public RNATemplateElement getAny() {
+               if (elements.isEmpty()) {
+                       return null;
+               } else {
+                       return elements.iterator().next();
+               }
+       }
+       
+       /**
+        * Return an arbitrary endpoint of the template,
+        * null if empty.
+        * Time: O(1)
+        */
+       public EdgeEndPoint getAnyEndPoint() {
+               if (isEmpty()) {
+                       return null;
+               } else {
+                       return getAny().getIn1EndPoint();
+               }
+       }
+       
+       /**
+        * Variable containing "this", used by the internal class
+        * to access this object.
+        */
+       private final RNATemplate template = this;
+       
+
+       /**
+        * To get an iterator of this class, use rnaIterator().
+        * See rnaIterator() for documentation.
+        */
+       private class RNAIterator implements Iterator<RNATemplateElement> {
+               private Iterator<EdgeEndPoint> iter = vertexIterator();
+
+               public boolean hasNext() {
+                       return iter.hasNext();
+               }
+
+               public RNATemplateElement next() {
+                       if (! hasNext()) {
+                               throw (new NoSuchElementException());
+                       }
+                       
+                       EdgeEndPoint currentEndPoint = iter.next();
+                       switch (currentEndPoint.getPosition()) {
+                       // We skip "IN" endpoints, so that we don't return elements twice
+                       case IN1:
+                       case IN2:
+                               // We get the corresponding "OUT" endpoint
+                               currentEndPoint = iter.next();
+                               break;
+                       }
+                       
+                       return currentEndPoint.getElement();
+               }
+
+               public void remove() {
+                       throw (new UnsupportedOperationException());
+               }
+               
+       }
+       
+       /**
+        * Iterates over the elements of the template, in the sequence order.
+        * Helixes will be given twice.
+        * Only one connected component will be iterated on.
+        * Note that if there is a cycle, the iterator may return a infinite
+        * number of elements.
+        */
+       public Iterator<RNATemplateElement> rnaIterator() {
+               return new RNAIterator();
+       }
+       
+       /**
+        * Iterates over all elements (each endpoint is given only once)
+        * in an arbitrary order.
+        */
+       public Iterator<RNATemplateElement> classicIterator() {
+               return elements.iterator();
+       }
+       
+       private class VertexIterator implements Iterator<EdgeEndPoint> {
+               private EdgeEndPoint endpoint = getFirstEndPoint();
+
+               public boolean hasNext() {
+                       return (endpoint != null);
+               }
+
+               public EdgeEndPoint next() {
+                       if (endpoint == null) {
+                               throw (new NoSuchElementException());
+                       }
+                       
+                       EdgeEndPoint currentEndPoint = endpoint;
+                       endpoint = currentEndPoint.getNextEndPoint();
+                       return currentEndPoint;
+               }
+
+               public void remove() {
+                       throw (new UnsupportedOperationException());
+               }
+       }
+       
+       /**
+        * Iterates over the elements edge endpoints of the template,
+        * in the sequence order.
+        * Only one connected component will be iterated on.
+        * Note that if there is a cycle, the iterator may return a infinite
+        * number of elements.
+        */
+       public Iterator<EdgeEndPoint> vertexIterator() {
+               return new VertexIterator();
+       }
+       
+       
+       
+       private class MakeEdgeList {
+               List<EdgeEndPoint> list = new LinkedList<EdgeEndPoint>();
+               
+               private void addEdgeIfNecessary(EdgeEndPoint endPoint) {
+                       if (endPoint.isConnected()) {
+                               list.add(endPoint);
+                       }
+               }
+               
+               public List<EdgeEndPoint> make() {
+                       for (RNATemplateElement element: elements) {
+                               if (element instanceof RNATemplateHelix) {
+                                       RNATemplateHelix helix = (RNATemplateHelix) element;
+                                       addEdgeIfNecessary(helix.getIn1());
+                                       addEdgeIfNecessary(helix.getIn2());
+                               } else if (element instanceof RNATemplateUnpairedSequence) {
+                                       RNATemplateUnpairedSequence sequence = (RNATemplateUnpairedSequence) element;
+                                       addEdgeIfNecessary(sequence.getIn());
+                               }
+                       }
+                       return list;
+               }
+       }
+       
+       /**
+        * Return over all edges in an arbitrary order.
+        * For each edge, the first (5' side) endpoint will be given. 
+        */
+       public List<EdgeEndPoint> makeEdgeList() {
+               MakeEdgeList listMaker = new MakeEdgeList();
+               return listMaker.make();
+       }
+       
+       
+       
+       
+
+       private class RemovePseudoKnots {
+               /**
+                * The elements of the template as an array, in the order of the
+                * RNA sequence. Note that helixes will appear twice,
+                * and non-paired sequences don't appear.
+                */
+               private ArrayList<RNATemplateHelix> helixesSeq;
+               
+               /**
+                * For any i,
+                * j = helixesStruct[i] is the index in helixesSeq
+                * where the same helix also appears.
+                * It means we have for all i:
+                * helixesSeq[helixesStruct[i]] == helixesSeq[i]
+                */
+               private ArrayList<Integer> helixesStruct;
+               
+               /**
+                * The same as helixesStruct, but without the pseudoknots,
+                * ie. helixesStructWithoutPseudoKnots[i] may be -1
+                * even though helixesStruct[i] != -1 .
+                */
+               private int[] helixesStructWithoutPseudoKnots;
+
+               
+               private void initArrays() throws ExceptionInvalidRNATemplate {
+                       helixesSeq = new ArrayList<RNATemplateHelix>();
+                       helixesStruct = new ArrayList<Integer>();
+                       Map<RNATemplateHelix,Integer> knownHelixes = new Hashtable<RNATemplateHelix,Integer>();
+                       Iterator<RNATemplateElement> iter = rnaIterator();
+                       while (iter.hasNext()) {
+                               RNATemplateElement element = iter.next();
+                               if (element instanceof RNATemplateHelix) {
+                                       helixesSeq.add((RNATemplateHelix) element);
+                                       int index = helixesSeq.size() - 1;
+                                       if (knownHelixes.containsKey(element)) {
+                                               // This is the second time we meet this helix.
+                                               int otherOccurenceIndex = knownHelixes.get(element);
+                                               helixesStruct.add(otherOccurenceIndex);
+                                               if (helixesStruct.get(otherOccurenceIndex) != -1) {
+                                                       throw (new ExceptionInvalidRNATemplate("We met an helix 3 times. Is there a cycle?"));
+                                               }
+                                               // Now we know the partner of the other part of
+                                               // the helix.
+                                               helixesStruct.set(otherOccurenceIndex, index);
+                                       } else {
+                                               // This is the first time we meet this helix.
+                                               // Remember its index
+                                               knownHelixes.put((RNATemplateHelix) element, index);
+                                               // For the moment we don't know where the other part
+                                               // of the helix is, but this will be found later.
+                                               helixesStruct.add(-1);
+                                       }
+                               }
+                       }
+                       
+               }
+               
+               /**
+                * Tells whether there is a pseudoknot.
+                * Adapted from RNAMLParser.isSelfCrossing()
+                */
+               private boolean isSelfCrossing() {
+                       Stack<Point> intervals = new Stack<Point>();
+                       intervals.add(new Point(0, helixesStruct.size() - 1));
+                       while (!intervals.empty()) {
+                               Point p = intervals.pop();
+                               if (p.x <= p.y) {
+                                       if (helixesStruct.get(p.x) == -1) {
+                                               intervals.push(new Point(p.x + 1, p.y));
+                                       } else {
+                                               int i = p.x;
+                                               int j = p.y;
+                                               int k = helixesStruct.get(i);
+                                               if ((k <= i) || (k > j)) {
+                                                       return true;
+                                               } else {
+                                                       intervals.push(new Point(i + 1, k - 1));
+                                                       intervals.push(new Point(k + 1, j));
+                                               }
+                                       }
+                               }
+                       }
+                       return false;
+               }
+               
+               /**
+                * We compute helixesStructWithoutPseudoKnots
+                * from helixesStruct by replacing values by -1
+                * for the helixes we cut (the bases are become non-paired).
+                * We try to cut as few base pairs as possible.
+                */
+               private void removePseudoKnotsAux() {
+                       if (!isSelfCrossing()) {
+                               helixesStructWithoutPseudoKnots = new int[helixesStruct.size()];
+                               for (int i=0; i<helixesStructWithoutPseudoKnots.length; i++) {
+                                       helixesStructWithoutPseudoKnots[i] = helixesStruct.get(i);
+                               }
+                       } else {
+                               
+                               // We need to get rid of pseudoknots
+                               // This code was adapted from RNAMLParser.planarize()
+                               int length = helixesStruct.size();
+       
+                               int[] result = new int[length];
+                               for (int i = 0; i < result.length; i++) {
+                                       result[i] = -1;
+                               }
+       
+                               short[][] tab = new short[length][length];
+                               short[][] backtrack = new short[length][length];
+       
+                               // On the diagonal we have intervals containing only
+                               // one endpoint. Therefore there can be no helix
+                               // (because an helix consists of 2 elements).
+                               for (int i = 0; i < result.length; i++) {
+                                       // tab[i][j] = 0;
+                                       backtrack[i][i] = -1;
+                               }
+                               
+                               for (int n = 1; n < length; n++) {
+                                       for (int i = 0; i < length - n; i++) {
+                                               int j = i + n;
+                                               tab[i][j] = tab[i + 1][j];
+                                               backtrack[i][j] = -1;
+                                               int k = helixesStruct.get(i);
+                                               assert k != -1;
+                                               if ((k <= j) && (i < k)) {
+                                                       int tmp = helixesSeq.get(i).getLength();
+                                                       if (i + 1 <= k - 1) {
+                                                               tmp += tab[i + 1][k - 1];
+                                                       }
+                                                       if (k + 1 <= j) {
+                                                               tmp += tab[k + 1][j];
+                                                       }
+                                                       if (tmp > tab[i][j]) {
+                                                               tab[i][j] = (short) tmp;
+                                                               backtrack[i][j] = (short) k;
+                                                       }
+                                               }
+                                       }
+                               }
+                               
+                               // debug
+                               //RNATemplateTests.printShortMatrix(tab);
+                               
+                               Stack<Point> intervals = new Stack<Point>();
+                               intervals.add(new Point(0, length - 1));
+                               while (!intervals.empty()) {
+                                       Point p = intervals.pop();
+                                       if (p.x <= p.y) {
+                                               if (backtrack[p.x][p.y] == -1) {
+                                                       result[p.x] = -1;
+                                                       intervals.push(new Point(p.x + 1, p.y));
+                                               } else {
+                                                       int i = p.x;
+                                                       int j = p.y;
+                                                       int k = backtrack[i][j];
+                                                       result[i] = k;
+                                                       result[k] = i;
+                                                       intervals.push(new Point(i + 1, k - 1));
+                                                       intervals.push(new Point(k + 1, j));
+                                               }
+                                       }
+                               }
+                               
+                               helixesStructWithoutPseudoKnots = result;
+                       }
+               }
+               
+               private Set<RNATemplateHelix> makeSet() {
+                       Set<RNATemplateHelix> removedHelixes = new HashSet<RNATemplateHelix>();
+                       
+                       for (int i=0; i<helixesStructWithoutPseudoKnots.length; i++) {
+                               if (helixesStructWithoutPseudoKnots[i] < 0) {
+                                       removedHelixes.add(helixesSeq.get(i));
+                               }
+                       }
+                       
+                       return removedHelixes;
+               }
+               
+               public Set<RNATemplateHelix> removePseudoKnots() throws ExceptionInvalidRNATemplate {
+                       initArrays();
+                       
+                       removePseudoKnotsAux();
+                       // debug
+                       //printIntArrayList(helixesStruct);
+                       //printIntArray(helixesStructWithoutPseudoKnots);
+                       
+                       return makeSet();
+               }
+       }
+       
+       private class ConvertToTree {
+               private Set<RNATemplateHelix> removedHelixes;
+               
+               public ConvertToTree(Set<RNATemplateHelix> removedHelixes) {
+                       this.removedHelixes = removedHelixes;
+               }
+               
+               private Iterator<RNATemplateElement> iter = template.rnaIterator();
+               private Set<RNATemplateHelix> knownHelixes = new HashSet<RNATemplateHelix>();
+               
+               public Tree<RNANodeValueTemplate> convert() throws ExceptionInvalidRNATemplate {
+                       Tree<RNANodeValueTemplate> root = new Tree<RNANodeValueTemplate>();
+                        // No value, this is a fake node because we need a root.
+                       root.setValue(null);
+                       makeChildren(root);
+                       return root;
+               }
+               
+               private void makeChildren(Tree<RNANodeValueTemplate> father) throws ExceptionInvalidRNATemplate {
+                       List<Tree<RNANodeValueTemplate>> children = father.getChildren();
+                       while (true) {
+                               try {
+                                       RNATemplateElement element = iter.next();
+                                       if (element instanceof RNATemplateHelix) {
+                                               RNATemplateHelix helix = (RNATemplateHelix) element;
+                                               if (removedHelixes.contains(helix)) {
+                                                       // Helix was removed
+                                                       
+                                                       boolean firstPartOfHelix;
+                                                       if (knownHelixes.contains(helix)) {
+                                                               firstPartOfHelix = false;
+                                                       } else {
+                                                               knownHelixes.add(helix);
+                                                               firstPartOfHelix = true;
+                                                       }
+                                                       
+                                                       int helixLength = helix.getLength();
+                                                       // Maybe we could allow helixes of length 0?
+                                                       // If we want to then this code can be changed in the future.
+                                                       if (helixLength < 1) {
+                                                               throw (new ExceptionInvalidRNATemplate("Helix length < 1"));
+                                                       }
+                                                       int firstPosition = firstPartOfHelix ? 0 : helixLength;
+                                                       int afterLastPosition = firstPartOfHelix ? helixLength : 2*helixLength;
+                                                       for (int i=firstPosition; i<afterLastPosition; i++) {
+                                                               RNANodeValueTemplateBrokenBasePair value = new RNANodeValueTemplateBrokenBasePair();
+                                                               value.setHelix(helix);
+                                                               value.setPositionInHelix(i);
+                                                               Tree<RNANodeValueTemplate> child = new Tree<RNANodeValueTemplate>();
+                                                               child.setValue(value);
+                                                               father.getChildren().add(child);
+                                                       }
+                                                       
+                                               } else {
+                                                       // We have an non-removed helix
+                                                       
+                                                       if (knownHelixes.contains(helix)) {
+                                                               if ((! (father.getValue() instanceof RNANodeValueTemplateBasePair))
+                                                                               || ((RNANodeValueTemplateBasePair) father.getValue()).getHelix() != helix) {
+                                                                       // We have already met this helix, so unless it is our father,
+                                                                       // we have a pseudoknot (didn't we remove them???).
+                                                                       throw (new ExceptionInvalidRNATemplate("Unexpected helix. Looks like there still are pseudoknots even after we removed them so something is wrong about the template."));
+                                                               } else {
+                                                                       // As we have found the father, we have finished our work
+                                                                       // with the children.
+                                                                       return;
+                                                               }
+                                                       } else {
+                                                               knownHelixes.add(helix);
+                                                               
+                                                               int helixLength = helix.getLength();
+                                                               // Maybe we could allow helixes of length 0?
+                                                               // If we want to then this code can be changed in the future.
+                                                               if (helixLength < 1) {
+                                                                       throw (new ExceptionInvalidRNATemplate("Helix length < 1"));
+                                                               }
+                                                               Tree<RNANodeValueTemplate> lastChild = father;
+                                                               for (int i=0; i<helixLength; i++) {
+                                                                       RNANodeValueTemplateBasePair value = new RNANodeValueTemplateBasePair();
+                                                                       value.setHelix(helix);
+                                                                       value.setPositionInHelix(i);
+                                                                       Tree<RNANodeValueTemplate> child = new Tree<RNANodeValueTemplate>();
+                                                                       child.setValue(value);
+                                                                       lastChild.getChildren().add(child);
+                                                                       lastChild = child;
+                                                               }
+                                                               // Now we put what follows as children of lastChild
+                                                               makeChildren(lastChild);
+                                                       }
+                                                       
+                                                       
+                                               }
+                                       } else if (element instanceof RNATemplateUnpairedSequence) {
+                                               RNATemplateUnpairedSequence sequence = (RNATemplateUnpairedSequence) element;
+                                               int seqLength = sequence.getLength();
+                                               
+                                               // Maybe we could allow sequences of length 0?
+                                               // If we want to then this code can be changed in the future.
+                                               if (seqLength < 1) {
+                                                       throw (new ExceptionInvalidRNATemplate("Non-paired sequence length < 1"));
+                                               }
+                                               
+                                               RNANodeValueTemplateSequence value = new RNANodeValueTemplateSequence();
+                                               value.setSequence(sequence);
+                                               Tree<RNANodeValueTemplate> child = new Tree<RNANodeValueTemplate>();
+                                               child.setValue(value);
+                                               children.add(child);
+                                       } else {
+                                               throw (new ExceptionInvalidRNATemplate("We have an endpoint which is neither an helix nor a sequence. What is that?"));
+                                       }
+                                       
+                               } catch (NoSuchElementException e) {
+                                       // We are at the end of elements so if everything is ok
+                                       // the father must be the root.
+                                       if (father.getValue() == null) {
+                                               return; // Work finished.
+                                       } else {
+                                               throw (new ExceptionInvalidRNATemplate("Unexpected end of template endpoint list."));
+                                       }
+                               }
+                       }
+               }
+       
+       }
+       
+       /**
+        * Tells whether the connected component to which endPoint belongs to
+        * is cyclic.
+        */
+       public boolean connectedComponentIsCyclic(EdgeEndPoint endPoint) {
+               Set<EdgeEndPoint> knownEndPoints = new HashSet<EdgeEndPoint>();
+               EdgeEndPoint currentEndPoint = endPoint;
+               while (true) {
+                       if (knownEndPoints.contains(currentEndPoint)) {
+                               return true;
+                       }
+                       knownEndPoints.add(currentEndPoint);
+                       EdgeEndPoint previousEndPoint = currentEndPoint.getPreviousEndPoint();
+                       if (previousEndPoint == null) {
+                               return false;
+                       } else {
+                               currentEndPoint = previousEndPoint;
+                       }
+               }
+       }
+       
+       /**
+        * Tells whether the template elements are all connected, ie. if the
+        * graph (edge endpoints being vertices) is connected. 
+        */
+       public boolean isConnected() {
+               if (isEmpty()) {
+                       return true;
+               }
+               
+               // Count all vertices
+               int n = 0;
+               for (RNATemplateElement element: elements) {
+                       if (element instanceof RNATemplateHelix) {
+                               n += 4;
+                       } else if (element instanceof RNATemplateUnpairedSequence) {
+                               n += 2;
+                       }
+               }
+               
+               // Now try reaching all vertices
+               Set<EdgeEndPoint> knownEndPoints = new HashSet<EdgeEndPoint>();
+               EdgeEndPoint currentEndPoint = getFirstEndPoint();
+               while (true) {
+                       if (knownEndPoints.contains(currentEndPoint)) {
+                               // We are back to our original endpoint, so stop
+                               break;
+                       }
+                       knownEndPoints.add(currentEndPoint);
+                       EdgeEndPoint nextEndPoint = currentEndPoint.getNextEndPoint();
+                       if (nextEndPoint == null) {
+                               break;
+                       } else {
+                               currentEndPoint = nextEndPoint;
+                       }
+               }
+               
+               // The graph is connected iff the number of reached vertices
+               // is equal to the total number of vertices.
+               return (knownEndPoints.size() == n);
+
+       }
+
+       /**
+        * Checks whether this template is a valid RNA template, ie.
+        * it is non-empty, it does not contain a cycle and all elements are in one
+        * connected component.
+        */
+       public void checkIsValidTemplate() throws ExceptionInvalidRNATemplate {
+               if (isEmpty()) {
+                       throw (new ExceptionInvalidRNATemplate("The template is empty."));
+               }
+               
+               if (! isConnected()) {
+                       throw (new ExceptionInvalidRNATemplate("The template is a non-connected graph."));
+               }
+               
+               // Now we know the graph is connected.
+               
+               if (connectedComponentIsCyclic(getAnyEndPoint())) {
+                       throw (new ExceptionInvalidRNATemplate("The template is cyclic."));
+               }
+       }
+       
+       /**
+        * Make a tree of the template. For this, we will remove pseudoknots,
+        * taking care to remove as few base pair links as possible.
+        * Requires the template to be valid and will check the validity
+        * (will call checkIsValidTemplate()).
+        * Calling this method will automatically call computeIn1Is().
+        */
+       public Tree<RNANodeValueTemplate> toTree() throws ExceptionInvalidRNATemplate {
+               // Compute the helix in1Is fields.
+               // We also rely on computeIn1Is() for checking the template validity.
+               computeIn1Is();
+               
+               // Remove pseudoknots
+               RemovePseudoKnots pseudoKnotKiller = new RemovePseudoKnots();
+               Set<RNATemplateHelix> removedHelixes = pseudoKnotKiller.removePseudoKnots();
+               
+               // Convert to tree
+               ConvertToTree converter = new ConvertToTree(removedHelixes);
+               return converter.convert();
+       }
+       
+       
+       /**
+        * Generate an RNA sequence that exactly matches the template.
+        * Requires the template to be valid and will check the validity
+        * (will call checkIsValidTemplate()).
+        */
+       public RNA toRNA() throws ExceptionInvalidRNATemplate {
+               // First, we check this is a valid template
+               checkIsValidTemplate();
+               
+               ArrayList<Integer> str = new ArrayList<Integer>();
+               Map<RNATemplateHelix, ArrayList<Integer>> helixes = new HashMap<RNATemplateHelix, ArrayList<Integer>>();
+               Iterator<RNATemplateElement> iter = rnaIterator();
+               while (iter.hasNext()) {
+                       RNATemplateElement element = iter.next();
+                       if (element instanceof RNATemplateHelix) {
+                               RNATemplateHelix helix = (RNATemplateHelix) element;
+                               int n = helix.getLength();
+                               if (helixes.containsKey(helix)) {
+                                       int firstBase = str.size();
+                                       ArrayList<Integer> helixMembers = helixes.get(helix);
+                                       for (int i = 0; i < n; i++) {
+                                               int indexOfAssociatedBase = helixMembers.get(n-1-i);
+                                               str.set(indexOfAssociatedBase, firstBase + i);
+                                               str.add(indexOfAssociatedBase);
+                                       }
+                               } else {
+                                       int firstBase = str.size();
+                                       ArrayList<Integer> helixMembers = new ArrayList<Integer>();
+                                       for (int i = 0; i < n; i++) {
+                                               // We don't known yet where the associated base is
+                                               str.add(-1);
+                                               helixMembers.add(firstBase + i);
+                                       }
+                                       helixes.put(helix, helixMembers);
+                               }
+                       } else if (element instanceof RNATemplateUnpairedSequence) {
+                               RNATemplateUnpairedSequence sequence = (RNATemplateUnpairedSequence) element;
+                               int n = sequence.getLength();
+                               for (int i=0; i<n; i++) {
+                                       str.add(-1);
+                               }
+                       } else {
+                               throw (new ExceptionInvalidRNATemplate("We have an endpoint which is neither an helix nor a sequence. What is that?"));
+                       }
+               }
+               
+               int[] strAsArray = RNATemplateAlign.intArrayFromList(str);
+               String[] seqAsArray = new String[strAsArray.length];
+               Arrays.fill(seqAsArray, " ");
+               RNA rna = new RNA();
+               try {
+                       rna.setRNA(seqAsArray, strAsArray);
+               } catch (ExceptionFileFormatOrSyntax e) {
+                       throw (new RuntimeException("Bug in toRNA(): setRNA() threw an ExceptionFileFormatOrSyntax exception."));
+               }
+               return rna;
+       }
+       
+       
+       private class ConvertToXml {
+               private Map<RNATemplateElement, String> elementNames = new HashMap<RNATemplateElement, String>();
+               private Element connectionsXmlElement;
+               private Document document;
+               
+               private void addConnectionIfNecessary(EdgeEndPoint endPoint) {
+                       if (endPoint != null && endPoint.isConnected()) {
+                               RNATemplateElement e1 = endPoint.getElement();
+                               EdgeEndPointPosition p1 = endPoint.getPosition();
+                               RNATemplateElement e2 = endPoint.getOtherElement();
+                               EdgeEndPointPosition p2 = endPoint.getOtherEndPoint().getPosition();
+                               Element xmlElement = document.createElement("edge");
+                               {
+                                       Element fromXmlElement = document.createElement("from");
+                                       fromXmlElement.setAttribute("endpoint", elementNames.get(e1));
+                                       fromXmlElement.setAttribute("position", p1.toString());
+                                       xmlElement.appendChild(fromXmlElement);
+                               }
+                               {
+                                       Element toXmlElement = document.createElement("to");
+                                       toXmlElement.setAttribute("endpoint", elementNames.get(e2));
+                                       toXmlElement.setAttribute("position", p2.toString());
+                                       xmlElement.appendChild(toXmlElement);
+                               }
+                               connectionsXmlElement.appendChild(xmlElement);
+                       }
+               }
+               
+               public Document toXMLDocument() throws ExceptionXMLGeneration, ExceptionInvalidRNATemplate {
+                       try {
+                               DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+                               DocumentBuilder builder = factory.newDocumentBuilder();
+                               document = builder.newDocument();
+                               Element root = document.createElement("RNATemplate");
+                               document.appendChild(root);
+                               Element elementsXmlElement = document.createElement("elements");
+                               root.appendChild(elementsXmlElement);
+                               connectionsXmlElement = document.createElement("edges");
+                               root.appendChild(connectionsXmlElement);
+                               
+                               // First pass, we create a mapping between java references and names (strings)
+                               {
+                                       int nextHelix = 1;
+                                       int nextNonPairedSequence = 1;
+                                       for (RNATemplateElement templateElement: elements) {
+                                               if (templateElement instanceof RNATemplateHelix) {
+                                                       RNATemplateHelix helix = (RNATemplateHelix) templateElement;
+                                                       if (! elementNames.containsKey(helix)) {
+                                                               elementNames.put(helix, "H ID " + nextHelix);
+                                                               nextHelix++;
+                                                       }
+                                               } else if (templateElement instanceof RNATemplateUnpairedSequence) {
+                                                       RNATemplateUnpairedSequence sequence = (RNATemplateUnpairedSequence) templateElement;
+                                                       if (! elementNames.containsKey(sequence)) {
+                                                               elementNames.put(sequence, "S ID " + nextNonPairedSequence);
+                                                               nextNonPairedSequence++;
+                                                       }
+                                               } else {
+                                                       throw (new ExceptionInvalidRNATemplate("We have an endpoint which is neither an helix nor a sequence. What is that?"));
+                                               }
+                                       }
+                               }
+                               
+                               // Now we generate the XML document
+                               for (RNATemplateElement templateElement: elements) {
+                                       String elementXmlName = elementNames.get(templateElement);
+                                       Element xmlElement;
+                                       if (templateElement instanceof RNATemplateHelix) {
+                                               RNATemplateHelix helix = (RNATemplateHelix) templateElement;
+                                               xmlElement = document.createElement("helix");
+                                               xmlElement.setAttribute("id", elementXmlName);
+                                               xmlElement.setAttribute("length", Integer.toString(helix.getLength()));
+                                               xmlElement.setAttribute("flipped", Boolean.toString(helix.isFlipped()));
+                                               if (helix.hasCaption()) {
+                                                       xmlElement.setAttribute("caption", helix.getCaption());
+                                               }
+                                               {
+                                                       Element startPositionXmlElement = document.createElement("startPosition");
+                                                       startPositionXmlElement.setAttribute("x", Double.toString(helix.getStartPosition().x));
+                                                       startPositionXmlElement.setAttribute("y", Double.toString(helix.getStartPosition().y));
+                                                       xmlElement.appendChild(startPositionXmlElement);
+                                               }
+                                               {
+                                                       Element endPositionXmlElement = document.createElement("endPosition");
+                                                       endPositionXmlElement.setAttribute("x", Double.toString(helix.getEndPosition().x));
+                                                       endPositionXmlElement.setAttribute("y", Double.toString(helix.getEndPosition().y));
+                                                       xmlElement.appendChild(endPositionXmlElement);
+                                               }
+                                               addConnectionIfNecessary(helix.getOut1());
+                                               addConnectionIfNecessary(helix.getOut2());
+                                       } else if (templateElement instanceof RNATemplateUnpairedSequence) {
+                                               RNATemplateUnpairedSequence sequence = (RNATemplateUnpairedSequence) templateElement;
+                                               xmlElement = document.createElement("sequence");
+                                               xmlElement.setAttribute("id", elementXmlName);
+                                               xmlElement.setAttribute("length", Integer.toString(sequence.getLength()));
+                                               {
+                                                       Element vertex5XmlElement = document.createElement("vertex5");
+                                                       vertex5XmlElement.setAttribute("x", Double.toString(sequence.getVertex5().x));
+                                                       vertex5XmlElement.setAttribute("y", Double.toString(sequence.getVertex5().y));
+                                                       xmlElement.appendChild(vertex5XmlElement);
+                                               }
+                                               {
+                                                       Element vertex3XmlElement = document.createElement("vertex3");
+                                                       vertex3XmlElement.setAttribute("x", Double.toString(sequence.getVertex3().x));
+                                                       vertex3XmlElement.setAttribute("y", Double.toString(sequence.getVertex3().y));
+                                                       xmlElement.appendChild(vertex3XmlElement);
+                                               }
+                                               {
+                                                       Element inTangentVectorXmlElement = document.createElement("inTangentVector");
+                                                       inTangentVectorXmlElement.setAttribute("angle", Double.toString(sequence.getInTangentVectorAngle()));
+                                                       inTangentVectorXmlElement.setAttribute("length", Double.toString(sequence.getInTangentVectorLength()));
+                                                       xmlElement.appendChild(inTangentVectorXmlElement);
+                                               }
+                                               {
+                                                       Element outTangentVectorXmlElement = document.createElement("outTangentVector");
+                                                       outTangentVectorXmlElement.setAttribute("angle", Double.toString(sequence.getOutTangentVectorAngle()));
+                                                       outTangentVectorXmlElement.setAttribute("length", Double.toString(sequence.getOutTangentVectorLength()));
+                                                       xmlElement.appendChild(outTangentVectorXmlElement);
+                                               }
+                                               addConnectionIfNecessary(sequence.getOut());
+                                       } else {
+                                               throw (new ExceptionInvalidRNATemplate("We have an endpoint which is neither an helix nor a sequence. What is that?"));
+                                       }
+                                       elementsXmlElement.appendChild(xmlElement);
+                               }
+                               
+                               return document;
+                       } catch (ParserConfigurationException e) {
+                               throw (new ExceptionXMLGeneration("ParserConfigurationException: " + e.getMessage()));
+                       }
+               }
+       }
+       
+       
+       
+       public void toXMLFile(File file) throws ExceptionXMLGeneration, ExceptionInvalidRNATemplate {
+               try {
+                       Document xmlDocument = toXMLDocument();
+                       Source source = new DOMSource(xmlDocument);
+                       Result result = new StreamResult(file);
+                       Transformer transformer;
+                       transformer = TransformerFactory.newInstance().newTransformer();
+                       transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+                       transformer.transform(source, result); 
+               } catch (TransformerConfigurationException e) {
+                       throw (new ExceptionXMLGeneration("TransformerConfigurationException: " + e.getMessage()));
+               } catch (TransformerFactoryConfigurationError e) {
+                       throw (new ExceptionXMLGeneration("TransformerFactoryConfigurationError: " + e.getMessage()));
+               } catch (TransformerException e) {
+                       throw (new ExceptionXMLGeneration("TransformerException: " + e.getMessage()));
+               }
+       }
+
+       
+       public Document toXMLDocument() throws ExceptionXMLGeneration, ExceptionInvalidRNATemplate {
+               ConvertToXml converter = new ConvertToXml();
+               return converter.toXMLDocument();
+       }
+       
+       
+       private class LoadFromXml {
+               private Document xmlDocument;
+               private Map<String, RNATemplateElement> elementNames = new HashMap<String, RNATemplateElement>();
+               
+               public LoadFromXml(Document xmlDocument) {
+                       this.xmlDocument = xmlDocument;
+               }
+               
+               private Point2D.Double pointFromXml(Element xmlPoint) {
+                       Point2D.Double point = new Point2D.Double();
+                       point.x = Double.parseDouble(xmlPoint.getAttribute("x"));
+                       point.y = Double.parseDouble(xmlPoint.getAttribute("y"));
+                       return point;
+               }
+               
+               private double vectorLengthFromXml(Element xmlVector) {
+                       return Double.parseDouble(xmlVector.getAttribute("length"));
+               }
+               
+               private double vectorAngleFromXml(Element xmlVector) {
+                       return Double.parseDouble(xmlVector.getAttribute("angle"));
+               }
+               
+               /**
+                * Takes an element of the form:
+                * <anything endpoint="an element id" position="a valid EdgeEndPointPosition"/>
+                * and returns the corresponding EdgeEndPoint object. 
+                */
+               private EdgeEndPoint endPointFromXml(Element xmlEdgeEndPoint) throws ExceptionXmlLoading {
+                       String elementId = xmlEdgeEndPoint.getAttribute("endpoint");
+                       if (elementId == null || elementId == "")
+                               throw (new ExceptionXmlLoading ("Missing endpoint attribute on " + xmlEdgeEndPoint));
+                       String positionOnElement = xmlEdgeEndPoint.getAttribute("position");
+                       if (positionOnElement == null || positionOnElement == "")
+                               throw (new ExceptionXmlLoading ("Missing position attribute on " + xmlEdgeEndPoint));
+                       if (elementNames.containsKey(elementId)) {
+                               RNATemplateElement templateElement = elementNames.get(elementId);
+                               EdgeEndPointPosition relativePosition = EdgeEndPointPosition.valueOf(positionOnElement);
+                               if (relativePosition == null)
+                                       throw (new ExceptionXmlLoading ("Could not compute relativePosition"));
+                               return templateElement.getEndPointFromPosition(relativePosition);
+                       } else {
+                               throw (new ExceptionXmlLoading("Edge is connected on unkown element: " + elementId));
+                       }
+               }
+               
+               private String connectErrMsg(EdgeEndPoint v1, EdgeEndPoint v2, String reason) {
+                       return "Error while connecting\n"
+                       + v1.toString() + " to\n"
+                       + v2.toString() + " because:\n"
+                       + reason;
+               }
+               
+               private void connect(EdgeEndPoint v1, EdgeEndPoint v2) throws ExceptionXmlLoading {
+                       if (v1 == null || v2 == null) {
+                               throw (new ExceptionXmlLoading("Invalid edge: missing endpoint\n v1 = " + v1 + "\n v2 = " + v2));
+                       }
+                       if (v2.isConnected()) {
+                               throw (new ExceptionXmlLoading(connectErrMsg(v1, v2, "Second vertex is already connected to " + v2.getOtherElement().toString())));
+                       }
+                       if (v1.isConnected()) {
+                               throw (new ExceptionXmlLoading(connectErrMsg(v1, v2, "First vertex is already connected to " + v1.getOtherElement().toString())));
+                       }
+                       
+                       try {
+                               v1.connectTo(v2);
+                       } catch (ExceptionEdgeEndpointAlreadyConnected e) {
+                               throw (new ExceptionXmlLoading("A vertex is on two edges at the same time: " + e.getMessage()));
+                       } catch (ExceptionInvalidRNATemplate e) {
+                               throw (new ExceptionXmlLoading("ExceptionInvalidRNATemplate: " + e.getMessage()));
+                       }
+               }
+               
+               public void load() throws ExceptionXmlLoading {
+                       // First part: we load all elements from the XML tree
+                       Element xmlElements = (Element) xmlDocument.getElementsByTagName("elements").item(0);
+                       {
+                               NodeList xmlElementsChildren = xmlElements.getChildNodes();
+                               for (int i=0; i<xmlElementsChildren.getLength(); i++) {
+                                       Node xmlElementsChild = xmlElementsChildren.item(i);
+                                       if (xmlElementsChild instanceof Element) {
+                                               Element xmlTemplateElement = (Element) xmlElementsChild;
+                                               String tagName = xmlTemplateElement.getTagName();
+                                               if (tagName == "helix") {
+                                                       RNATemplateHelix helix = new RNATemplateHelix(xmlTemplateElement.getAttribute("id"));
+                                                       helix.setFlipped(Boolean.parseBoolean(xmlTemplateElement.getAttribute("flipped")));
+                                                       helix.setLength(Integer.parseInt(xmlTemplateElement.getAttribute("length")));
+                                                       if (xmlTemplateElement.hasAttribute("caption")) {
+                                                               helix.setCaption(xmlTemplateElement.getAttribute("caption"));
+                                                       }
+                                                       elementNames.put(xmlTemplateElement.getAttribute("id"), helix);
+                                                       NodeList xmlHelixChildren = xmlTemplateElement.getChildNodes();
+                                                       for (int j=0; j<xmlHelixChildren.getLength(); j++) {
+                                                               Node xmlHelixChild = xmlHelixChildren.item(j);
+                                                               if (xmlHelixChild instanceof Element) {
+                                                                       Element xmlHelixChildElement = (Element) xmlHelixChild;
+                                                                       String helixChildTagName = xmlHelixChildElement.getTagName();
+                                                                       if (helixChildTagName == "startPosition") {
+                                                                               helix.setStartPosition(pointFromXml(xmlHelixChildElement));
+                                                                       } else if (helixChildTagName == "endPosition") {
+                                                                               helix.setEndPosition(pointFromXml(xmlHelixChildElement));
+                                                                       }
+                                                               }
+                                                       }
+                                               } else if (tagName == "sequence") {
+                                                       RNATemplateUnpairedSequence sequence = new RNATemplateUnpairedSequence(xmlTemplateElement.getAttribute("id"));
+                                                       sequence.setLength(Integer.parseInt(xmlTemplateElement.getAttribute("length")));
+                                                       elementNames.put(xmlTemplateElement.getAttribute("id"), sequence);
+                                                       NodeList xmlSequenceChildren = xmlTemplateElement.getChildNodes();
+                                                       for (int j=0; j<xmlSequenceChildren.getLength(); j++) {
+                                                               Node xmlSequenceChild = xmlSequenceChildren.item(j);
+                                                               if (xmlSequenceChild instanceof Element) {
+                                                                       Element xmlSequenceChildElement = (Element) xmlSequenceChild;
+                                                                       String sequenceChildTagName = xmlSequenceChildElement.getTagName();
+                                                                       if (sequenceChildTagName == "inTangentVector") {
+                                                                               sequence.setInTangentVectorLength(vectorLengthFromXml(xmlSequenceChildElement));
+                                                                               sequence.setInTangentVectorAngle(vectorAngleFromXml(xmlSequenceChildElement));
+                                                                       } else if (sequenceChildTagName == "outTangentVector") {
+                                                                               sequence.setOutTangentVectorLength(vectorLengthFromXml(xmlSequenceChildElement));
+                                                                               sequence.setOutTangentVectorAngle(vectorAngleFromXml(xmlSequenceChildElement));
+                                                                       } else if (sequenceChildTagName == "vertex5") {
+                                                                               sequence.setVertex5(pointFromXml(xmlSequenceChildElement));
+                                                                       } else if (sequenceChildTagName == "vertex3") {
+                                                                               sequence.setVertex3(pointFromXml(xmlSequenceChildElement));
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+                       
+                       // Second part: We read the edges from the XML tree
+                       Element xmlEdges = (Element) xmlDocument.getElementsByTagName("edges").item(0);
+                       {
+                               NodeList xmlEdgesChildren = xmlEdges.getChildNodes();
+                               for (int i=0; i<xmlEdgesChildren.getLength(); i++) {
+                                       Node xmlEdgesChild = xmlEdgesChildren.item(i);
+                                       if (xmlEdgesChild instanceof Element) {
+                                               Element xmlTemplateEdge = (Element) xmlEdgesChild;
+                                               if (xmlTemplateEdge.getTagName() == "edge") {
+                                                       EdgeEndPoint v1 = null, v2 = null;
+                                                       NodeList xmlEdgeChildren = xmlTemplateEdge.getChildNodes();
+                                                       for (int j=0; j<xmlEdgeChildren.getLength(); j++) {
+                                                               Node xmlEdgeChild = xmlEdgeChildren.item(j);
+                                                               if (xmlEdgeChild instanceof Element) {
+                                                                       Element xmlEdgeChildElement = (Element) xmlEdgeChild;
+                                                                       String edgeChildTagName = xmlEdgeChildElement.getTagName();
+                                                                       if (edgeChildTagName == "from") {
+                                                                               v1 = endPointFromXml(xmlEdgeChildElement);
+                                                                       } else if (edgeChildTagName == "to") {
+                                                                               v2 = endPointFromXml(xmlEdgeChildElement);
+                                                                       }
+                                                               }
+                                                       }
+                                                       if (v1 == null)
+                                                               throw (new ExceptionXmlLoading("Invalid edge: missing \"from\" declaration"));
+                                                       if (v2 == null)
+                                                               throw (new ExceptionXmlLoading("Invalid edge: missing \"to\" declaration"));
+                                                       connect(v1, v2);
+                                               }
+                                       }
+                               }
+                       
+                       }
+               }
+       }
+       
+       
+       public static RNATemplate fromXMLFile(File file) throws ExceptionXmlLoading {
+               try {
+                       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+                       factory.setIgnoringElementContentWhitespace(true);
+                       DocumentBuilder builder = factory.newDocumentBuilder();
+                       Document xmlDocument = builder.parse(file);
+                       return fromXMLDocument(xmlDocument);
+               } catch (ParserConfigurationException e) {
+                       throw (new ExceptionXmlLoading("ParserConfigurationException: " + e.getMessage()));
+               } catch (SAXException e) {
+                       throw (new ExceptionXmlLoading("SAXException: " + e.getMessage()));
+               } catch (IOException e) {
+                       throw (new ExceptionXmlLoading("IOException: " + e.getMessage()));
+               }
+       }
+       
+       
+       public static RNATemplate fromXMLDocument(Document xmlDocument) throws ExceptionXmlLoading {
+               RNATemplate template = new RNATemplate();
+               LoadFromXml loader = template.new LoadFromXml(xmlDocument);
+               loader.load();
+               return template;
+       }
+       
+       
+       
+       /**
+        * For an helix, tells us whether IN1/OUT1 is the 5' strand
+        * (the first strand we meet if we follow the RNA sequence)
+        * or the 3' strand (the second we meet if we follow the RNA sequence).
+        */
+       public enum In1Is {
+               IN1_IS_5PRIME, IN1_IS_3PRIME
+       }
+       
+       
+       /**
+        * For each helix, compute the in1Is field.
+        * If helices connections are changed, the value may become obsolete,
+        * so you need to call this method again before accessing the in1Is
+        * fields if you have modified connections in the template.
+        * Requires the template to be valid and will check the validity
+        * (will call checkIsValidTemplate()).
+        */
+       public void computeIn1Is() throws ExceptionInvalidRNATemplate {
+               checkIsValidTemplate();
+               
+               Iterator<EdgeEndPoint> iter = vertexIterator();
+               Set<RNATemplateHelix> knownHelices = new HashSet<RNATemplateHelix>();
+               while (iter.hasNext()) {
+                       EdgeEndPoint endPoint = iter.next();
+                       RNATemplateElement templateElement = endPoint.getElement();
+                       if (templateElement instanceof RNATemplateHelix) {
+                               RNATemplateHelix helix = (RNATemplateHelix) templateElement;
+                               if (! knownHelices.contains(helix)) {
+                                       // first time we meet this helix
+                                       switch (endPoint.getPosition()) {
+                                       case IN1:
+                                       case OUT1:
+                                               helix.setIn1Is(In1Is.IN1_IS_5PRIME);
+                                               break;
+                                       case IN2:
+                                       case OUT2:
+                                               helix.setIn1Is(In1Is.IN1_IS_3PRIME);
+                                               break;
+                                       }
+                                       knownHelices.add(helix);
+                               }
+                       }
+               }
+       }
+       
+       
+       
+       /**
+        * Remove the element from the template.
+        * The element is automatically disconnected from any other element.
+        * Returns true if and only if the element was present in the template,
+        * otherwise nothing was done.
+        */
+       public boolean removeElement(RNATemplateElement element) throws ExceptionInvalidRNATemplate {
+               if (elements.contains(element)) {
+                       element.disconnectFromAny();
+                       elements.remove(element);
+                       return true;
+               } else {
+                       return false;
+               }
+       }
+       
+       
+       /**
+        * Position of an endpoint on an endpoint.
+        * Not all values make sense for any endpoint.
+        * For an helix, all four make sense, but for a non-paired
+        * sequence, only IN1 and OUT1 make sense.
+        */
+       public enum EdgeEndPointPosition {
+               IN1, IN2, OUT1, OUT2;
+       }
+       
+       
+       private static int NEXT_ID = 1;
+       
+       /**
+        * An endpoint of an RNA template,
+        * it can be an helix or a sequence of non-paired bases.
+        * 
+        * You cannot create an object of this class directly,
+        * use RNATemplateHelix or RNATemplateUnpairedSequence instead.
+        * 
+        * @author Raphael Champeimont
+        */
+       public abstract class RNATemplateElement {
+               
+               public int _id = NEXT_ID++;
+               
+               public String getName()
+               {return "RNATemplate"+_id; }
+               
+               
+               /**
+                * This variable is just there so that "this" can be accessed by a name
+                * from the internal class EdgeEndPoint.
+                */
+               private final RNATemplateElement element = this;
+               
+               /**
+                * When the endpoint is created, it is added to the list of elements
+                * in this template. To remove it, call RNATemplate.removeElement().
+                */
+               public RNATemplateElement() {
+                       elements.add(this);
+               }
+               
+               /**
+                * Disconnect this endpoint from any other elements it may be connected to.
+                */
+               public abstract void disconnectFromAny();
+               
+               /**
+                * Get the the IN endpoint in the case of a sequence
+                * and the IN1 endpoint in the case of an helix.
+                */
+               public abstract EdgeEndPoint getIn1EndPoint();
+
+               /**
+                * Returns the template to which this endpoint belongs.
+                */
+               public RNATemplate getParentTemplate() {
+                       return template;
+               }
+               
+               /**
+                * Provided endpoint is an endpoint of this endpoint, get the next
+                * endpoint, either on this same endpoint, or or the connected endpoint.
+                * Note that you should use the getNextEndPoint() method of the endpoint
+                * itself directly.
+                */
+               protected abstract EdgeEndPoint getNextEndPoint(EdgeEndPoint endpoint);
+               
+               /**
+                * Provided endpoint is an endpoint of this endpoint, get the previous
+                * endpoint, either on this same endpoint, or or the connected endpoint.
+                * Note that you should use the getPreviousEndPoint() method of the endpoint
+                * itself directly.
+                */
+               protected abstract EdgeEndPoint getPreviousEndPoint(EdgeEndPoint endpoint);
+
+               
+               /**
+                * An edge endpoint is where an edge can connect.
+                */
+               public class EdgeEndPoint {
+                       private EdgeEndPoint() {
+                       }
+                       
+                       /**
+                        * Get the next endpoint. If this endpoint is an "in" endpoint,
+                        * returns the corresponding "out" endpoint. If this endpoint
+                        * is an "out" endpoint, return the connected endpoint if there is
+                        * one, otherwise return null.
+                        */
+                       public EdgeEndPoint getNextEndPoint() {
+                               return element.getNextEndPoint(this);
+                       }
+                       
+                       
+                       /**
+                        * Same as getNextEndPoint(), but with the previous endpoint.
+                        */
+                       public EdgeEndPoint getPreviousEndPoint() {
+                               return element.getPreviousEndPoint(this);
+                       }
+                       
+                       
+                       /**
+                        * Get the position on the endpoint where this endpoint is.
+                        */
+                       public EdgeEndPointPosition getPosition() {
+                               return element.getPositionFromEndPoint(this);
+                       }
+                       
+                       
+                       private EdgeEndPoint otherEndPoint;
+                       
+                       /**
+                        * Returns the endpoint on which this edge endpoint is.
+                        */
+                       public RNATemplateElement getElement() {
+                               return element;
+                       }
+                       
+                       /**
+                        * Returns the other endpoint of the edge.
+                        * Will be null if there is no edge connecter to this endpoint.
+                        */
+                       public EdgeEndPoint getOtherEndPoint() {
+                               return otherEndPoint;
+                       }
+                       /**
+                        * Returns the endpoint at the other endpoint of the edge.
+                        * Will be null if there is no edge connecter to this endpoint.
+                        */
+                       public RNATemplateElement getOtherElement() {
+                               return (otherEndPoint != null) ? otherEndPoint.getElement() : null;
+                       }
+                       
+                       /**
+                        * Disconnect this endpoint from the other, ie. delete the edge
+                        * between them. Note that this will modify both endpoints, and that 
+                        * x.disconnect() is equivalent to x.getOtherEndPoint().disconnect().
+                        * If this endpoint is not connected, does nothing.
+                        */
+                       public void disconnect() {
+                               if (otherEndPoint != null) {
+                                       otherEndPoint.otherEndPoint = null;
+                                       otherEndPoint = null;
+                               }
+                       }
+                       
+                       /**
+                        * Tells whether this endpoint is connected with an edge to
+                        * an other endpoint.
+                        */
+                       public boolean isConnected() {
+                               return (otherEndPoint != null);
+                       }
+
+
+                       /**
+                        * Create an edge between two edge endpoints.
+                        * This is a symmetric operation and it will modify both endpoints.
+                        * It means x.connectTo(y) is equivalent to y.connectTo(x).
+                        * The edge endpoint must be free (ie. not yet connected).
+                        * Also, elements connected together must belong to the same template.
+                        */
+                       public void connectTo(EdgeEndPoint otherEndPoint) throws ExceptionEdgeEndpointAlreadyConnected, ExceptionInvalidRNATemplate {
+                               if (this.otherEndPoint != null || otherEndPoint.otherEndPoint != null) {
+                                       throw (new ExceptionEdgeEndpointAlreadyConnected());
+                               }
+                               if (template != otherEndPoint.getElement().getParentTemplate()) {
+                                       throw (new ExceptionInvalidRNATemplate("Elements from different templates cannot be connected with each other."));
+                               }
+                               this.otherEndPoint = otherEndPoint;
+                               otherEndPoint.otherEndPoint = this;
+                       }
+                       
+
+                       public String toString() {
+                               return "Edge endpoint on element " + element.toString() + " at position " + getPosition().toString();
+                       }
+               }
+               
+               
+               /**
+                * Get the EdgeEndPoint object corresponding to the the given
+                * position on this endpoint.
+                */
+               public abstract EdgeEndPoint getEndPointFromPosition(EdgeEndPointPosition position);
+               
+               
+               /**
+                * The inverse of getEndPointFromPosition.
+                */
+               public abstract EdgeEndPointPosition getPositionFromEndPoint(EdgeEndPoint endPoint);
+               
+               
+               /**
+                * Connect the endpoint at position positionHere of this endpoint
+                * to the otherEndPoint.
+                */
+               public void connectTo(
+                               EdgeEndPointPosition positionHere,
+                               EdgeEndPoint otherEndPoint)
+               throws ExceptionEdgeEndpointAlreadyConnected, ExceptionInvalidRNATemplate {
+                       EdgeEndPoint endPointHere = getEndPointFromPosition(positionHere);
+                       endPointHere.connectTo(otherEndPoint);
+               }
+               
+               /**
+                * Connect the endpoint at position positionHere of this endpoint
+                * to the endpoint of otherElement at position positionOnOtherElement.
+                * @throws ExceptionInvalidRNATemplate 
+                * @throws ExceptionEdgeEndpointAlreadyConnected, ExceptionEdgeEndpointAlreadyConnected 
+                */
+               public void connectTo(
+                               EdgeEndPointPosition positionHere,
+                               RNATemplateElement otherElement,
+                               EdgeEndPointPosition positionOnOtherElement)
+               throws ExceptionEdgeEndpointAlreadyConnected, ExceptionEdgeEndpointAlreadyConnected, ExceptionInvalidRNATemplate {
+                       EdgeEndPoint otherEndPoint = otherElement.getEndPointFromPosition(positionOnOtherElement);
+                       connectTo(positionHere, otherEndPoint);
+               }
+       
+       
+       }
+       
+
+       /**
+        * An helix in an RNA template.
+        * 
+        * @author Raphael Champeimont
+        */
+       public class RNATemplateHelix extends RNATemplateElement {
+               /**
+                * Number of base pairs in the helix.
+                */
+               private int length;
+               
+               /**
+                * Position of the helix start point,
+                * ie. the middle in the line [x,y] where (x,y)
+                * x is the base at the IN1 edge endpoint and
+                * y is the base at the OUT2 edge endpoint.
+                */
+               private Point2D.Double startPosition;
+               
+               /**
+                * Position of the helix end point,
+                * ie. the middle in the line [x,y] where (x,y)
+                * x is the base at the OUT1 edge endpoint and
+                * y is the base at the IN2 edge endpoint.
+                */
+               private Point2D.Double endPosition;
+               
+               
+               /**
+                * Tells whether the helix is flipped.
+                */
+               private boolean flipped = false;
+               
+               public boolean isFlipped() {
+                       return flipped;
+               }
+
+               public void setFlipped(boolean flipped) {
+                       this.flipped = flipped;
+               }
+               
+               /**
+                * For an helix, tells us whether IN1/OUT1 is the 5' strand
+                * (the first strand we meet if we follow the RNA sequence)
+                * or the 3' strand (the second we meet if we follow the RNA sequence).
+                * This information cannot be known locally, we need the complete
+                * template to compute it, see RNATemplate.computeIn1Is().
+                */
+               private In1Is in1Is = null;
+               
+               public In1Is getIn1Is() {
+                       return in1Is;
+               }
+
+               public void setIn1Is(In1Is in1Is) {
+                       this.in1Is = in1Is;
+               }
+               
+               
+               
+               /**
+                * A string displayed on the helix.
+                */
+               private String caption = null;
+               
+               public String getCaption() {
+                       return caption;
+               }
+
+               public void setCaption(String caption) {
+                       this.caption = caption;
+               }
+               
+               public boolean hasCaption() {
+                       return caption != null;
+               }
+
+               
+               
+               
+               /**
+                * If we go through all bases of the RNA from first to last,
+                * we will pass twice through this helix. On time, we arrive
+                * from in1, and leave by out2, and the other time we arrive from
+                * in2 and leave by out2.
+                * Whether we go through in1/out1 or in2/out2 the first time
+                * is written in the in1Is field.
+                */
+               private final EdgeEndPoint in1, out1, in2, out2;
+               private String _name;
+               
+               public RNATemplateHelix(String name) {
+                       in1 = new EdgeEndPoint();
+                       out1 = new EdgeEndPoint();
+                       in2 = new EdgeEndPoint();
+                       out2 = new EdgeEndPoint();
+                       _name = name;
+               }
+               
+               
+
+               
+               
+               public String toString() {
+                       return "Helix    @" + Integer.toHexString(hashCode()) + " len=" + length + " caption=" + caption;
+               }
+               
+               public String getName()
+               {return ""+_name; }
+               
+               
+
+               public int getLength() {
+                       return length;
+               }
+
+               public void setLength(int length) {
+                       this.length = length;
+               }
+
+               public Point2D.Double getStartPosition() {
+                       return startPosition;
+               }
+
+               public void setStartPosition(Point2D.Double startPosition) {
+                       this.startPosition = startPosition;
+               }
+
+               public Point2D.Double getEndPosition() {
+                       return endPosition;
+               }
+
+               public void setEndPosition(Point2D.Double endPosition) {
+                       this.endPosition = endPosition;
+               }
+
+               public EdgeEndPoint getIn1() {
+                       return in1;
+               }
+
+               public EdgeEndPoint getOut1() {
+                       return out1;
+               }
+
+               public EdgeEndPoint getIn2() {
+                       return in2;
+               }
+
+               public EdgeEndPoint getOut2() {
+                       return out2;
+               }
+
+               public void disconnectFromAny() {
+                       getIn1().disconnect();
+                       getIn2().disconnect();
+                       getOut1().disconnect();
+                       getOut2().disconnect();
+               }
+
+
+               protected EdgeEndPoint getNextEndPoint(EdgeEndPoint endpoint) {
+                       if (endpoint == in1) {
+                               return out1;
+                       } else if (endpoint == in2) {
+                               return out2;
+                       } else {
+                               return endpoint.getOtherEndPoint();
+                       }
+               }
+
+
+               protected EdgeEndPoint getPreviousEndPoint(EdgeEndPoint endpoint) {
+                       if (endpoint == out1) {
+                               return in1;
+                       } else if (endpoint == out2) {
+                               return in2;
+                       } else {
+                               return endpoint.getOtherEndPoint();
+                       }
+               }
+
+
+               public EdgeEndPoint getIn1EndPoint() {
+                       return in1;
+               }
+
+               public EdgeEndPoint getEndPointFromPosition(
+                               EdgeEndPointPosition position) {
+                       switch (position) {
+                       case IN1:
+                               return getIn1();
+                       case IN2:
+                               return getIn2();
+                       case OUT1:
+                               return getOut1();
+                       case OUT2:
+                               return getOut2();
+                       default:
+                               return null;
+                       }
+               }
+
+               public EdgeEndPointPosition getPositionFromEndPoint(
+                               EdgeEndPoint endPoint) {
+                       if (endPoint == in1) {
+                               return EdgeEndPointPosition.IN1;
+                       } else if (endPoint == in2) {
+                               return EdgeEndPointPosition.IN2;
+                       } else if (endPoint == out1) {
+                               return EdgeEndPointPosition.OUT1;
+                       } else if (endPoint == out2) {
+                               return EdgeEndPointPosition.OUT2;
+                       } else {
+                               return null;
+                       }
+               }
+
+
+       }
+
+
+
+       /**
+        * A sequence of non-paired bases in an RNA template.
+        * 
+        * @author Raphael Champeimont
+        */
+       public class RNATemplateUnpairedSequence extends RNATemplateElement {
+               /**
+                * Number of (non-paired) bases. 
+                */
+               private int length;
+               
+               private static final double defaultTangentVectorAngle  = Math.PI / 2;
+               private static final double defaultTangentVectorLength = 100;
+               
+               /**
+                * The sequence is drawn along a cubic Bezier curve.
+                * The curve can be defined by 2 vectors, one for the start of the line
+                * and the other for the end. They are the tangents to the line at
+                * the beginning and the end of the line.
+                * Each vector can be defined by its length and its absolute angle.
+                * The angles are given in radians.
+                */
+               private double inTangentVectorAngle   = defaultTangentVectorAngle,
+                              inTangentVectorLength  = defaultTangentVectorLength,
+                              outTangentVectorAngle  = defaultTangentVectorAngle,
+                              outTangentVectorLength = defaultTangentVectorLength;
+               
+               
+               
+               
+               /**
+                * Position of the begginning (at the "in" endpoint) of the line.
+                * It is only useful when the sequence is not yet connected to an helix.
+                * (Otherwise we can deduce it from this helix position).
+                */
+               private Point2D.Double vertex5;
+               
+               /**
+                * Position of the end (at the "out" endpoint) of the line.
+                * It is only useful when the sequence is not yet connected to an helix.
+                * (Otherwise we can deduce it from this helix position).
+                */
+               private Point2D.Double vertex3;
+               
+               
+               public Point2D.Double getVertex5() {
+                       return vertex5;
+               }
+
+               public void setVertex5(Point2D.Double vertex5) {
+                       this.vertex5 = vertex5;
+               }
+
+               public Point2D.Double getVertex3() {
+                       return vertex3;
+               }
+
+               public void setVertex3(Point2D.Double vertex3) {
+                       this.vertex3 = vertex3;
+               }
+
+
+               
+               
+               /**
+                * The helixes connected on both sides.
+                * They must be helixes because only helixes have absolute positions,
+                * and the positions of the starting and ending points of the sequence
+                * are those stored in the helixes.
+                */
+               private final EdgeEndPoint in, out;
+               
+               private String _name;
+               
+               public RNATemplateUnpairedSequence(String name) {
+                       in = new EdgeEndPoint();
+                       out = new EdgeEndPoint();
+                       _name = name;
+               }
+
+               
+               public String toString() {
+                       return "Sequence @" + Integer.toHexString(hashCode()) + " len=" + length;
+               }
+               
+               public String getName()
+               {return ""+_name; }
+               
+               
+               
+               public int getLength() {
+                       return length;
+               }
+
+               public void setLength(int length) {
+                       this.length = length;
+               }
+
+               public double getInTangentVectorAngle() {
+                       return inTangentVectorAngle;
+               }
+
+               public void setInTangentVectorAngle(double inTangentVectorAngle) {
+                       this.inTangentVectorAngle = inTangentVectorAngle;
+               }
+
+               public double getInTangentVectorLength() {
+                       return inTangentVectorLength;
+               }
+
+               public void setInTangentVectorLength(double inTangentVectorLength) {
+                       this.inTangentVectorLength = inTangentVectorLength;
+               }
+
+               public double getOutTangentVectorAngle() {
+                       return outTangentVectorAngle;
+               }
+
+               public void setOutTangentVectorAngle(double outTangentVectorAngle) {
+                       this.outTangentVectorAngle = outTangentVectorAngle;
+               }
+
+               public double getOutTangentVectorLength() {
+                       return outTangentVectorLength;
+               }
+
+               public void setOutTangentVectorLength(double outTangentVectorLength) {
+                       this.outTangentVectorLength = outTangentVectorLength;
+               }
+
+               public EdgeEndPoint getIn() {
+                       return in;
+               }
+
+               public EdgeEndPoint getOut() {
+                       return out;
+               }
+
+               public void disconnectFromAny() {
+                       getIn().disconnect();
+                       getOut().disconnect();
+               }
+
+
+               protected EdgeEndPoint getNextEndPoint(EdgeEndPoint endpoint) {
+                       if (endpoint == in) {
+                               return out;
+                       } else {
+                               return endpoint.getOtherEndPoint();
+                       }
+               }
+
+               protected EdgeEndPoint getPreviousEndPoint(EdgeEndPoint endpoint) {
+                       if (endpoint == out) {
+                               return in;
+                       } else {
+                               return endpoint.getOtherEndPoint();
+                       }
+               }
+               
+               public EdgeEndPoint getIn1EndPoint() {
+                       return in;
+               }
+
+
+               public EdgeEndPoint getEndPointFromPosition(
+                               EdgeEndPointPosition position) {
+                       switch (position) {
+                       case IN1:
+                               return getIn();
+                       case OUT1:
+                               return getOut();
+                       default:
+                               return null;
+                       }
+               }
+
+
+               public EdgeEndPointPosition getPositionFromEndPoint(
+                               EdgeEndPoint endPoint) {
+                       if (endPoint == in) {
+                               return EdgeEndPointPosition.IN1;
+                       } else if (endPoint == out) {
+                               return EdgeEndPointPosition.OUT1;
+                       } else {
+                               return null;
+                       }
+               }
+
+               
+       }
+
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNATemplateAlign.java b/src2/fr/orsay/lri/varna/models/templates/RNATemplateAlign.java
new file mode 100644 (file)
index 0000000..358e280
--- /dev/null
@@ -0,0 +1,418 @@
+package fr.orsay.lri.varna.models.templates;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import fr.orsay.lri.varna.exceptions.ExceptionInvalidRNATemplate;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateHelix;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateUnpairedSequence;
+import fr.orsay.lri.varna.models.treealign.AlignedNode;
+import fr.orsay.lri.varna.models.treealign.RNANodeValue;
+import fr.orsay.lri.varna.models.treealign.RNANodeValue2;
+import fr.orsay.lri.varna.models.treealign.RNATree2;
+import fr.orsay.lri.varna.models.treealign.RNATree2Exception;
+import fr.orsay.lri.varna.models.treealign.Tree;
+import fr.orsay.lri.varna.models.treealign.TreeAlign;
+import fr.orsay.lri.varna.models.treealign.TreeAlignException;
+import fr.orsay.lri.varna.models.treealign.TreeAlignResult;
+
+/**
+ * This class is about the alignment between a tree of RNANodeValue2
+ * and a tree of RNANodeValueTemplate.
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNATemplateAlign {
+       
+       // We check this node can be part of a non-broken helix.
+       private static boolean canBePartOfAnHelix(RNANodeValue2 leftNodeValue) {
+               return (leftNodeValue != null) && leftNodeValue.isSingleNode() && leftNodeValue.getNode().getRightBasePosition() > 0;
+       }
+       
+       private static boolean canBePartOfASequence(RNANodeValue2 leftNodeValue) {
+               return (leftNodeValue != null) && !leftNodeValue.isSingleNode();
+       }
+       
+       private static boolean canBePartOfABrokenHelix(RNANodeValue2 leftNodeValue) {
+               return (leftNodeValue != null) && leftNodeValue.isSingleNode() && leftNodeValue.getNode().getRightBasePosition() < 0;
+       }
+       
+       
+       /**
+        * This method takes an alignment between a tree of RNANodeValue2
+        * of RNANodeValue and a tree of RNANodeValue2 of RNANodeValueTemplate,
+        * and the original RNA object that was used to create the first tree
+        * in the alignment.
+        * It returns the corresponding RNATemplateMapping.
+        */
+       public static RNATemplateMapping makeTemplateMapping(TreeAlignResult<RNANodeValue2,RNANodeValueTemplate> alignResult, RNA rna) throws RNATemplateMappingException {
+               RNATemplateMapping mapping = new RNATemplateMapping();
+               Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>> alignment = alignResult.getAlignment();
+               mapping.setDistance(alignResult.getDistance());
+               
+               // Map sequences and helices together, without managing pseudoknots
+               {
+                       // We will go through the tree using a DFS
+                       // The reason why this algorithm is not trivial is that we may have
+                       // a longer helix on the RNA side than on the template side, in which
+                       // case some nodes on the RNA side are going to be alone while we
+                       // would want them to be part of the helix.
+                       RNATemplateHelix currentHelix = null;
+                       LinkedList<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>> remainingNodes = new LinkedList<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>>();
+                       List<RNANodeValue2> nodesInSameHelix = new LinkedList<RNANodeValue2>();
+                       remainingNodes.add(alignment);
+                       while (!remainingNodes.isEmpty()) {
+                               Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>> node = remainingNodes.getLast();
+                               remainingNodes.removeLast();
+                               
+                               Tree<RNANodeValue2> leftNode = node.getValue().getLeftNode();
+                               Tree<RNANodeValueTemplate> rightNode = node.getValue().getRightNode();
+                               
+                               // Do we have something on RNA side?
+                               if (leftNode != null && leftNode.getValue() != null) {
+                                       RNANodeValue2 leftNodeValue = leftNode.getValue();
+                                       
+                                       // Do we have something on template side?
+                                       if (rightNode != null && rightNode.getValue() != null) {
+                                               RNANodeValueTemplate rightNodeValue = rightNode.getValue();
+                                               
+                                               if (rightNodeValue instanceof RNANodeValueTemplateBasePair
+                                                               && canBePartOfAnHelix(leftNodeValue)) {
+                                                       RNATemplateHelix helix = ((RNANodeValueTemplateBasePair) rightNodeValue).getHelix();
+                                                       currentHelix = helix;
+                                                       int i = leftNodeValue.getNode().getLeftBasePosition();
+                                                       int j = leftNodeValue.getNode().getRightBasePosition();
+                                                       mapping.addCouple(i, helix);
+                                                       mapping.addCouple(j, helix);
+                                                       
+                                                       // Maybe we have marked nodes as part of the same helix
+                                                       // when we didn't know yet which helix it was.
+                                                       if (nodesInSameHelix.size() > 0) {
+                                                               for (RNANodeValue2 v: nodesInSameHelix) {
+                                                                       int k = v.getNode().getLeftBasePosition();
+                                                                       int l = v.getNode().getRightBasePosition();
+                                                                       // We want to check nodesInSameHelix is a parent helix and not a sibling.
+                                                                       boolean validExtension = (k < i) && (j < l);
+                                                                       if (validExtension) {
+                                                                               mapping.addCouple(v.getNode().getLeftBasePosition(), helix);
+                                                                               mapping.addCouple(v.getNode().getRightBasePosition(), helix);
+                                                                       }       
+                                                               }
+                                                       }
+                                                       nodesInSameHelix.clear();
+                                                       
+                                               } else if (rightNodeValue instanceof RNANodeValueTemplateSequence
+                                                               && canBePartOfASequence(leftNodeValue)) {
+                                                       currentHelix = null;
+                                                       nodesInSameHelix.clear();
+                                                       RNATemplateUnpairedSequence sequence = ((RNANodeValueTemplateSequence) rightNodeValue).getSequence();
+                                                       for (RNANodeValue nodeValue: leftNode.getValue().getNodes()) {
+                                                               mapping.addCouple(nodeValue.getLeftBasePosition(), sequence);
+                                                       }
+                                               } else {
+                                                       // Pseudoknot in template
+                                                       currentHelix = null;
+                                                       nodesInSameHelix.clear();
+                                               }
+                                               
+                                       } else {
+                                               // We have nothing on template side
+                                               
+                                               if (canBePartOfAnHelix(leftNodeValue)) {
+                                                       if (currentHelix != null) {
+                                                               // We may be in this case when the RNA
+                                                               // contains a longer helix than in the template 
+                                                               int i = leftNodeValue.getNode().getLeftBasePosition();
+                                                               int j = leftNodeValue.getNode().getRightBasePosition();
+                                                               int k = Integer.MAX_VALUE;
+                                                               int l = Integer.MIN_VALUE;
+                                                               for (int b: mapping.getAncestor(currentHelix)) {
+                                                                       k = Math.min(k, b);
+                                                                       l = Math.max(l, b);
+                                                               }
+                                                               // We want to check currentHelix is a parent helix and not a sibling.
+                                                               boolean validExtension = (k < i) && (j < l);
+                                                               if (validExtension) {
+                                                                       mapping.addCouple(i, currentHelix);
+                                                                       mapping.addCouple(j, currentHelix);
+                                                               }       
+                                                       } else {
+                                                               // Maybe this left node is part of an helix
+                                                               // which is smaller in the template
+                                                               nodesInSameHelix.add(leftNodeValue);
+                                                       }
+                                               }
+                                       }
+                               }
+                               
+                               
+                               // If this node has children, add them in the stack
+                               List<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>> children = node.getChildren();
+                               int n = children.size();
+                               if (n > 0) {
+                                       int helixChildren = 0;
+                                       // For each subtree, we want the sequences (in RNA side) to be treated first
+                                       // and then the helix nodes, because finding an aligned sequence tells
+                                       // us we cannot grow a current helix
+                                       ArrayList<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>> addToStack1 = new ArrayList<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>>();
+                                       ArrayList<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>> addToStack2 = new ArrayList<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>>();
+                                       for (int i=0; i<n; i++) {
+                                               Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>> child = children.get(i);
+                                               Tree<RNANodeValue2> RNAchild = child.getValue().getLeftNode();
+                                               if (RNAchild != null
+                                                               && RNAchild.getValue() != null
+                                                               && (canBePartOfAnHelix(RNAchild.getValue()) || canBePartOfABrokenHelix(RNAchild.getValue()) )) {
+                                                       helixChildren++;
+                                                       addToStack2.add(child);
+                                               } else {
+                                                       addToStack1.add(child);
+                                               }
+                                       }
+                                       // We add the children in their reverse order so they
+                                       // are given in the original order by the iterator
+                                       for (int i=addToStack2.size()-1; i>=0; i--) {
+                                               remainingNodes.add(addToStack2.get(i));
+                                       }
+                                       for (int i=addToStack1.size()-1; i>=0; i--) {
+                                               remainingNodes.add(addToStack1.get(i));
+                                       }
+                                       if (helixChildren >= 2) {
+                                               // We cannot "grow" the current helix, because we have a multiloop
+                                               // in the RNA.
+                                               currentHelix = null;
+                                               //nodesInSameHelix.clear();
+                                       }
+                               }
+                       }
+               }
+               
+               
+               // Now recover pseudoknots (broken helices)
+               {
+                       // First create a temporary mapping with broken helices
+                       LinkedList<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>> remainingNodes = new LinkedList<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>>();
+                       remainingNodes.add(alignment);
+                       RNATemplateMapping tempPKMapping = new RNATemplateMapping();
+                       while (!remainingNodes.isEmpty()) {
+                               Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>> node = remainingNodes.getLast();
+                               remainingNodes.removeLast();
+                               List<Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>>> children = node.getChildren();
+                               int n = children.size();
+                               if (n > 0) {
+                                       for (int i=n-1; i>=0; i--) {
+                                               // We add the children in their reverse order so they
+                                               // are given in the original order by the iterator
+                                               remainingNodes.add(children.get(i));
+                                       }
+                                       List<RNANodeValue2> nodesInSameHelix = new LinkedList<RNANodeValue2>();
+                                       RNATemplateHelix currentHelix = null;
+                                       for (Tree<AlignedNode<RNANodeValue2,RNANodeValueTemplate>> child: node.getChildren()) {
+                                               Tree<RNANodeValue2> leftNode = child.getValue().getLeftNode();
+                                               Tree<RNANodeValueTemplate> rightNode = child.getValue().getRightNode();
+                                               
+                                               if (leftNode != null && leftNode.getValue() != null) {
+                                                       RNANodeValue2 leftNodeValue = leftNode.getValue();
+                                                       // We have a real left (RNA side) node
+                                                       
+                                                       if (rightNode != null && rightNode.getValue() != null) {
+                                                               // We have a real right (template side) node
+                                                               RNANodeValueTemplate rightNodeValue = rightNode.getValue();
+                                                               
+                                                               if (rightNodeValue instanceof RNANodeValueTemplateBrokenBasePair
+                                                                               && canBePartOfABrokenHelix(leftNodeValue)) {
+                                                                       RNATemplateHelix helix = ((RNANodeValueTemplateBrokenBasePair) rightNodeValue).getHelix();
+                                                                       currentHelix = helix;
+                                                                       tempPKMapping.addCouple(leftNodeValue.getNode().getLeftBasePosition(), helix);
+                                                                       
+                                                                       // Maybe we have marked nodes as part of the same helix
+                                                                       // when we didn't know yet which helix it was.
+                                                                       for (RNANodeValue2 v: nodesInSameHelix) {
+                                                                               tempPKMapping.addCouple(v.getNode().getLeftBasePosition(), helix);
+                                                                       }
+                                                                       nodesInSameHelix.clear();
+                                                               } else {
+                                                                       currentHelix = null;
+                                                                       nodesInSameHelix.clear();
+                                                               }
+                                                       } else {
+                                                               // We have no right (template side) node
+                                                               if (canBePartOfABrokenHelix(leftNodeValue)) {
+                                                                       if (currentHelix != null) {
+                                                                               // We may be in this case if the RNA sequence
+                                                                               // contains a longer helix than in the template
+                                                                               tempPKMapping.addCouple(leftNodeValue.getNode().getLeftBasePosition(), currentHelix);
+                                                                       } else {
+                                                                               // Maybe this left node is part of an helix
+                                                                               // which is smaller in the template
+                                                                               nodesInSameHelix.add(leftNodeValue);
+                                                                       }
+                                                               } else {
+                                                                       currentHelix = null;
+                                                                       nodesInSameHelix.clear();
+                                                               }
+                                                       }
+                                               } else {
+                                                       currentHelix = null;
+                                                       nodesInSameHelix.clear();
+                                               }
+                                       }
+                               }
+                       }
+                       
+                       
+                       // As parts of broken helices were aligned independently,
+                       // we need to check for consistency, ie. keep only bases for
+                       // which the associated base is also aligned with the same helix.
+                       for (RNATemplateElement element: tempPKMapping.getTargetElemsAsSet()) {
+                               RNATemplateHelix helix = (RNATemplateHelix) element;
+                               HashSet<Integer> basesInHelix = new HashSet<Integer>(tempPKMapping.getAncestor(helix));
+                               for (int baseIndex: basesInHelix) {
+                                       System.out.println("PK: " + helix + " aligned with " + baseIndex);
+                                       boolean baseOK = false;
+                                       // Search for an associated base aligned with the same helix
+                                       ArrayList<ModeleBP> auxBasePairs = rna.getAuxBPs(baseIndex);
+                                       for (ModeleBP auxBasePair: auxBasePairs) {
+                                               int partner5 = ((ModeleBaseNucleotide) auxBasePair.getPartner5()).getIndex();
+                                               int partner3 = ((ModeleBaseNucleotide) auxBasePair.getPartner3()).getIndex();
+                                               if (baseIndex == partner5) {
+                                                       if (basesInHelix.contains(partner3)) {
+                                                               baseOK = true;
+                                                               break;
+                                                       }
+                                               } else if (baseIndex == partner3) {
+                                                       if (basesInHelix.contains(partner5)) {
+                                                               baseOK = true;
+                                                               break;
+                                                       }
+                                               }
+                                       }
+                                       if (baseOK) {
+                                               // Add it to the real mapping
+                                               mapping.addCouple(baseIndex, helix);
+                                       }
+                               }
+                       }
+               }
+               
+               
+               return mapping;
+       }
+       
+       
+       
+       public static void printMapping(RNATemplateMapping mapping, RNATemplate template, String sequence) {
+               Iterator<RNATemplateElement> iter = template.rnaIterator();
+               while (iter.hasNext()) {
+                       RNATemplateElement element = iter.next();
+                       System.out.println(element.toString());
+                       ArrayList<Integer> A = mapping.getAncestor(element);
+                       if (A != null) {
+                               RNATemplateAlign.printIntArrayList(A);
+                               for (int n=A.size(), i=0; i<n; i++) {
+                                       System.out.print("\t" + sequence.charAt(A.get(i)));
+                               }
+                               System.out.println("");
+                       } else {
+                               System.out.println("\tno match");
+                       }
+               }
+       }
+       
+       
+       /**
+        * Align the given RNA with the given RNA template.
+        */
+       public static TreeAlignResult<RNANodeValue2,RNANodeValueTemplate> alignRNAWithTemplate(RNA rna, RNATemplate template) throws RNATemplateDrawingAlgorithmException {
+               try {
+                       Tree<RNANodeValue2> rnaAsTree = RNATree2.RNATree2FromRNA(rna);
+                       Tree<RNANodeValueTemplate> templateAsTree = template.toTree();
+                       TreeAlign<RNANodeValue2,RNANodeValueTemplate> treeAlign = new TreeAlign<RNANodeValue2,RNANodeValueTemplate>(new RNANodeValue2TemplateDistance());
+                       TreeAlignResult<RNANodeValue2,RNANodeValueTemplate> result = treeAlign.align(rnaAsTree, templateAsTree);
+                       return result;
+               } catch (RNATree2Exception e) {
+                       throw (new RNATemplateDrawingAlgorithmException("RNATree2Exception: " + e.getMessage()));
+               } catch (ExceptionInvalidRNATemplate e) {
+                       throw (new RNATemplateDrawingAlgorithmException("ExceptionInvalidRNATemplate: " + e.getMessage()));
+               } catch (TreeAlignException e) {
+                       throw (new RNATemplateDrawingAlgorithmException("TreeAlignException: " + e.getMessage()));
+               }
+       }
+       
+       /**
+        * Map an RNA with an RNATemplate using tree alignment.
+        */
+       public static RNATemplateMapping mapRNAWithTemplate(RNA rna, RNATemplate template) throws RNATemplateDrawingAlgorithmException {
+               try {
+                       TreeAlignResult<RNANodeValue2,RNANodeValueTemplate> alignResult = RNATemplateAlign.alignRNAWithTemplate(rna, template); 
+                       RNATemplateMapping mapping = RNATemplateAlign.makeTemplateMapping(alignResult, rna);
+                       return mapping;
+               } catch (RNATemplateMappingException e) {
+                       e.printStackTrace();
+                       throw (new RNATemplateDrawingAlgorithmException("RNATemplateMappingException: " + e.getMessage()));
+               }
+       }
+       
+       
+
+       /**
+        * Print an integer array.
+        */
+       public static void printIntArray(int[] A) {
+               for (int i=0; i<A.length; i++) {
+                       System.out.print("\t" + A[i]);
+               }
+               System.out.println("");
+       }
+
+       /**
+        * Print an integer ArrayList.
+        */
+       public static void printIntArrayList(ArrayList<Integer> A) {
+               for (int i=0; i<A.size(); i++) {
+                       System.out.print("\t" + A.get(i));
+               }
+               System.out.println("");
+       }
+
+       /**
+        * Print an matrix of shorts.
+        */
+       public static void printShortMatrix(short[][] M) {
+               System.out.println("Begin matrix");
+               for (int i=0; i<M.length; i++) {
+                       for (int j=0; j<M[i].length; j++) {
+                               System.out.print("\t" + M[i][j]);
+                       }
+                       System.out.println("");
+               }
+               System.out.println("End matrix");
+       }
+       
+       /**
+        * Convert a list of integers into an array of integers.
+        * The returned arrays is freshly allocated.
+        * Returns null if given null.
+        */
+       public static int[] intArrayFromList(List<Integer> l) {
+               if (l != null) {
+                       int n = l.size();
+                       int[] result = new int[n];
+                       for (int i=0; i<n; i++) {
+                               result[i] = l.get(i);
+                       }
+                       return result;
+               } else {
+                       return null;
+               }
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNATemplateDrawingAlgorithmException.java b/src2/fr/orsay/lri/varna/models/templates/RNATemplateDrawingAlgorithmException.java
new file mode 100644 (file)
index 0000000..818ef0f
--- /dev/null
@@ -0,0 +1,18 @@
+package fr.orsay.lri.varna.models.templates;
+
+import fr.orsay.lri.varna.exceptions.ExceptionDrawingAlgorithm;
+
+/**
+ * Exception thrown in case of failure of the template-based
+ * RNA drawing algorithm.
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNATemplateDrawingAlgorithmException extends ExceptionDrawingAlgorithm {
+
+       private static final long serialVersionUID = 1701307036024533400L;
+
+       public RNATemplateDrawingAlgorithmException(String message) {
+               super(message);
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNATemplateMapping.java b/src2/fr/orsay/lri/varna/models/templates/RNATemplateMapping.java
new file mode 100644 (file)
index 0000000..39d76d0
--- /dev/null
@@ -0,0 +1,158 @@
+package fr.orsay.lri.varna.models.templates;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import fr.orsay.lri.varna.applications.templateEditor.Couple;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateElement;
+import fr.orsay.lri.varna.models.templates.RNATemplate.RNATemplateHelix;
+
+/**
+ * A RNATemplateMapping is a mapping between bases in an RNA sequence
+ * and elements in a RNA template.
+ * A base is mapped to only one template element
+ * but a template element can be mapped to several bases.
+ * This class is designed to be similar to the Mapping class.
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNATemplateMapping {
+       private Map<Integer, RNATemplateElement> map = new HashMap<Integer, RNATemplateElement>();
+       private Map<RNATemplateElement, ArrayList<Integer>> invmap = new HashMap<RNATemplateElement, ArrayList<Integer>>();
+       
+       /**
+        * Alignment distance.
+        */
+       private double distance;
+       
+       
+       public double getDistance() {
+               return distance;
+       }
+       
+       public void setDistance(double distance) {
+               this.distance = distance;
+       }
+       
+       /**
+        * Tell this mapping object that this base index and this element are
+        * mapped with each other. This will throw RNATemplateMappingException
+        * and do nothing if the base index is already in the mapping.
+        */
+       public void addCouple(int baseIndex, RNATemplateElement templateElement) throws RNATemplateMappingException {
+               if (map.containsKey(baseIndex)) {
+                       throw (new RNATemplateMappingException("Base index already in mapping: " + baseIndex));
+               }
+               if (baseIndex < 0) {
+                       throw (new RNATemplateMappingException("Invalid base index: " + baseIndex));
+               }
+               map.put(baseIndex, templateElement);
+               if (!invmap.containsKey(templateElement)) {
+                       invmap.put(templateElement, new ArrayList<Integer>());
+               }
+               invmap.get(templateElement).add(baseIndex);
+       }
+
+
+       public String showCompact(RNA r)
+       {
+               HashMap<String,Couple<Integer,Integer> > ranges = new HashMap<String,Couple<Integer,Integer> >();
+               for(int i:map.keySet())
+               {
+                       RNATemplateElement t = map.get(i);
+                       String k = t.getName();
+                       if (t instanceof RNATemplate.RNATemplateHelix)
+                       {
+                               k += " (" + ((RNATemplateHelix) t).getCaption() + ")";
+                               ModeleBase mb = r.getBaseAt(i);
+                               if (mb.getElementStructure()>i)
+                                 k = k+":5'";
+                               else
+                                 k = k+":3'";
+                       }
+                       if (!ranges.containsKey(k))
+                       {  ranges.put(k, new Couple<Integer,Integer>(Integer.MAX_VALUE,Integer.MIN_VALUE));  }
+                       Couple<Integer,Integer> c = ranges.get(k);
+                       c.first = Math.min(c.first, i);
+                       c.second = Math.max(c.second, i);                       
+               }
+               String result = "";
+               for(String k:ranges.keySet())
+               {
+                       Couple<Integer,Integer> c = ranges.get(k);
+                       RNATemplateElement t = map.get(c.first);
+                       String type = ((t instanceof RNATemplate.RNATemplateHelix)?"strand":"loop");
+                       if (t instanceof RNATemplate.RNATemplateHelix)
+                       {
+                               if (k.endsWith("5'"))
+                               {
+                                       Couple<Integer,Integer> c3 = ranges.get(k.replace("5'", "3'"));
+                                       result += "dummyID\t1\t"+k.replace(":5'", "")+"\t"+type+"\t"+c.first+"-"+c.second+":"+c3.first+"-"+c3.second+"\n";
+                               }
+                       }
+                       else if (t instanceof RNATemplate.RNATemplateUnpairedSequence)
+                       {
+                         result += "dummyID\t1\t"+k+"\t"+type+"\t"+c.first+"-"+c.second+"\n";
+                       }
+               }
+               result += "alignment distance = " + distance;
+               return result;
+       }
+       
+       
+       /**
+        * If the given base index is in the mapping, return the
+        * corresponding template element, otherwise return null.
+        */
+       public RNATemplateElement getPartner(int baseIndex) {
+               if (map.containsKey(baseIndex)) {
+                       return map.get(baseIndex);
+               } else {
+                       return null;
+               }
+       }
+       
+       
+       
+       /**
+        * If the given template element is in the mapping, return an ArrayList
+        * containing the corresponding base indexes, otherwise return null.
+        * Note that you should not modify the returned ArrayList because
+        * no copy is made, so if you modify it this mapping object will
+        * contain inconsistent data.
+        */
+       public ArrayList<Integer> getAncestor(RNATemplateElement templateElement) {
+               if (invmap.containsKey(templateElement)) {
+                       return invmap.get(templateElement);
+               } else {
+                       return null;
+               }
+       }
+       
+       
+       
+       /**
+        * Return a set containing all the base indexes in the mapping.
+        * You should not modify the returned set.
+        */
+       public Set<Integer> getSourceElemsAsSet() {
+               return map.keySet();
+       }
+       
+       
+       
+       /**
+        * Return a set containing all the template elements in the mapping.
+        * You should not modify the return set.
+        */
+       public Set<RNATemplateElement> getTargetElemsAsSet() {
+               return invmap.keySet();
+       }
+       
+       
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/RNATemplateMappingException.java b/src2/fr/orsay/lri/varna/models/templates/RNATemplateMappingException.java
new file mode 100644 (file)
index 0000000..3b689f1
--- /dev/null
@@ -0,0 +1,19 @@
+package fr.orsay.lri.varna.models.templates;
+
+/**
+ * This exception is thrown when we discover that a template is invalid
+ * (it contains impossible connections between elements).
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNATemplateMappingException extends Exception {
+       
+       private static final long serialVersionUID = -201638492590138354L;
+
+       public RNATemplateMappingException(String message) {
+               super(message);
+       }
+       
+       public RNATemplateMappingException() {
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/templates/TODO.txt b/src2/fr/orsay/lri/varna/models/templates/TODO.txt
new file mode 100644 (file)
index 0000000..1057527
--- /dev/null
@@ -0,0 +1,7 @@
+TODO for the template-based RNA drawing algorithm:
+- Calculer le tableau centers[] entièrement dans l'algo de tracé.
+- RNATemplateAlign.multiPassMap() is currently just an alias
+  for singlePassMap(), but it should me multi-pass.
+- Decalage des helices en absence de PK
+- Ellipses pour non-appariees
+- couts affine
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/models/treealign/AlignedNode.java b/src2/fr/orsay/lri/varna/models/treealign/AlignedNode.java
new file mode 100644 (file)
index 0000000..9f42890
--- /dev/null
@@ -0,0 +1,48 @@
+package fr.orsay.lri.varna.models.treealign;
+
+
+/**
+ * The type of node values in an alignment.
+ * Contains a reference to both original nodes.
+ * This class implements GraphvizDrawableNodeValue but it will only work
+ * if the original nodes implement it.
+ * @author Raphael Champeimont
+ * @param <OriginalNodeValueType1> The type of values in the original first tree.
+ * @param <OriginalNodeValueType2> The type of values in the original second tree.
+ */
+public class AlignedNode<OriginalNodeValueType1, OriginalNodeValueType2> implements GraphvizDrawableNodeValue {
+       private Tree<OriginalNodeValueType1> leftNode;
+       private Tree<OriginalNodeValueType2> rightNode;
+
+       public Tree<OriginalNodeValueType1> getLeftNode() {
+               return leftNode;
+       }
+
+       public void setLeftNode(Tree<OriginalNodeValueType1> leftNode) {
+               this.leftNode = leftNode;
+       }
+
+       public Tree<OriginalNodeValueType2> getRightNode() {
+               return rightNode;
+       }
+
+       public void setRightNode(Tree<OriginalNodeValueType2> rightNode) {
+               this.rightNode = rightNode;
+       }
+       
+       private String maybeNodeToGraphvizNodeName(Tree <? extends GraphvizDrawableNodeValue> tree) {
+               return (tree != null && tree.getValue() != null) ? tree.getValue().toGraphvizNodeName() : "_";
+       }
+
+       /**
+        * This method will work only if the left and right node
+        * already implement GraphvizDrawableNodeValue.
+        */
+       @SuppressWarnings("unchecked")
+       public String toGraphvizNodeName() {
+               return "(" + maybeNodeToGraphvizNodeName((Tree) leftNode)
+               + "," + maybeNodeToGraphvizNodeName((Tree) rightNode) + ")";
+       }
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/ExampleDistance2.java b/src2/fr/orsay/lri/varna/models/treealign/ExampleDistance2.java
new file mode 100644 (file)
index 0000000..f58bcbb
--- /dev/null
@@ -0,0 +1,39 @@
+package fr.orsay.lri.varna.models.treealign;
+
+
+/**
+ * This distance is such that a substitution costs nothing.
+ * 
+ * @author Raphael Champeimont
+ *
+ */
+public class ExampleDistance2 implements TreeAlignLabelDistanceSymmetric<RNANodeValue2> {
+       public double f(RNANodeValue2 v1, RNANodeValue2 v2) {
+               if (v1 == null) {
+                       if (v2 == null) {
+                               return 0;
+                       } else if (!v2.isSingleNode()) { // v2 is a list of bases
+                               return v2.getNodes().size();
+                       } else { // v2 is a single node
+                               return 2;
+                       }
+               } else if (!v1.isSingleNode()) { // v1 is a list of bases
+                       if (v2 == null) {
+                               return v1.getNodes().size();
+                       } else if (!v2.isSingleNode()) { // v2 is a list of bases
+                               return Math.abs(v2.getNodes().size() - v1.getNodes().size());
+                       } else { // v2 is a single node
+                               return 2 + v1.getNodes().size();
+                       }
+               } else { // v1 is a single node
+                       // all the same as when v1 == null
+                       if (v2 == null) {
+                               return 2;
+                       } else if (!v2.isSingleNode()) { // v2 is a list of bases
+                               return 2 + v2.getNodes().size();
+                       } else { // v2 is a single node
+                               return 0;
+                       }
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/ExampleDistance3.java b/src2/fr/orsay/lri/varna/models/treealign/ExampleDistance3.java
new file mode 100644 (file)
index 0000000..cba2a8a
--- /dev/null
@@ -0,0 +1,194 @@
+package fr.orsay.lri.varna.models.treealign;
+import java.util.ArrayList;
+
+
+
+/**
+ * 
+ * 
+ * @author Raphael Champeimont
+ */
+public class ExampleDistance3 implements TreeAlignLabelDistanceSymmetric<RNANodeValue2> {
+       public double f(RNANodeValue2 v1, RNANodeValue2 v2) {
+               if (v1 == null) {
+                       if (v2 == null) {
+                               return 0;
+                       } else if (!v2.isSingleNode()) { // v2 is a list of bases
+                               // We insert all bases, with a cost of 1 for each base.
+                               return v2.getNodes().size();
+                       } else { // v2 is a single node
+                               return 2;
+                       }
+               } else if (!v1.isSingleNode()) { // v1 is a list of bases
+                       if (v2 == null) {
+                               return v1.getNodes().size();
+                       } else if (!v2.isSingleNode()) { // v2 is a list of bases
+                               // We compute the sequence distance
+                               return alignSequenceNodes(v1, v2).getDistance();
+                       } else { // v2 is a single node
+                               return 2 + v1.getNodes().size();
+                       }
+               } else { // v1 is a single node
+                       // all the same as when v1 == null
+                       if (v2 == null) {
+                               return 2;
+                       } else if (!v2.isSingleNode()) { // v2 is a list of bases
+                               return 2 + v2.getNodes().size();
+                       } else { // v2 is a single node
+                               String l1 = v1.getNode().getLeftNucleotide();
+                               String r1 = v1.getNode().getRightNucleotide();
+                               String l2 = v2.getNode().getLeftNucleotide();
+                               String r2 = v2.getNode().getRightNucleotide();
+                               // We have cost(subst((x,y) to (x',y'))) = 1
+                               // when x != x' and y != y'.
+                               // It means it is less than substituting 2 non-paired bases 
+                               return (!l1.equals(l2) ? 0.5 : 0)
+                                    + (!r1.equals(r2) ? 0.5 : 0);
+                       }
+               }
+       }
+       
+
+       public class SequenceAlignResult {
+               private double distance;
+               private int[][] alignment;
+               
+               public double getDistance() {
+                       return distance;
+               }
+               public void setDistance(double distance) {
+                       this.distance = distance;
+               }
+               
+               /** The result array is a matrix of height 2
+                * and width at most length(sequence A) + length(sequence B).
+                * with result[0] is the alignment for A
+                * and result[1] the alignment for B.
+                * The alignment consists int the indexes of the original
+                * bases positions, with -1 when there is no match.
+                */
+               public int[][] getAlignment() {
+                       return alignment;
+               }
+               public void setAlignment(int[][] alignment) {
+                       this.alignment = alignment;
+               }
+               
+       }
+       
+       /**
+        * Align two sequences contained in nodes.
+        * Both nodes have to be non-single nodes, otherwise an
+        * RNANodeValue2WrongTypeException exception will be thrown.
+        */
+       public SequenceAlignResult alignSequenceNodes(RNANodeValue2 v1, RNANodeValue2 v2) {
+               char[] A = v1.computeSequence();
+               char[] B = v2.computeSequence();
+               return alignSequences(A, B);
+       }
+       
+       /**
+        * Align sequences using the Needleman-Wunsch algorithm.
+        * Time: O(A.length * B.length)
+        * Space: O(A.length * B.length)
+        * Space used by the returned object: O(A.length + B.length)
+        */
+       public SequenceAlignResult alignSequences(char[] A, char[] B) {
+               SequenceAlignResult result = new SequenceAlignResult();
+               
+               final int la = A.length;
+               final int lb = B.length;
+               double[][] F = new double[la+1][lb+1];
+               int[][] decisions = new int[la+1][lb+1];
+               final double d = 1; // insertion/deletion cost
+               final double substCost = 1; // substitution cost
+               for (int i=0; i<=la; i++)
+                       F[i][0] = d*i;
+               for (int j=0; j<=lb; j++)
+                       F[0][j] = d*j;
+               for (int i=1; i<=la; i++)
+                       for (int j=1; j<=lb; j++)
+                       {
+                               double min;
+                               int decision;
+                               double match = F[i-1][j-1] + (A[i-1] == B[j-1] ? 0 : substCost);
+                               double delete = F[i-1][j] + d;
+                               if (match < delete) {
+                                       decision = 1;
+                                       min = match;
+                               } else {
+                                       decision = 2;
+                                       min = delete;
+                               }
+                               double insert = F[i][j-1] + d;
+                               if (insert < min) {
+                                       decision = 3;
+                                       min = insert;
+                               }
+                               F[i][j] = min;
+                               decisions[i][j] = decision;
+                       }
+               
+               result.setDistance(F[la][lb]);
+
+               int[][] alignment = computeAlignment(F, decisions, A, B);
+               result.setAlignment(alignment);
+               
+               return result;
+       }
+       
+       private int[][] computeAlignment(double[][] F, int[][] decisions, char[] A, char[] B) {
+               // At worst the alignment will be of length (A.length + B.length)
+               ArrayList<Integer> AlignmentA = new ArrayList<Integer>(A.length + B.length);
+               ArrayList<Integer> AlignmentB = new ArrayList<Integer>(A.length + B.length);
+               int i = A.length;
+               int j = B.length;
+               while (i > 0 && j > 0)
+               {
+                       int decision = decisions[i][j];
+                       switch (decision) {
+                       case 1:
+                               AlignmentA.add(i-1);
+                               AlignmentB.add(j-1);
+                               i = i - 1;
+                               j = j - 1;
+                               break;
+                       case 2:
+                               AlignmentA.add(i-1);
+                               AlignmentB.add(-1);
+                               i = i - 1;
+                               break;
+                       case 3:
+                               AlignmentA.add(-1);
+                               AlignmentB.add(j-1);
+                               j = j - 1;
+                               break;
+                       default:
+                               throw (new Error("Bug in ExampleDistance3: decision = " + decision));
+                       }
+               }
+               while (i > 0)
+               {
+                       AlignmentA.add(i-1);
+                       AlignmentB.add(-1);
+                       i = i - 1;
+               }
+               while (j > 0)
+               {
+                       AlignmentA.add(-1);
+                       AlignmentB.add(j-1);
+                       j = j - 1;
+               }
+
+               // Convert the ArrayLists to the right format:
+               // We need to reverse the list and change the numbering of
+               int l = AlignmentA.size();
+               int[][] result = new int[2][l];
+               for (i=0; i<l; i++) {
+                       result[0][i] = AlignmentA.get(l-1-i);
+                       result[1][i] = AlignmentB.get(l-1-i);
+               }
+               return result;
+               
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/GraphvizDrawableNodeValue.java b/src2/fr/orsay/lri/varna/models/treealign/GraphvizDrawableNodeValue.java
new file mode 100644 (file)
index 0000000..46c50ec
--- /dev/null
@@ -0,0 +1,14 @@
+package fr.orsay.lri.varna.models.treealign;
+
+/**
+ * A tree can be displayed using graphviz (using class TreeGraphviz)
+ * if the node values in the tree implement this interface.
+ * 
+ * @author Raphael Champeimont
+ */
+public interface GraphvizDrawableNodeValue {
+       /**
+        * Returns a string that will be displayed on the node by graphviz.
+        */
+       public String toGraphvizNodeName();
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/RNANodeValue.java b/src2/fr/orsay/lri/varna/models/treealign/RNANodeValue.java
new file mode 100644 (file)
index 0000000..3b26b47
--- /dev/null
@@ -0,0 +1,102 @@
+package fr.orsay.lri.varna.models.treealign;
+
+/**
+ * We use the following convention: If the node is marked by a couple (n,m)
+ * these integers are stored in leftBasePosition and rightBasePosition
+ * (ie. we have a pair of bases), if only
+ * one value is present, it is stored in leftBasePosition and rightBasePosition
+ * contains -1 (ie. we have a non-paired base).
+ * The right and left nucleotides follow the same rule, but are optional,
+ * and '_' is used as undefined instead of -1.
+ * Note that it is part of the contract of this class that default
+ * values are -1 and _.
+ * 
+ * @author Raphael Champeimont
+ */
+public class RNANodeValue implements GraphvizDrawableNodeValue {
+       private int leftBasePosition = -1;
+       private int rightBasePosition = -1;
+       
+       private String leftNucleotide = "_";
+       private String rightNucleotide = "_";
+       
+       public enum Origin {
+               BASE_PAIR_FROM_HELIX,
+               BASE_FROM_HELIX_STRAND5,
+               BASE_FROM_HELIX_STRAND3,
+               BASE_FROM_UNPAIRED_REGION;
+       }
+       
+       /**
+        * Used to store the origin of this base / base pair.
+        */
+       private Origin origin = null;
+       
+       public Origin getOrigin() {
+               return origin;
+       }
+       public void setOrigin(Origin comesFromAnHelix) {
+               this.origin = comesFromAnHelix;
+       }
+       
+       
+       
+       public String getLeftNucleotide() {
+               return leftNucleotide;
+       }
+       public void setLeftNucleotide(String leftNucleotide) {
+               this.leftNucleotide = leftNucleotide;
+       }
+       public String getRightNucleotide() {
+               return rightNucleotide;
+       }
+       public void setRightNucleotide(String rightNucleotide) {
+               this.rightNucleotide = rightNucleotide;
+       }
+       public int getLeftBasePosition() {
+               return leftBasePosition;
+       }
+       public void setLeftBasePosition(int leftBasePosition) {
+               this.leftBasePosition = leftBasePosition;
+       }
+       public int getRightBasePosition() {
+               return rightBasePosition;
+       }
+       public void setRightBasePosition(int rightBasePosition) {
+               this.rightBasePosition = rightBasePosition;
+       }
+       
+       public String toGraphvizNodeName() {
+               if (rightNucleotide.equals("_")) {
+                       if (leftNucleotide.equals("_")) {
+                               if (rightBasePosition == -1) {
+                                       if (leftBasePosition == -1) {
+                                               return super.toString();
+                                       } else {
+                                               return Integer.toString(leftBasePosition);
+                                       }
+                               } else {
+                                       return "(" + leftBasePosition + "," + rightBasePosition + ")";
+                               }
+                       } else {
+                               return leftNucleotide;
+                       }
+               } else {
+                       return "(" + leftNucleotide + "," + rightNucleotide + ")";
+               }
+       }
+       
+       public String toString() {
+               if (rightBasePosition == -1) {
+                       if (leftBasePosition == -1) {
+                               return super.toString();
+                       } else {
+                               return Integer.toString(leftBasePosition);
+                       }
+               } else {
+                       return "(" + leftBasePosition + "," + rightBasePosition + ")";
+               }
+       }
+       
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/RNANodeValue2.java b/src2/fr/orsay/lri/varna/models/treealign/RNANodeValue2.java
new file mode 100644 (file)
index 0000000..6fff9a9
--- /dev/null
@@ -0,0 +1,136 @@
+package fr.orsay.lri.varna.models.treealign;
+import java.util.ArrayList;
+import java.util.List;
+
+
+
+/**
+ * In this model, nodes are either:
+ * 1. a couple of paired bases, and in that case they may have children,
+ *    in this case singleNode is true 
+ * 2. a single base that comes from a broken base pair
+ *    (broken during planarization), without children,
+ *    in this case singleNode is true
+ * 3. a list of consecutive non-paired bases, without children.
+ *    in this case singleNode is false
+ * Note that case 2 happens only if original sequences contained
+ * pseudoknots, otherwise this case can be ignored.
+ * 
+ * @author Raphael Champeimont
+ *
+ */
+public class RNANodeValue2 implements GraphvizDrawableNodeValue {
+       /**
+        * Says whether we have a single node or a list of nodes.
+        */
+       private boolean singleNode = true;
+       
+       /**
+        * Defined if singleNode is true. 
+        */
+       private RNANodeValue node;
+       
+       /**
+        * Defined if singleNode is false; 
+        */
+       private List<RNANodeValue> nodes;
+       
+       public RNANodeValue2(boolean singleNode) {
+               this.singleNode = singleNode;
+               if (singleNode) {
+                       node = new RNANodeValue();
+               } else {
+                       nodes = new ArrayList<RNANodeValue>();
+               }
+       }
+
+       /**
+        * In case of a single node, return it.
+        * Will throw RNANodeValue2WrongTypeException if singleNode = false.
+        */
+       public RNANodeValue getNode() {
+               if (singleNode) {
+                       return node;
+               } else {
+                       throw (new RNANodeValue2WrongTypeException());
+               }
+       }
+       
+       public void setNode(RNANodeValue node) {
+               if (singleNode) {
+                       this.node = node;
+               } else {
+                       throw (new RNANodeValue2WrongTypeException());
+               }
+       }
+
+       /**
+        * In case of multiple nodes, return them.
+        * Will throw RNANodeValue2WrongTypeException if singleNode = true.
+        */
+       public List<RNANodeValue> getNodes() {
+               if (!singleNode) {
+                       return nodes;
+               } else {
+                       throw (new RNANodeValue2WrongTypeException());
+               }
+       }
+       /**
+        * In case of multiple nodes, return the sequence of nucleotides.
+        */
+       public char[] computeSequence() {
+               if (!singleNode) {
+                       final int n = nodes.size();
+                       char[] sequence = new char[n];
+                       for (int i=0; i<n; i++) {
+                               sequence[i] = nodes.get(i).getLeftNucleotide().charAt(0);
+                       }
+                       return sequence;
+               } else {
+                       throw (new RNANodeValue2WrongTypeException());
+               }
+       }
+       
+       public void setNodes(List<RNANodeValue> nodes) {
+               if (!singleNode) {
+                       this.nodes = nodes;
+               } else {
+                       throw (new RNANodeValue2WrongTypeException());
+               }
+       }
+
+       public boolean isSingleNode() {
+               return singleNode;
+       }
+       
+       public String toString() {
+               if (singleNode) {
+                       return node.toString();
+               } else {
+                       String s = "";
+                       for (RNANodeValue node: nodes) {
+                               if (s != "") {
+                                       s += " ";
+                               }
+                               s += node.toString();
+                       }
+                       return s;
+               }
+       }
+       
+       public String toGraphvizNodeName() {
+               if (singleNode) {
+                       return node.toGraphvizNodeName();
+               } else {
+                       String s = "";
+                       for (RNANodeValue node: nodes) {
+                               if (s != "") {
+                                       s += " ";
+                               }
+                               s += node.toGraphvizNodeName();
+                       }
+                       return s;
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/RNANodeValue2WrongTypeException.java b/src2/fr/orsay/lri/varna/models/treealign/RNANodeValue2WrongTypeException.java
new file mode 100644 (file)
index 0000000..8dd2505
--- /dev/null
@@ -0,0 +1,11 @@
+package fr.orsay.lri.varna.models.treealign;
+
+/**
+ * @author Raphael Champeimont
+ *
+ */
+public class RNANodeValue2WrongTypeException extends NullPointerException {
+
+       private static final long serialVersionUID = -2709057098523675088L;
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/RNATree.java b/src2/fr/orsay/lri/varna/models/treealign/RNATree.java
new file mode 100644 (file)
index 0000000..8a72fbf
--- /dev/null
@@ -0,0 +1,158 @@
+package fr.orsay.lri.varna.models.treealign;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import fr.orsay.lri.varna.exceptions.MappingException;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+
+/**
+ * This class contains all functions that are specific to trees
+ * (class Tree) of RNA.
+ * 
+ * @author Raphael Champeimont
+ *
+ */
+public class RNATree { 
+       /**
+        * Convert an RNA object into a RNA tree.
+        * The root node will have a null value because it is a fake
+        * node added to have a tree (otherwise we would have a forest).
+        */
+       public static Tree<RNANodeValue> RNATreeFromRNA(RNA rna) {
+               ConvertToTree converter = new ConvertToTree(rna);
+               return converter.toTreeAux(0);
+       }
+       
+       private static class ConvertToTree {
+               private RNA rna;
+               
+               private int i = 0;
+               
+               /** Starts at the current position i in the sequence and converts the sequence
+                *  to a tree.
+                * @return the created tree
+                */
+               public Tree<RNANodeValue> toTreeAux(int depth) {
+                       Tree<RNANodeValue> tree = new Tree<RNANodeValue>();
+                       List<Tree<RNANodeValue>> children = tree.getChildren();
+                       // No value because it is a fake root
+                       tree.setValue(null);
+                       
+                       int length = rna.getSize();
+                       while (i < length) {
+                               ModeleBase base = rna.getBaseAt(i);
+                               int indexOfAssociatedBase = base.getElementStructure();
+                               if (indexOfAssociatedBase >= 0) {
+                                       if (indexOfAssociatedBase > i) {
+                                               // left parenthesis, we must analyze the children
+                                               RNANodeValue childValue = new RNANodeValue();
+                                               childValue.setLeftBasePosition(i);
+                                               childValue.setRightBasePosition(indexOfAssociatedBase);
+                                               childValue.setOrigin(RNANodeValue.Origin.BASE_PAIR_FROM_HELIX);
+                                               
+                                               if (base instanceof ModeleBaseNucleotide) {
+                                                       childValue.setLeftNucleotide(((ModeleBaseNucleotide) base).getBase());
+                                                       childValue.setRightNucleotide(((ModeleBaseNucleotide) rna.getBaseAt(indexOfAssociatedBase)).getBase());
+                                               }
+                                               i++;
+                                               Tree<RNANodeValue> child = toTreeAux(depth+1);
+                                               child.setValue(childValue);
+                                               children.add(child);
+                                       } else {
+                                               // right parenthesis, we have finished analyzing the children
+                                               i++;
+                                               break;
+                                       }
+                               } else {
+                                       // we have a non-paired base
+                                       Tree<RNANodeValue> child = new Tree<RNANodeValue>();
+                                       RNANodeValue childValue = new RNANodeValue();
+                                       childValue.setLeftBasePosition(i);
+                                       if (base instanceof ModeleBaseNucleotide) {
+                                               childValue.setLeftNucleotide(((ModeleBaseNucleotide) base).getBase());
+                                       }
+                                       
+                                       // Even in this case (getElementStructure() < 0)
+                                       // this base may still come from an helix which may have
+                                       // been broken to remove a pseudoknot.
+                                       childValue.setOrigin(RNANodeValue.Origin.BASE_FROM_UNPAIRED_REGION);
+                                       ArrayList<ModeleBP> auxBasePairs = rna.getAuxBPs(i);
+                                       for (ModeleBP auxBasePair: auxBasePairs) {
+                                               if (auxBasePair.isCanonical()) {
+                                                       int partner5 = ((ModeleBaseNucleotide) auxBasePair.getPartner5()).getIndex();
+                                                       int partner3 = ((ModeleBaseNucleotide) auxBasePair.getPartner3()).getIndex();
+                                                       if (i == partner5) {
+                                                               childValue.setOrigin(RNANodeValue.Origin.BASE_FROM_HELIX_STRAND5);
+                                                       } else if (i == partner3) {
+                                                               childValue.setOrigin(RNANodeValue.Origin.BASE_FROM_HELIX_STRAND3);
+                                                       } else {
+                                                               System.err.println("Warning: Base index is " + i + " but neither endpoint matches it (edge endpoints are " + partner5 + " and " + partner3 + ").");
+                                                       }
+                                                       
+                                               }
+                                       }
+                                       
+                                       child.setValue(childValue);
+                                       children.add(child);
+                                       i++;
+                               }
+                       }
+                       
+                       return tree;
+               }
+               
+               public ConvertToTree(RNA rna) {
+                       this.rna = rna;
+               }
+       }
+       
+
+       /**
+        * Convert an RNA tree alignment into a Mapping.
+        */
+       public static Mapping mappingFromAlignment(Tree<AlignedNode<RNANodeValue,RNANodeValue>> alignment) throws MappingException {
+               ConvertToMapping converter = new ConvertToMapping();
+               return converter.convert(alignment);
+       }
+       
+       private static class ConvertToMapping {
+               private Mapping m;
+               
+               public Mapping convert(Tree<AlignedNode<RNANodeValue,RNANodeValue>> tree) throws MappingException {
+                       m = new Mapping();
+                       convertSubTree(tree);
+                       return m;
+               }
+               
+               private void convertSubTree(Tree<AlignedNode<RNANodeValue,RNANodeValue>> tree) throws MappingException {
+                       AlignedNode<RNANodeValue,RNANodeValue> alignedNode = tree.getValue();
+                       Tree<RNANodeValue> leftNode  = alignedNode.getLeftNode();
+                       Tree<RNANodeValue> rightNode = alignedNode.getRightNode();
+                       if (leftNode != null && rightNode != null) {
+                               RNANodeValue v1 = leftNode.getValue();
+                               RNANodeValue v2 = rightNode.getValue();
+                               int l1 = v1.getLeftBasePosition();
+                               int r1 = v1.getRightBasePosition();
+                               int l2 = v2.getLeftBasePosition();
+                               int r2 = v2.getRightBasePosition();
+                               if (l1 >= 0 && l2 >= 0) {
+                                       m.addCouple(l1, l2);
+                               }
+                               if (r1 >= 0 && r2 >= 0) {
+                                       m.addCouple(r1, r2);
+                               }
+                       }
+                       for (Tree<AlignedNode<RNANodeValue,RNANodeValue>> child: tree.getChildren()) {
+                               convertSubTree(child);
+                       }
+               }
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/RNATree2.java b/src2/fr/orsay/lri/varna/models/treealign/RNATree2.java
new file mode 100644 (file)
index 0000000..753819b
--- /dev/null
@@ -0,0 +1,172 @@
+package fr.orsay.lri.varna.models.treealign;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+
+import fr.orsay.lri.varna.exceptions.MappingException;
+import fr.orsay.lri.varna.models.rna.Mapping;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+/**
+ * This class contains all functions that are specific to trees
+ * (class Tree) of RNA, with RNANodeValue2.
+ * 
+ * @author Raphael Champeimont
+ *
+ */
+public class RNATree2 {
+       /**
+        * Convert an RNA object into a RNA tree with RNANodeValue2.
+        * @throws RNATree2Exception 
+        */
+       public static Tree<RNANodeValue2> RNATree2FromRNA(RNA rna) throws RNATree2Exception {
+               Tree<RNANodeValue> fullTree = RNATree.RNATreeFromRNA(rna);
+               return RNATree2FromRNATree(fullTree);
+       }
+
+       /**
+        * Convert from RNANodeValue model to RNANodeValue2 model,
+        * ie. compact consecutive non-paired bases.
+        */
+       public static Tree<RNANodeValue2> RNATree2FromRNATree(Tree<RNANodeValue> originalTree) throws RNATree2Exception {
+               Tree<RNANodeValue2> newTree = new Tree<RNANodeValue2>();
+               // Root in original tree is fake, so make a fake root
+               newTree.setValue(null);
+               newTree.replaceChildrenListBy(RNAForest2FromRNAForest(originalTree.getChildren()));
+               return newTree;
+       }
+       
+       private static void RNAForest2FromRNAForestCommitNonPaired(List<Tree<RNANodeValue2>> forest, List<RNANodeValue> consecutiveNonPairedBases) {
+               // add the group of non-paired bases if there is one
+               if (consecutiveNonPairedBases.size() > 0) {
+                       RNANodeValue2 groupOfConsecutiveBases = new RNANodeValue2(false);
+                       groupOfConsecutiveBases.getNodes().addAll(consecutiveNonPairedBases);
+                       Tree<RNANodeValue2> groupOfConsecutiveBasesNode = new Tree<RNANodeValue2>();
+                       groupOfConsecutiveBasesNode.setValue(groupOfConsecutiveBases);
+                       forest.add(groupOfConsecutiveBasesNode);
+                       consecutiveNonPairedBases.clear();
+               }
+       }
+       
+       private static List<Tree<RNANodeValue2>> RNAForest2FromRNAForest(List<Tree<RNANodeValue>> originalForest) throws RNATree2Exception {
+               List<Tree<RNANodeValue2>> forest = new ArrayList<Tree<RNANodeValue2>>();
+               List<RNANodeValue> consecutiveNonPairedBases = new LinkedList<RNANodeValue>();
+               for (Tree<RNANodeValue> originalTree: originalForest) {
+                       if (originalTree.getValue().getRightBasePosition() == -1) {
+                               // non-paired base
+                               if (originalTree.getChildren().size() > 0) {
+                                       throw (new RNATree2Exception("Non-paired base cannot have children."));
+                               }
+                               
+                               switch (originalTree.getValue().getOrigin()) {
+                               case BASE_FROM_HELIX_STRAND5:
+                               case BASE_FROM_HELIX_STRAND3:
+                                       // This base is part of a broken base pair
+                                       
+                                       // if we have gathered some non-paired bases, add a node with
+                                       // the group of them 
+                                       RNAForest2FromRNAForestCommitNonPaired(forest, consecutiveNonPairedBases);
+                                       
+                                       // now add the node
+                                       RNANodeValue2 pairedBase = new RNANodeValue2(true);
+                                       pairedBase.setNode(originalTree.getValue());
+                                       Tree<RNANodeValue2> pairedBaseNode = new Tree<RNANodeValue2>();
+                                       pairedBaseNode.setValue(pairedBase);
+                                       forest.add(pairedBaseNode);
+                                       break;
+                               case BASE_FROM_UNPAIRED_REGION:
+                                       consecutiveNonPairedBases.add(originalTree.getValue());
+                                       break;
+                               case BASE_PAIR_FROM_HELIX:
+                                       throw (new RNATree2Exception("Origin is BASE_PAIR_FROM_HELIX but this is not a pair."));
+                               }
+                       } else {
+                               // paired bases
+                               
+                               // if we have gathered some non-paired bases, add a node with
+                               // the group of them 
+                               RNAForest2FromRNAForestCommitNonPaired(forest, consecutiveNonPairedBases);
+                               
+                               // now add the node
+                               RNANodeValue2 pairedBase = new RNANodeValue2(true);
+                               pairedBase.setNode(originalTree.getValue());
+                               Tree<RNANodeValue2> pairedBaseNode = new Tree<RNANodeValue2>();
+                               pairedBaseNode.setValue(pairedBase);
+                               pairedBaseNode.replaceChildrenListBy(RNAForest2FromRNAForest(originalTree.getChildren()));
+                               forest.add(pairedBaseNode);
+                       }
+               }
+               
+               // if there we have some non-paired bases, add them grouped
+               RNAForest2FromRNAForestCommitNonPaired(forest, consecutiveNonPairedBases);
+               
+               return forest;
+       }
+       
+       
+       /**
+        * Convert an RNA tree (with RNANodeValue2) alignment into a Mapping.
+        */
+       public static Mapping mappingFromAlignment(Tree<AlignedNode<RNANodeValue2,RNANodeValue2>> alignment) throws MappingException {
+               ConvertToMapping converter = new ConvertToMapping();
+               return converter.convert(alignment);
+       }
+       
+       private static class ConvertToMapping {
+               private Mapping m;
+               ExampleDistance3 sequenceAligner = new ExampleDistance3();
+               
+               public Mapping convert(Tree<AlignedNode<RNANodeValue2,RNANodeValue2>> tree) throws MappingException {
+                       m = new Mapping();
+                       convertSubTree(tree);
+                       return m;
+               }
+               
+               private void convertSubTree(Tree<AlignedNode<RNANodeValue2,RNANodeValue2>> tree) throws MappingException {
+                       AlignedNode<RNANodeValue2,RNANodeValue2> alignedNode = tree.getValue();
+                       Tree<RNANodeValue2> leftNode  = alignedNode.getLeftNode();
+                       Tree<RNANodeValue2> rightNode = alignedNode.getRightNode();
+                       if (leftNode != null && rightNode != null) {
+                               RNANodeValue2 v1 = leftNode.getValue();
+                               RNANodeValue2 v2 = rightNode.getValue();
+                               if (v1.isSingleNode() && v2.isSingleNode()) {
+                                       // we have aligned (x,y) with (x',y')
+                                       // so we map x with x' and y with y'
+                                       RNANodeValue vsn1 = v1.getNode();
+                                       RNANodeValue vsn2 = v2.getNode();
+                                       int l1 = vsn1.getLeftBasePosition();
+                                       int r1 = vsn1.getRightBasePosition();
+                                       int l2 = vsn2.getLeftBasePosition();
+                                       int r2 = vsn2.getRightBasePosition();
+                                       if (l1 >= 0 && l2 >= 0) {
+                                               m.addCouple(l1, l2);
+                                       }
+                                       if (r1 >= 0 && r2 >= 0) {
+                                               m.addCouple(r1, r2);
+                                       }
+                               } else if (!v1.isSingleNode() && !v2.isSingleNode()) {
+                                       // We have aligned x1 x2 ... xn with y1 y2 ... ym.
+                                       // So we will now (re-)compute this sequence alignment.
+                                       int[][] sequenceAlignment = sequenceAligner.alignSequenceNodes(v1, v2).getAlignment();
+                                       int l = sequenceAlignment[0].length;
+                                       for (int i=0; i<l; i++) {
+                                               // b1 and b2 are indexes in the aligned sequences
+                                               int b1 = sequenceAlignment[0][i];
+                                               int b2 = sequenceAlignment[1][i];
+                                               if (b1 != -1 && b2 != -1) {
+                                                       int l1 = v1.getNodes().get(b1).getLeftBasePosition();
+                                                       int l2 = v2.getNodes().get(b2).getLeftBasePosition();
+                                                       m.addCouple(l1, l2);
+                                               }
+                                       }
+
+                               }
+                       }
+                       
+                       for (Tree<AlignedNode<RNANodeValue2,RNANodeValue2>> child: tree.getChildren()) {
+                               convertSubTree(child);
+                       }
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/RNATree2Exception.java b/src2/fr/orsay/lri/varna/models/treealign/RNATree2Exception.java
new file mode 100644 (file)
index 0000000..81ccce9
--- /dev/null
@@ -0,0 +1,15 @@
+package fr.orsay.lri.varna.models.treealign;
+
+/**
+ * @author Raphael Champeimont
+ *
+ */
+public class RNATree2Exception extends Exception {
+       
+       private static final long serialVersionUID = 2034802149835891010L;
+
+       public RNATree2Exception(String message) {
+               super(message);
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/Tree.java b/src2/fr/orsay/lri/varna/models/treealign/Tree.java
new file mode 100644 (file)
index 0000000..ff00e71
--- /dev/null
@@ -0,0 +1,157 @@
+package fr.orsay.lri.varna.models.treealign;
+import java.util.*;
+
+
+/**
+ * An object of this class is a rooted tree, where children are ordered.
+ * The tree is iterable, and the default iterator is DFS
+ * (depth-first search), with the fathers given before the children.
+ * 
+ * @param <T> The type of values on nodes.
+ * @author Raphael Champeimont
+ */
+public class Tree<T> implements Iterable<Tree<T>> {
+       private List<Tree<T>> children;
+       private T value;
+       private Tree<T> tree = this;
+       
+       public T getValue() {
+               return value;
+       }
+
+       public void setValue(T value) {
+               this.value = value;
+       }
+
+       /**
+        * Returns the list of children.
+        * The return list has a O(1) access time to any of its elements
+        * (ie. it is like an array and unlike a linked list)
+        */
+       public List<Tree<T>> getChildren() {
+               return children;
+       }
+       
+       /**
+        * This method replaces the list of children of a tree with the list given
+        * as argument. Be careful, because it means the list will be kept as a
+        * reference (it will not be copied) so if you later modify the list
+        * you passed as an argument here, it will modify the list of children.
+        * Note that the List object you give must have a 0(1) access time to
+        * elements (because someone calling getChildren() can expect that property).
+        * This method may be useful if you have already built a list of children
+        * and you don't want to use this.getChildren.addAll() to avoid a O(n) copy.
+        * In that case you would simply call the constructor that takes no argument
+        * to create an empty tree and then call replaceChildrenListBy(children)
+        * where children is the list of children you have built.
+        * @param children the new list of children
+        */
+       public void replaceChildrenListBy(List<Tree<T>> children) {
+               this.children = children;
+       }
+
+       /**
+        * Creates a tree, with the given set of children.
+        * The given set is any collection that implements Iterable<Tree>.
+        * The set is iterated on and its elements are copied (as references).
+        */
+       public Tree(Iterable<Tree<T>> children) {
+               this();
+               for (Tree<T> child: children) {
+                       this.children.add(child);
+               }
+       }
+       
+       /**
+        * Creates a tree, with an empty list of children.
+        */
+       public Tree() {
+               children = new ArrayList<Tree<T>>();
+       }
+       
+       /**
+        * Returns the number of children of the root node.
+        */
+       public int rootDegree() {
+               return children.size();
+       }
+       
+       
+       /**
+        * Count the nodes in the tree.
+        * Time: O(n)
+        * @return the number of nodes in the tree
+        */
+       public int countNodes() {
+               int count = 1;
+               for (Tree<T> child: children) {
+                       count += child.countNodes();
+               }
+               return count;
+       }
+       
+       /**
+        * Compute the tree degree, ie. the max over nodes of the node degree.
+        * Time: O(n)
+        * @return the maximum node degree
+        */
+       public int computeDegree() {
+               int max = children.size();
+               for (Tree<T> child: children) {
+                       int maxCandidate = child.computeDegree();
+                       if (maxCandidate > max) {
+                               max = maxCandidate;
+                       }
+               }
+               return max;
+       }
+       
+       /**
+        * Returns a string unique to this node.
+        */
+       public String toGraphvizNodeId() {
+               return super.toString();
+       }
+       
+       
+       public Iterator<Tree<T>> iterator() {
+               return (new DFSPrefixIterator());
+       }
+       
+       /**
+        * An iterator that returns the nodes in prefix (fathers before
+        * children) DFS (go deep first) order.
+        */
+       public class DFSPrefixIterator implements Iterator<Tree<T>> {
+               private LinkedList<Tree<T>> remainingNodes = new LinkedList<Tree<T>>();
+               
+               public boolean hasNext() {
+                       return !remainingNodes.isEmpty();
+               }
+               
+               public Tree<T> next() {
+                       if (remainingNodes.isEmpty()) {
+                               throw (new NoSuchElementException());
+                       }
+                       Tree<T> currentNode = remainingNodes.getLast();
+                       remainingNodes.removeLast();
+                       List<Tree<T>> children = currentNode.getChildren();
+                       int n = children.size();
+                       // The children access is in O(1) so this loop is O(n)
+                       for (int i=n-1; i>=0; i--) {
+                               // We add the children is their reverse order so they
+                               // are given in the original order by the iterator
+                               remainingNodes.add(children.get(i));
+                       }
+                       return currentNode;
+               }
+               
+               public DFSPrefixIterator() {
+                       remainingNodes.add(tree);
+               }
+
+               public void remove() {
+                       throw (new UnsupportedOperationException());
+               }
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/TreeAlign.java b/src2/fr/orsay/lri/varna/models/treealign/TreeAlign.java
new file mode 100644 (file)
index 0000000..ebf89d6
--- /dev/null
@@ -0,0 +1,775 @@
+package fr.orsay.lri.varna.models.treealign;
+
+import java.util.*;
+
+
+/**
+ * Tree alignment algorithm.
+ * This class implements the tree alignment algorithm
+ * for ordered trees explained in article:
+ *   T. Jiang, L. Wang, K. Zhang,
+ *   Alignment of trees - an alternative to tree edit,
+ *   Theoret. Comput. Sci. 143 (1995).
+ * Other references:
+ * - Claire Herrbach, Alain Denise and Serge Dulucq.
+ *   Average complexity of the Jiang-Wang-Zhang pairwise tree alignment
+ *   algorithm and of a RNA secondary structure alignment algorithm.
+ *   Theoretical Computer Science 411 (2010) 2423-2432.
+ *   
+ * Our implementation supposes that the trees will never have more
+ * than 32000 nodes and that the total distance will never require more
+ * significant digits that a float (single precision) has. 
+ * 
+ * @author Raphael Champeimont
+ * @param <ValueType1> The type of values on nodes in the first tree.
+ * @param <ValueType2> The type of values on nodes in the second tree.
+ */
+public class TreeAlign<ValueType1, ValueType2> {
+       
+       private class TreeData<ValueType> {
+               /**
+                * The tree.
+                */
+               public Tree<ValueType> tree;
+               
+               /**
+                * The tree size (number of nodes).
+                */
+               public int size = -1;
+               
+               /**
+                * The number of children of a node is called the node degree.
+                * This variable is the maximum node degree in the tree.
+                */
+               public int degree = -1;
+               
+               /**
+                * The number of children of a node is called the node degree.
+                * degree[i] is the degree of node i, with i being an index in nodes.
+                */
+               public int[] degrees;
+               
+               /**
+                * The trees as an array of its nodes (subtrees rooted at each node
+                * in fact), in postorder. 
+                */
+               public Tree<ValueType>[] nodes;
+               
+               /**
+                * children[i] is the array of children (as indexes in nodes)
+                * of i (an index in nodes)
+                */
+               public int[][] children;
+               
+               /**
+                * Values of nodes.
+                */
+               public ValueType[] values;
+       }
+
+
+       /**
+        * The distance function between labels.
+        */
+       private TreeAlignLabelDistanceAsymmetric<ValueType1,ValueType2> labelDist;
+
+       
+       /**
+        * Create a TreeAlignSymmetric object, which can align trees.
+        * The distance function will be called only once on every pair
+        * of nodes. The result is then kept in a matrix, so you need not manage
+        * yourself a cache of f(value1, value2).
+        * Note that it is permitted to have null values on nodes,
+        * so comparing a node with a non-null value with a node with a null
+        * value will give the same cost as to insert the first node.
+        * This can be useful if you tree has "fake" nodes.
+        * @param labelDist The label distance.
+        */
+       public TreeAlign(TreeAlignLabelDistanceAsymmetric<ValueType1,ValueType2> labelDist) {
+               this.labelDist = labelDist;
+       }
+       
+
+       
+       private class ConvertTreeToArray<ValueType> {
+               private int nextNodeIndex = 0;
+               private TreeData<ValueType> treeData;
+               
+               public ConvertTreeToArray(TreeData<ValueType> treeData) {
+                       this.treeData = treeData;
+               }
+               
+               private void convertTreeToArrayAux(
+                               Tree<ValueType> subtree,
+                               int[] siblingIndexes,
+                               int siblingNumber) throws TreeAlignException {
+                       // We want it in postorder, so first we put the children
+                       List<Tree<ValueType>> children = subtree.getChildren();
+                       int numberOfChildren = children.size();
+                       int[] childrenIndexes = new int[numberOfChildren];
+                       int myIndex = -1;
+                       {
+                               int i = 0;
+                               for (Tree<ValueType> child: children) {
+                                       convertTreeToArrayAux(child, childrenIndexes, i);
+                                       i++;
+                               }
+                       }
+                       // Compute the maximum degree
+                       if (numberOfChildren > treeData.degree) {
+                               treeData.degree = numberOfChildren;
+                       }
+                       // Now we add the node (root of the given subtree).
+                       myIndex = nextNodeIndex;
+                       nextNodeIndex++;
+                       treeData.nodes[myIndex] = subtree;
+                       // Record how many children I have
+                       treeData.degrees[myIndex] = numberOfChildren;
+                       // Store my value in an array
+                       ValueType v = subtree.getValue();
+                       treeData.values[myIndex] = v;
+                       // Tell the caller my index
+                       siblingIndexes[siblingNumber] = myIndex;
+                       // Record my children indexes
+                       treeData.children[myIndex] = childrenIndexes;
+               }
+               
+               /**
+                * Reads: treeData.tree
+                * Computes: treeData.nodes, treeData.degree, treeData.degrees
+                *           treeData.fathers, treeData.children, treeData.size,
+                *           treeData.values
+                * Converts a tree to an array of nodes, in postorder.
+                * We also compute the maximum node degree in the tree.
+                * @throws TreeAlignException 
+                */
+               @SuppressWarnings("unchecked")
+               public void convert() throws TreeAlignException {
+                       treeData.degree = 0;
+                       treeData.size = treeData.tree.countNodes();
+                       // we didn't write new Tree<ValueType>[treeData.size] because
+                       // java does not support generics with arrays
+                       treeData.nodes = new Tree[treeData.size];
+                       treeData.children = new int[treeData.size][];
+                       treeData.degrees = new int[treeData.size];
+                       treeData.values = (ValueType[]) new Object[treeData.size];
+                       int rootIndex[] = new int[1];
+                       convertTreeToArrayAux(treeData.tree, rootIndex, 0);
+               }
+       }
+       
+
+       /**
+        * For arrays that take at least O(|T1|*|T2|) we take care
+        * not to use too big data types.
+        */
+       private class Aligner {
+               /**
+                * The first tree.
+                */
+               private TreeData<ValueType1> treeData1;
+               
+               /**
+                * The second tree. 
+                */
+               private TreeData<ValueType2> treeData2;
+               
+               /**
+                * DF1[i][j_t] is DFL for (i,j,s,t) with s=0.
+                * See description of DFL in Aligner.computeAlignmentP1().
+                * DF1 and DF2 are the "big" arrays, ie. those that may the space
+                * complexity what it is.
+                */
+               private float[][][][] DF1;
+               
+               /**
+                * DF2[j][i_s] is DFL for (i,j,s,t) with t=0.
+                * See description of DFL in Aligner.computeAlignmentP1().
+                */
+               private float[][][][] DF2;
+               
+               /**
+                * This arrays have the same shape as respectively DF1.
+                * They are used to remember which term in the minimum won, so that
+                * we can compute the alignment.
+                * Decision1 is a case number (< 10)
+                * and Decision2 is a child index, hence the types.
+                */
+               private byte[][][][] DF1Decisions1;
+               private short[][][][] DF1Decisions2;
+               
+               /**
+                * This arrays have the same shape as respectively DF2.
+                * They are used to remember which term in the minimum won, so that
+                * we can compute the alignment.
+                */
+               private byte[][][][] DF2Decisions1;
+               private short[][][][] DF2Decisions2;
+               
+               /**
+                * Distances between subtrees.
+                * DT[i][j] is the distance between the subtree rooted at i in the first tree
+                * and the subtree rooted at j in the second tree.
+                */
+               private float[][] DT;
+               
+               /**
+                * This array has the same shape as DT, but is used to remember which
+                * case gave the minimum, so that we can later compute the alignment.
+                */
+               private byte[][] DTDecisions1;
+               private short[][] DTDecisions2;
+               
+               /**
+                * Distances between labels.
+                * DL[i][j] is the distance labelDist.f(value(T1[i]), value(T2[i])).
+                * By convention, we say that value(T1[|T1|]) = null
+                * and value(T2[|T2|]) = null
+                */
+               private float[][] DL;
+               
+               /**
+                * DET1[i] is the distance between the empty tree and T1[i]
+                * (the subtree rooted at node i in the first tree).
+                */
+               private float[] DET1;
+               
+               /**
+                * Same as DET1, but for second tree.
+                */
+               private float[] DET2;
+               
+               /**
+                * DEF1[i] is the distance between the empty forest and F1[i]
+                * (the forest of children of node i in the first tree).
+                */
+               private float[] DEF1;
+               
+               /**
+                * Same as DEF1, but for second tree.
+                */
+               private float[] DEF2;
+               
+               
+               /**
+                * @param i node in T1
+                * @param s number of first child of i to consider
+                * @param m_i degree of i
+                * @param j node in T2
+                * @param t number of first child of j to consider
+                * @param n_j degree of j
+                * @param DFx which array to fill (DF1 or DF2)
+                */
+               private void computeAlignmentP1(int i, int s, int m_i, int j, int t, int n_j, int DFx) {
+                       /**
+                        * DFL[pr][qr] is D(F1[i_s, i_p], F2[j_t, j_q])
+                        * where p=s+pr-1 and q=t+qr-1 (ie. pr=p-s+1 and qr=q-t+1)
+                        * By convention, F1[i_s, i_{s-1}] and F2[j_t, j_{t-1}] are the
+                        * empty forests.
+                        * Said differently, DFL[pr][qr] is the distance between the forest
+                        * of the pr first children of i, starting with child s
+                        * (first child is s = 0), and the forest of the qr first children
+                        * of j, starting with child t (first child is t = 0).
+                        * This array is allocated for a fixed value of (i,j,s,t).
+                        */
+                       float[][] DFL;
+                       
+                       /**
+                        * Same shape as DFL, but to remember which term gave the min,
+                        * so that we can later compute the alignment.
+                        */
+                       byte[][] DFLDecisions1;
+                       short[][] DFLDecisions2;
+                       
+                       DFL = new float[m_i-s+2][n_j-t+2];
+                       DFL[0][0] = 0; // D(empty forest, empty forest) = 0
+                       
+                       DFLDecisions1 = new byte[m_i-s+2][n_j-t+2];
+                       DFLDecisions2 = new short[m_i-s+2][n_j-t+2];
+                       
+                       // Compute indexes of i_s and j_t because we will need them
+                       int i_s = m_i != 0 ? treeData1.children[i][s] : -1;
+                       int j_t = n_j != 0 ? treeData2.children[j][t] : -1;
+                       
+                       for (int p=s; p<m_i; p++) {
+                               DFL[p-s+1][0] = DFL[p-s][0] + DET1[treeData1.children[i][p]];
+                       }
+                       
+                       for (int q=t; q<n_j; q++) {
+                               DFL[0][q-t+1] = DFL[0][q-t] + DET2[treeData2.children[j][q]];
+                       }
+                       
+                       for (int p=s; p<m_i; p++) {
+                               int i_p = treeData1.children[i][p];
+                               for (int q=t; q<n_j; q++) {
+                                       int j_q = treeData2.children[j][q];
+                                       
+                                       float min = Float.POSITIVE_INFINITY;
+                                       int decision1 = -1;
+                                       int decision2 = -1;
+                                       
+                                       // Lemma 3 - Case: We delete the rightmost tree of T1
+                                       {
+                                               float minCandidate = DFL[p-s][q-t+1] + DET1[i_p];
+                                               if (minCandidate < min) {
+                                                       min = minCandidate;
+                                                       decision1 = 1;
+                                               }
+                                       }
+                                       
+                                       // Lemma 3 - Case: We insert the rightmost tree of T2 (symmetric of previous case)
+                                       {
+                                               float minCandidate = DFL[p-s+1][q-t] + DET2[j_q];
+                                               if (minCandidate < min) {
+                                                       min = minCandidate;
+                                                       decision1 = 2;
+                                               }
+                                       }
+                                       
+                                       // Lemma 3 - Case: Align rightmost trees with each other
+                                       {
+                                               float minCandidate = 
+                                                       DFL[p-s][q-t] + DT [i_p] [j_q];
+                                               if (minCandidate < min) {
+                                                       min = minCandidate;
+                                                       decision1 = 3;
+                                               }
+                                       }
+                                       
+                                       // Lemma 3 - Case: We cut the T1 forest and match the first part
+                                       // with the T2 forest except the rightmost tree, and we match the second
+                                       // part with the T2 rightmost tree's forest of children
+                                       {
+                                               float minCandidate = Float.POSITIVE_INFINITY;
+                                               int best_k = -1;
+                                               for (int k=s; k<p; k++) {
+                                                       float d = DFL[k-s][q-t]
+                                                                + DF2 [j_q] [treeData1.children[i][k]] [p-k+1] [treeData2.degrees[j_q]];
+                                                       if (d < minCandidate) {
+                                                               minCandidate = d;
+                                                               best_k = k;
+                                                       }
+                                               }
+                                               minCandidate += DL[treeData1.size][j_q];
+                                               if (minCandidate < min) {
+                                                       min = minCandidate;
+                                                       decision1 = 4;
+                                                       decision2 = best_k;
+                                               }
+                                       }
+                                       
+                                       // Lemma 3 - Case: Syemmetric of preivous case
+                                       {
+                                               float minCandidate = Float.POSITIVE_INFINITY;
+                                               int best_k = -1;
+                                               for (int k=t; k<q; k++) {
+                                                       float d = DFL[p-s][k-t]
+                                                                + DF1 [i_p] [treeData2.children[j][k]] [treeData1.degrees[i_p]] [q-k+1];
+                                                       if (d < minCandidate) {
+                                                               minCandidate = d;
+                                                               best_k = k;
+                                                       }
+                                               }
+                                               minCandidate += DL[i_p][treeData2.size];
+                                               if (minCandidate < min) {
+                                                       min = minCandidate;
+                                                       decision1 = 5;
+                                                       decision2 = best_k;
+                                               }
+                                       }
+                                       
+                                       DFL[p-s+1][q-t+1] = min;
+                                       DFLDecisions1[p-s+1][q-t+1] = (byte) decision1;
+                                       DFLDecisions2[p-s+1][q-t+1] = (short) decision2;
+                               }
+                       }
+                       
+                       // Copy references to DFL to persistent arrays
+                       if (DFx == 2) {
+                               DF2[j][i_s] = DFL;
+                               DF2Decisions1[j][i_s] = DFLDecisions1;
+                               DF2Decisions2[j][i_s] = DFLDecisions2;
+                       } else {
+                               DF1[i][j_t] = DFL;
+                               DF1Decisions1[i][j_t] = DFLDecisions1;
+                               DF1Decisions2[i][j_t] = DFLDecisions2;
+                       }
+                       
+               }
+               
+               public float align() throws TreeAlignException {
+                       (new ConvertTreeToArray<ValueType1>(treeData1)).convert();
+                       (new ConvertTreeToArray<ValueType2>(treeData2)).convert();
+                       
+                       // Allocate necessary arrays
+                       DT = new float[treeData1.size][treeData2.size];
+                       DTDecisions1 = new byte[treeData1.size][treeData2.size];
+                       DTDecisions2 = new short[treeData1.size][treeData2.size];
+                       DL = new float[treeData1.size+1][treeData2.size+1];
+                       DET1 = new float[treeData1.size];
+                       DET2 = new float[treeData2.size];
+                       DEF1 = new float[treeData1.size];
+                       DEF2 = new float[treeData2.size];
+                       DF1 = new float[treeData1.size][treeData2.size][][];
+                       DF1Decisions1 = new byte[treeData1.size][treeData2.size][][];
+                       DF1Decisions2 = new short[treeData1.size][treeData2.size][][];
+                       DF2 = new float[treeData2.size][treeData1.size][][];
+                       DF2Decisions1 = new byte[treeData2.size][treeData1.size][][];
+                       DF2Decisions2 = new short[treeData2.size][treeData1.size][][];
+                       
+                       DL[treeData1.size][treeData2.size] = (float) labelDist.f(null, null);
+
+                       for (int i=0; i<treeData1.size; i++) {
+                               int m_i = treeData1.degrees[i];
+                               DEF1[i] = 0;
+                               for (int k=0; k<m_i; k++) {
+                                       DEF1[i] += DET1[treeData1.children[i][k]];
+                               }
+                               DL[i][treeData2.size] = (float) labelDist.f((ValueType1) treeData1.values[i], null);
+                               DET1[i] = DEF1[i] + DL[i][treeData2.size];
+                       }
+                       
+                       for (int j=0; j<treeData2.size; j++) {
+                               int n_j = treeData2.degrees[j];
+                               DEF2[j] = 0;
+                               for (int k=0; k<n_j; k++) {
+                                       DEF2[j] += DET2[treeData2.children[j][k]];
+                               }
+                               DL[treeData1.size][j] = (float) labelDist.f(null, (ValueType2) treeData2.values[j]);
+                               DET2[j] = DEF2[j] + DL[treeData1.size][j];
+                       }
+                       
+
+                       for (int i=0; i<treeData1.size; i++) {
+                               int m_i = treeData1.degrees[i];
+                               for (int j=0; j<treeData2.size; j++) {
+                                       int n_j = treeData2.degrees[j];
+                                       
+                                       // Precompute f(value(i), value(j)) and keep the result
+                                       // to avoid calling f on the same values several times.
+                                       // This is important in case the computation of f takes
+                                       // long.
+                                       DL[i][j] = (float) labelDist.f((ValueType1) treeData1.values[i], (ValueType2) treeData2.values[j]);
+                                       
+                                       for (int s=0; s<m_i; s++) {
+                                               computeAlignmentP1(i, s, m_i, j, 0, n_j, 2);
+                                       }
+                                       
+                                       for (int t=0; t<n_j; t++) {
+                                               computeAlignmentP1(i, 0, m_i, j, t, n_j, 1);
+                                       }
+                                       
+                                       DT[i][j] = Float.POSITIVE_INFINITY;
+                                       // Lemma 2 - Case: Root is (blank, j)
+                                       {
+                                               float minCandidate = Float.POSITIVE_INFINITY;
+                                               int best_r = -1;
+                                               for (int r=0; r<n_j; r++) {
+                                                       float d = DT[i][treeData2.children[j][r]] - DET2[treeData2.children[j][r]];
+                                                       if (d < minCandidate) {
+                                                               minCandidate = d;
+                                                               best_r = r;
+                                                       }
+                                               }
+                                               minCandidate += DET2[j];
+                                               if (minCandidate < DT[i][j]) {
+                                                       DT[i][j] = minCandidate;
+                                                       DTDecisions1[i][j] = 1;
+                                                       DTDecisions2[i][j] = (short) best_r;
+                                               }
+                                       }
+                                       // Lemma 2 - Case: Root is (i, blank)
+                                       {
+                                               float minCandidate = Float.POSITIVE_INFINITY;
+                                               int best_r = -1;
+                                               for (int r=0; r<m_i; r++) {
+                                                       float d = DT[treeData1.children[i][r]][j] - DET1[treeData1.children[i][r]];
+                                                       if (d < minCandidate) {
+                                                               minCandidate = d;
+                                                               best_r = r;
+                                                       }
+                                               }
+                                               minCandidate += DET1[i];
+                                               if (minCandidate < DT[i][j]) {
+                                                       DT[i][j] = minCandidate;
+                                                       DTDecisions1[i][j] = 2;
+                                                       DTDecisions2[i][j] = (short) best_r;
+                                               }
+                                       }
+                                       // Lemma 2 - Case: Root is (i,j)
+                                       {
+                                               float minCandidate;
+                                               if (n_j != 0) {
+                                                       minCandidate = DF1 [i] [treeData2.children[j][0]] [m_i] [n_j];
+                                               } else {
+                                                       if (m_i != 0) {
+                                                               minCandidate = DF2 [j] [treeData1.children[i][0]] [m_i] [n_j];
+                                                       } else {
+                                                               minCandidate = 0; // D(empty forest, empty forest) = 0
+                                                       }
+                                               }
+                                               minCandidate += DL[i][j];
+                                               if (minCandidate < DT[i][j]) {
+                                                       DT[i][j] = minCandidate;
+                                                       DTDecisions1[i][j] = 3;
+                                               }
+                                       }
+                                       
+                                       
+                               }
+                       }
+
+                       
+                       // We return the distance beetween T1[root] and T2[root].
+                       return DT[treeData1.size-1][treeData2.size-1];
+               }
+               
+               public Aligner(Tree<ValueType1> T1, Tree<ValueType2> T2) {
+                       treeData1 = new TreeData<ValueType1>();
+                       treeData1.tree = T1;
+                       treeData2 = new TreeData<ValueType2>();
+                       treeData2.tree = T2;
+               }
+               
+               /** Align F1[i_s,i_p] with F2[j_t,j_q].
+                * If p = s-1, by convention it means F1[i_s,i_p] = empty forest.
+                * Idem for q=t-1.
+                */
+               private List<Tree<AlignedNode<ValueType1,ValueType2>>> computeForestAlignment(int i, int s, int p, int j, int t, int q) {
+                       if (p == s-1) { // left forest is the empty forest
+                               List<Tree<AlignedNode<ValueType1,ValueType2>>> result = new ArrayList<Tree<AlignedNode<ValueType1,ValueType2>>>();
+                               for (int k=t; k<=q; k++) {
+                                       result.add(treeInserted(treeData2.children[j][k]));
+                               }
+                               return result;
+                       } else {
+                               if (q == t-1) { // right forest is the empty forest
+                                       List<Tree<AlignedNode<ValueType1,ValueType2>>> result = new ArrayList<Tree<AlignedNode<ValueType1,ValueType2>>>();
+                                       for (int k=s; k<=p; k++) {
+                                               result.add(treeDeleted(treeData1.children[i][k]));
+                                       }
+                                       return result;
+                               } else { // both forests are non-empty
+                                       int decision1, k;
+                                       if (s == 0) {
+                                               decision1 =
+                                                       DF1Decisions1 [i] [treeData2.children[j][t]] [p-s+1] [q-t+1];
+                                               k = 
+                                                       DF1Decisions2 [i] [treeData2.children[j][t]] [p-s+1] [q-t+1];
+                                       } else if (t == 0) {
+                                               decision1 =
+                                                       DF2Decisions1 [j] [treeData1.children[i][s]] [p-s+1] [q-t+1];
+                                               k = 
+                                                       DF2Decisions2 [j] [treeData1.children[i][s]] [p-s+1] [q-t+1];
+                                       } else {
+                                               throw (new Error("TreeAlignSymmetric bug: both s and t are non-zero"));
+                                       }
+                                       switch (decision1) {
+                                       case 1:
+                                       {
+                                               List<Tree<AlignedNode<ValueType1,ValueType2>>> result;
+                                               result = computeForestAlignment(i, s, p-1, j, t, q);
+                                               result.add(treeDeleted(treeData1.children[i][p]));
+                                               return result;
+                                       }
+                                       case 2:
+                                       {
+                                               List<Tree<AlignedNode<ValueType1,ValueType2>>> result;
+                                               result = computeForestAlignment(i, s, p, j, t, q-1);
+                                               result.add(treeInserted(treeData2.children[j][q]));
+                                               return result;
+                                       }
+                                       case 3:
+                                       {
+                                               List<Tree<AlignedNode<ValueType1,ValueType2>>> result;
+                                               result = computeForestAlignment(i, s, p-1, j, t, q-1);
+                                               result.add(computeTreeAlignment(treeData1.children[i][p], treeData2.children[j][q]));
+                                               return result;
+                                       }
+                                       case 4:
+                                       {
+                                               List<Tree<AlignedNode<ValueType1,ValueType2>>> result;
+                                               result = computeForestAlignment(i, s, k-1, j, t, q-1);
+                                               
+                                               int j_q = treeData2.children[j][q];
+                                               Tree<AlignedNode<ValueType1,ValueType2>> insertedNode = new Tree<AlignedNode<ValueType1,ValueType2>>();
+                                               AlignedNode<ValueType1,ValueType2> insertedNodeValue = new AlignedNode<ValueType1,ValueType2>();
+                                               insertedNodeValue.setLeftNode(null);
+                                               insertedNodeValue.setRightNode((Tree<ValueType2>) treeData2.nodes[j_q]);
+                                               insertedNode.setValue(insertedNodeValue);
+                                               
+                                               insertedNode.replaceChildrenListBy(computeForestAlignment(i, k, p, j_q, 0, treeData2.degrees[j_q]-1));
+                                               
+                                               result.add(insertedNode);
+                                               
+                                               return result;
+                                       }
+                                       case 5:
+                                       {
+                                               List<Tree<AlignedNode<ValueType1,ValueType2>>> result;
+                                               result = computeForestAlignment(i, s, p-1, j, t, k-1);
+                                               
+                                               int i_p = treeData1.children[i][p];
+                                               Tree<AlignedNode<ValueType1,ValueType2>> deletedNode = new Tree<AlignedNode<ValueType1,ValueType2>>();
+                                               AlignedNode<ValueType1,ValueType2> deletedNodeValue = new AlignedNode<ValueType1,ValueType2>();
+                                               deletedNodeValue.setLeftNode((Tree<ValueType1>) treeData1.nodes[i_p]);
+                                               deletedNodeValue.setRightNode(null);
+                                               deletedNode.setValue(deletedNodeValue);
+                                               
+                                               deletedNode.replaceChildrenListBy(computeForestAlignment(i_p, 0, treeData1.degrees[i_p]-1, j, k, q));
+                                               
+                                               result.add(deletedNode);
+                                               
+                                               return result;
+                                       }
+                                       default:
+                                               throw (new Error("TreeAlign: decision1 = " + decision1));
+                                       }
+                               }
+                       }
+               }
+               
+               /**
+                * Align T1[i] with the empty tree.
+                * @return the alignment
+                */
+               private Tree<AlignedNode<ValueType1,ValueType2>> treeDeleted(int i) {
+                       Tree<AlignedNode<ValueType1,ValueType2>> root = new Tree<AlignedNode<ValueType1,ValueType2>>();
+                       AlignedNode<ValueType1,ValueType2> alignedNode = new AlignedNode<ValueType1,ValueType2>();
+                       alignedNode.setLeftNode(treeData1.nodes[i]);
+                       alignedNode.setRightNode(null);
+                       root.setValue(alignedNode);
+                       for (int r = 0; r<treeData1.degrees[i]; r++) {
+                               root.getChildren().add(treeDeleted(treeData1.children[i][r]));
+                       }
+                       return root;
+               }
+               
+               /**
+                * Align the empty tree with T2[j].
+                * @return the alignment
+                */
+               private Tree<AlignedNode<ValueType1,ValueType2>> treeInserted(int j) {
+                       Tree<AlignedNode<ValueType1,ValueType2>> root = new Tree<AlignedNode<ValueType1,ValueType2>>();
+                       AlignedNode<ValueType1,ValueType2> alignedNode = new AlignedNode<ValueType1,ValueType2>();
+                       alignedNode.setLeftNode(null);
+                       alignedNode.setRightNode(treeData2.nodes[j]);
+                       root.setValue(alignedNode);
+                       for (int r = 0; r<treeData2.degrees[j]; r++) {
+                               root.getChildren().add(treeInserted(treeData2.children[j][r]));
+                       }
+                       return root;
+               }
+               
+               private Tree<AlignedNode<ValueType1,ValueType2>> computeTreeAlignment(int i, int j) {
+                       switch (DTDecisions1[i][j]) {
+                       case 1:
+                       {
+                               Tree<AlignedNode<ValueType1,ValueType2>> root = new Tree<AlignedNode<ValueType1,ValueType2>>();
+                               
+                               // Compute the value of the node
+                               AlignedNode<ValueType1,ValueType2> alignedNode = new AlignedNode<ValueType1,ValueType2>();
+                               alignedNode.setLeftNode(null);
+                               alignedNode.setRightNode(treeData2.nodes[j]);
+                               root.setValue(alignedNode);
+                               
+                               // Compute the children
+                               for (int r = 0; r<treeData2.degrees[j]; r++) {
+                                       if (r == DTDecisions2[i][j]) {
+                                               root.getChildren().add(computeTreeAlignment(i, treeData2.children[j][r]));
+                                       } else {
+                                               root.getChildren().add(treeInserted(treeData2.children[j][r]));
+                                       }
+                               }
+                               return root;
+                       }
+                       case 2:
+                       {
+                               Tree<AlignedNode<ValueType1,ValueType2>> root = new Tree<AlignedNode<ValueType1,ValueType2>>();
+                               
+                               // Compute the value of the node
+                               AlignedNode<ValueType1,ValueType2> alignedNode = new AlignedNode<ValueType1,ValueType2>();
+                               alignedNode.setLeftNode(treeData1.nodes[i]);
+                               alignedNode.setRightNode(null);
+                               root.setValue(alignedNode);
+                               
+                               // Compute the children
+                               for (int r = 0; r<treeData1.degrees[i]; r++) {
+                                       if (r == DTDecisions2[i][j]) {
+                                               root.getChildren().add(computeTreeAlignment(treeData1.children[i][r], j));
+                                       } else {
+                                               root.getChildren().add(treeDeleted(treeData1.children[i][r]));
+                                       }
+                               }
+                               return root;
+                       }
+                       case 3:
+                       {
+                               Tree<AlignedNode<ValueType1,ValueType2>> root = new Tree<AlignedNode<ValueType1,ValueType2>>();
+                               
+                               // Compute the value of the node
+                               AlignedNode<ValueType1,ValueType2> alignedNode = new AlignedNode<ValueType1,ValueType2>();
+                               alignedNode.setLeftNode(treeData1.nodes[i]);
+                               alignedNode.setRightNode(treeData2.nodes[j]);
+                               root.setValue(alignedNode);
+                               
+                               // Compute the children
+                               List<Tree<AlignedNode<ValueType1,ValueType2>>> children =
+                                       computeForestAlignment(i, 0, treeData1.degrees[i]-1, j, 0, treeData2.degrees[j]-1);
+                               root.replaceChildrenListBy(children);
+                               
+                               return root;
+                       }
+                       default:
+                               throw (new Error("TreeAlign: DTDecisions1[i][j] = " + DTDecisions1[i][j]));
+                       }
+               }
+               
+               public Tree<AlignedNode<ValueType1,ValueType2>> computeAlignment() {
+                       return computeTreeAlignment(treeData1.size-1, treeData2.size-1);
+               }
+               
+       }
+
+       
+       /**
+        * Align T1 with T2, computing both the distance and the alignment.
+        * Time:  O(|T1|*|T2|*(deg(T1)+deg(T2))^2)
+        * Space: O(|T1|*|T2|*(deg(T1)+deg(T2)))
+        * Average (over possible trees) time: O(|T1|*|T2|)
+        * @param T1 The first tree.
+        * @param T2 The second tree.
+        * @return The distance and the alignment.
+        * @throws TreeAlignException 
+        */
+       public TreeAlignResult<ValueType1, ValueType2> align(Tree<ValueType1> T1, Tree<ValueType2> T2) throws TreeAlignException {
+               TreeAlignResult<ValueType1, ValueType2> result = new TreeAlignResult<ValueType1, ValueType2>();
+               Aligner aligner = new Aligner(T1, T2);
+               result.setDistance(aligner.align());
+               result.setAlignment(aligner.computeAlignment());
+               return result;
+       }
+       
+       
+       /**
+        * Takes a alignment, and compute the distance between the two 
+        * original trees. If you have called align(), the result object already
+        * contains the distance D and the alignment A. If you call
+        * distanceFromAlignment on the alignment A it will compute the distance D.
+        */
+       public float distanceFromAlignment(Tree<AlignedNode<ValueType1,ValueType2>> alignment) {
+               Tree<ValueType1> originalT1Node;
+               Tree<ValueType2> originalT2Node;
+               originalT1Node = alignment.getValue().getLeftNode();
+               originalT2Node = alignment.getValue().getRightNode();
+               float d = (float) labelDist.f(
+                               originalT1Node != null ? originalT1Node.getValue() : null,
+                               originalT2Node != null ? originalT2Node.getValue() : null);
+               for (Tree<AlignedNode<ValueType1,ValueType2>> child: alignment.getChildren()) {
+                       d += distanceFromAlignment(child);
+               }
+               return d;
+       }
+
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/TreeAlignException.java b/src2/fr/orsay/lri/varna/models/treealign/TreeAlignException.java
new file mode 100644 (file)
index 0000000..0ad966d
--- /dev/null
@@ -0,0 +1,14 @@
+package fr.orsay.lri.varna.models.treealign;
+
+/**
+ * @author Raphael Champeimont
+ *
+ */
+public class TreeAlignException extends Exception {
+
+       private static final long serialVersionUID = 7782935062930780231L;
+
+       public TreeAlignException(String message) {
+               super(message);
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/TreeAlignLabelDistanceAsymmetric.java b/src2/fr/orsay/lri/varna/models/treealign/TreeAlignLabelDistanceAsymmetric.java
new file mode 100644 (file)
index 0000000..91aff2f
--- /dev/null
@@ -0,0 +1,18 @@
+package fr.orsay.lri.varna.models.treealign;
+
+public interface TreeAlignLabelDistanceAsymmetric<ValueType1, ValueType2> {
+       /** 
+        * Returns the substitution cost between v1 and v2.
+        * We use the convention that a null reference is a blank,
+        * ie. f(x, null) is the cost of deleting x
+        * and f(null, x) is the cost of inserting x.
+        * We won't use f(null, null).
+        * We suppose f is such that:
+        * f(x,x) = 0
+        * 0 <= f(x,y) < +infinity
+        * You may also want to have the triangle inequality,
+        * although the alignment algorithm does not require it:
+        * f(x,z) <= f(x,y) + f(y,z)
+        */
+       public double f(ValueType1 x, ValueType2 y);
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/TreeAlignLabelDistanceSymmetric.java b/src2/fr/orsay/lri/varna/models/treealign/TreeAlignLabelDistanceSymmetric.java
new file mode 100644 (file)
index 0000000..b702bc0
--- /dev/null
@@ -0,0 +1,12 @@
+package fr.orsay.lri.varna.models.treealign;
+
+/**
+ * Same as TreeAlignLabelDistanceAsymmetric, but elements on both
+ * trees are of the same type, and the function is symmetric, ie.
+ * f(x,y) = f(y,x) .
+ *
+ * @param <ValueType>
+ */
+public interface TreeAlignLabelDistanceSymmetric<ValueType> extends TreeAlignLabelDistanceAsymmetric<ValueType, ValueType> {
+       
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/TreeAlignResult.java b/src2/fr/orsay/lri/varna/models/treealign/TreeAlignResult.java
new file mode 100644 (file)
index 0000000..f8ff988
--- /dev/null
@@ -0,0 +1,27 @@
+package fr.orsay.lri.varna.models.treealign;
+
+
+/**
+ * The result of aligning a tree T1 with a tree T2.
+ * On the resulting tree, each node has a value
+ * of type AlignedNode<original value type>.
+ * @author Raphael Champeimont
+ */
+public class TreeAlignResult<ValueType1, ValueType2> {
+       private Tree<AlignedNode<ValueType1, ValueType2>> alignment;
+       private double distance;
+       
+       public Tree<AlignedNode<ValueType1, ValueType2>> getAlignment() {
+               return alignment;
+       }
+       public void setAlignment(Tree<AlignedNode<ValueType1, ValueType2>> alignment) {
+               this.alignment = alignment;
+       }
+       public double getDistance() {
+               return distance;
+       }
+       public void setDistance(double distance) {
+               this.distance = distance;
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/models/treealign/TreeGraphviz.java b/src2/fr/orsay/lri/varna/models/treealign/TreeGraphviz.java
new file mode 100644 (file)
index 0000000..be22782
--- /dev/null
@@ -0,0 +1,114 @@
+package fr.orsay.lri.varna.models.treealign;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+
+
+
+/**
+ * This class translates a Tree to a graphviz file.
+ * @author Raphael Champeimont
+ *
+ * @param <? extends GraphvizDrawableNodeValue> the type of values in the tree
+ */
+public class TreeGraphviz {
+
+       /**
+        * Generates a PostScript file using graphviz.
+        * The dot command must be available.
+        */
+       public static void treeToGraphvizPostscript(Tree<? extends GraphvizDrawableNodeValue> tree, String filename, String title) throws IOException {
+               // generate graphviz source
+               String graphvizSource = treeToGraphviz(tree, title);
+               
+               // open output file
+               BufferedWriter fbw;
+               fbw = new BufferedWriter(new FileWriter(filename));
+       
+       // execute graphviz
+               Process proc = Runtime.getRuntime().exec("dot -Tps");
+       BufferedWriter bw  = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
+       BufferedReader br  = new BufferedReader(new InputStreamReader(proc.getInputStream()));
+       BufferedReader bre = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
+       bw.write(graphvizSource);
+       bw.close();
+       {
+               String line = null;
+            while ((line = br.readLine()) != null) {
+               fbw.write(line + "\n");
+            }
+       }
+       {
+               String line = null;
+            while ((line = bre.readLine()) != null) {
+               System.err.println(line);
+            }
+       }
+       
+       // wait for graphviz to end
+        try {
+                       proc.waitFor();
+               } catch (InterruptedException e) {
+                       e.printStackTrace();
+               }
+
+        // close file
+               fbw.close();
+       }
+       
+       /**
+        * Like treeToGraphvizPostscript(Tree,String,String) but with the title
+        * equal to the filename.
+        */
+       public static void treeToGraphvizPostscript(Tree<? extends GraphvizDrawableNodeValue> tree, String filename) throws IOException {
+               treeToGraphvizPostscript(tree, filename, filename);
+       }
+       
+       /**
+        * Creates a graphviz source file from a Tree.
+        * @param title the title of the graph
+        */
+       public static void treeToGraphvizFile(Tree<? extends GraphvizDrawableNodeValue> tree, String filename, String title) throws IOException {
+               BufferedWriter bw;
+               bw = new BufferedWriter(new FileWriter(filename));
+       bw.write(treeToGraphviz(tree, filename));
+       bw.close();
+       }
+       
+       /**
+        * Like treeToGraphvizFile(Tree,String,String) but with the title
+        * equal to the filename.
+        */
+       public static void treeToGraphvizFile(Tree<? extends GraphvizDrawableNodeValue> tree, String filename) throws IOException {
+               treeToGraphvizFile(tree, filename, filename);
+       }
+       
+       /**
+        * Creates a graphviz source from a Tree.
+        * @param title the title of the graph
+        */
+       public static String treeToGraphviz(Tree<? extends GraphvizDrawableNodeValue> tree, String title) {
+               return "digraph \"" + title + "\" {\n" + subtreeToGraphviz(tree) + "}\n";
+       }
+       
+       private static String subtreeToGraphviz(Tree<? extends GraphvizDrawableNodeValue> tree) {
+               String s = "";
+               String myId = tree.toGraphvizNodeId();
+               
+               s +=
+                       "\""
+                       + myId
+                       + "\" [label=\""
+                       + ((tree.getValue() != null) ? tree.getValue().toGraphvizNodeName() : "null")
+                       + "\"]\n";
+               for (Tree<? extends GraphvizDrawableNodeValue> child: tree.getChildren()) {
+                       s += "\"" + myId + "\" -> \"" + child.toGraphvizNodeId() + "\"\n";
+                       s += subtreeToGraphviz(child);
+               }
+               
+               return s;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/utils/RNAMLParser.java b/src2/fr/orsay/lri/varna/utils/RNAMLParser.java
new file mode 100644 (file)
index 0000000..d5f6746
--- /dev/null
@@ -0,0 +1,651 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Universit� Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.utils;
+
+import java.awt.Point;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Stack;
+import java.util.Vector;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBP.Edge;
+import fr.orsay.lri.varna.models.rna.ModeleBP.Stericity;
+
+public class RNAMLParser extends DefaultHandler {
+       public class HelixTemp {
+               public int pos5, pos3, length;
+               public String name;
+
+               public HelixTemp(int pos5, int pos3, int length, String name) {
+                       this.pos3 = pos3;
+                       this.pos5 = pos5;
+                       this.length = length;
+                       this.name = name;
+               }
+
+               public String toString() {
+                       return ("[" + name + "," + pos5 + "," + pos3 + "," + length + "]");
+               }
+
+       }
+
+       public class BPTemp {
+               public int pos5, pos3;
+               public String edge5, edge3, orientation;
+
+               public BPTemp(int pos5, int pos3, String edge5, String edge3,
+                               String orientation) {
+                       if (edge3 == null) {
+                               edge3 = "+";
+                       }
+                       if (edge5 == null) {
+                               edge5 = "+";
+                       }
+                       if (orientation == null) {
+                               orientation = "c";
+                       }
+                       this.pos5 = pos5;
+                       this.pos3 = pos3;
+                       this.edge5 = edge5;
+                       this.edge3 = edge3;
+                       this.orientation = orientation;
+               }
+
+               public ModeleBP createBPStyle(ModeleBase mb5, ModeleBase mb3) {
+                       ModeleBP.Edge e5, e3;
+                       @SuppressWarnings("unused")
+                       boolean isCanonical = false;
+                       if (edge5.equals("W")) {
+                               e5 = ModeleBP.Edge.WC;
+                       } else if (edge5.equals("H")) {
+                               e5 = ModeleBP.Edge.HOOGSTEEN;
+                       } else if (edge5.equals("S")) {
+                               e5 = ModeleBP.Edge.SUGAR;
+                       } else {
+                               e5 = ModeleBP.Edge.WC;
+                       }
+
+                       if (edge3.equals("W")) {
+                               e3 = ModeleBP.Edge.WC;
+                       } else if (edge3.equals("H")) {
+                               e3 = ModeleBP.Edge.HOOGSTEEN;
+                       } else if (edge3.equals("S")) {
+                               e3 = ModeleBP.Edge.SUGAR;
+                       } else {
+                               e3 = ModeleBP.Edge.WC;
+                       }
+
+                       if ((edge5.equals("+") && edge3.equals("+"))
+                                       || (edge5.equals("-") && edge3.equals("-"))) {
+                               e3 = ModeleBP.Edge.WC;
+                               e5 = ModeleBP.Edge.WC;
+                       }
+
+                       ModeleBP.Stericity ster;
+
+                       if (orientation.equals("c")) {
+                               ster = ModeleBP.Stericity.CIS;
+                       } else if (orientation.equals("t")) {
+                               ster = ModeleBP.Stericity.TRANS;
+                       } else {
+                               ster = ModeleBP.Stericity.CIS;
+                       }
+
+                       return (new ModeleBP(mb5, mb3, e5, e3, ster));
+               }
+
+               public String toString() {
+                       return ("[" + pos5 + "," + pos3 + "," + edge5 + "," + edge3 + ","
+                                       + orientation + "]");
+               }
+       }
+
+       public class RNATmp {
+               public ArrayList<String> _sequence = new ArrayList<String>();
+               public Vector<Integer> _sequenceIDs = new Vector<Integer>();
+               public Vector<BPTemp> _structure = new Vector<BPTemp>();
+               public Vector<HelixTemp> _helices = new Vector<HelixTemp>();
+
+               public ArrayList<String> getSequence() {
+                       return _sequence;
+               }
+
+               public Vector<BPTemp> getStructure() {
+                       return _structure;
+               }
+       };
+
+       private Hashtable<String, RNATmp> _molecules = new Hashtable<String, RNATmp>();
+
+       private boolean _inSequenceIDs, _inLength, _inSequence, _inHelix,
+                       _inStrAnnotation, _inBP, _inBP5, _inBP3, _inEdge5, _inEdge3,
+                       _inPosition, _inBondOrientation, _inMolecule;
+       private StringBuffer _buffer;
+       private String _currentModel = "";
+       private int _id5, _id3, _length;
+       String _edge5, _edge3, _orientation, _helixID;
+
+       public RNAMLParser() {
+               super();
+               _inSequenceIDs = false;
+               _inSequence = false;
+               _inStrAnnotation = false;
+               _inBP = false;
+               _inBP5 = false;
+               _inBP3 = false;
+               _inPosition = false;
+               _inEdge5 = false;
+               _inEdge3 = false;
+               _inBondOrientation = false;
+               _inHelix = false;
+               _inMolecule = false;
+       }
+
+       public InputSource createSourceFromURL(String path) {
+               URL url = null;
+               try {
+                       url = new URL(path);
+                       URLConnection connexion = url.openConnection();
+                       connexion.setUseCaches(false);
+                       InputStream r = connexion.getInputStream();
+                       InputStreamReader inr = new InputStreamReader(r);
+                       return new InputSource(inr);
+               } catch (Exception e) {
+                       e.printStackTrace();
+               }
+               return new InputSource(new StringReader(""));
+       }
+
+       public InputSource resolveEntity(String publicId, String systemId) {
+               // System.out.println("[crade]");
+               if (systemId.endsWith("rnaml.dtd"))
+               {
+                       String resourceName = "/rnaml.dtd";
+                       URL url = ClassLoader.getSystemResource(resourceName);
+                       if (url!=null)
+                       {
+                               try {
+                                       InputStream stream = url.openStream();
+                                       if (stream != null)
+                                       {
+                                               return new InputSource(stream );
+                                       }
+                               } catch (IOException e) {
+                                       e.printStackTrace();
+                               }
+                       }
+               }
+               return new InputSource(new StringReader(""));
+       }
+
+       public void startElement(String uri, String localName, String qName,
+                       Attributes attributes) throws SAXException {
+               if (qName.equals("numbering-table")) {
+                       _inSequenceIDs = true;
+                       _buffer = new StringBuffer();
+               } else if (qName.equals("helix")) {
+                       _inHelix = true;
+                       _buffer = new StringBuffer();
+                       _helixID = attributes.getValue("id");
+               } else if (qName.equals("seq-data")) {
+                       _inSequence = true;
+                       _buffer = new StringBuffer();
+               } else if (qName.equals("length")) {
+                       _inLength = true;
+                       _buffer = new StringBuffer();
+               } else if (qName.equals("str-annotation")) {
+                       _inStrAnnotation = true;
+               } else if (qName.equals("base-pair")) {
+                       _inBP = true;
+               } else if (qName.equals("base-id-5p")) {
+                       if (_inBP || _inHelix) {
+                               _inBP5 = true;
+                       }
+               } else if (qName.equals("base-id-3p")) {
+                       if (_inBP || _inHelix) {
+                               _inBP3 = true;
+                       }
+               } else if (qName.equals("edge-5p")) {
+                       _inEdge5 = true;
+                       _buffer = new StringBuffer();
+               } else if (qName.equals("edge-3p")) {
+                       _inEdge3 = true;
+                       _buffer = new StringBuffer();
+               } else if (qName.equals("position")) {
+                       _inPosition = true;
+                       _buffer = new StringBuffer();
+               } else if (qName.equals("bond-orientation")) {
+                       _inBondOrientation = true;
+                       _buffer = new StringBuffer();
+               } else if (qName.equals("molecule")) {
+                       _inMolecule = true;
+                       String id = (attributes.getValue("id"));
+                       // System.err.println("Molecule#"+id);
+                       _molecules.put(id, new RNATmp());
+                       _currentModel = id;
+               } else {
+                       // We don't care too much about the rest ...
+               }
+       }
+
+       public void endElement(String uri, String localName, String qName)
+                       throws SAXException {
+               if (qName.equals("numbering-table")) {
+                       _inSequenceIDs = false;
+                       String content = _buffer.toString();
+                       content = content.trim();
+                       String[] tokens = content.split("\\s+");
+                       Vector<Integer> results = new Vector<Integer>();
+                       for (int i = 0; i < tokens.length; i++) {
+                               try {
+                                       results.add(new Integer(Integer.parseInt(tokens[i])));
+                               } catch (NumberFormatException e) {
+                                       e.printStackTrace();
+                               }
+                       }
+                       _molecules.get(_currentModel)._sequenceIDs = results;
+                       _buffer = null;
+               } else if (qName.equals("seq-data")) {
+                       _inSequence = false;
+                       String content = _buffer.toString();
+                       content = content.trim();
+                       String[] tokens = content.split("\\s+");
+                       ArrayList<String> results = new ArrayList<String>();
+                       for (int i = 0; i < tokens.length; i++) {
+                               for (int j = 0; j < tokens[i].length(); j++)
+                                       results.add("" + tokens[i].charAt(j));
+                       }
+                       // System.err.println("  Seq: "+results);
+                       _molecules.get(_currentModel)._sequence = results;
+                       _buffer = null;
+               } else if (qName.equals("bond-orientation")) {
+                       _inBondOrientation = false;
+                       String content = _buffer.toString();
+                       content = content.trim();
+                       _orientation = content;
+                       _buffer = null;
+               } else if (qName.equals("str-annotation")) {
+                       _inStrAnnotation = false;
+               } else if (qName.equals("base-pair")) {
+                       if (_inMolecule) {
+                               _inBP = false;
+                               BPTemp bp = new BPTemp(_id5, _id3, _edge5, _edge3, _orientation);
+                               _molecules.get(_currentModel)._structure.add(bp);
+                               // System.err.println("  "+bp);
+                       }
+               } else if (qName.equals("helix")) {
+                       _inHelix = false;
+                       if (_inMolecule) {
+                               HelixTemp h = new HelixTemp(_id5, _id3, _length, _helixID);
+                               _molecules.get(_currentModel)._helices.add(h);
+                       }
+               } else if (qName.equals("base-id-5p")) {
+                       _inBP5 = false;
+               } else if (qName.equals("base-id-3p")) {
+                       _inBP3 = false;
+               } else if (qName.equals("length")) {
+                       _inLength = false;
+                       String content = _buffer.toString();
+                       content = content.trim();
+                       _length = Integer.parseInt(content);
+                       _buffer = null;
+               } else if (qName.equals("position")) {
+                       String content = _buffer.toString();
+                       content = content.trim();
+                       int pos = Integer.parseInt(content);
+                       if (_inBP5) {
+                               _id5 = pos;
+                       }
+                       if (_inBP3) {
+                               _id3 = pos;
+                       }
+                       _buffer = null;
+               } else if (qName.equals("edge-5p")) {
+                       _inEdge5 = false;
+                       String content = _buffer.toString();
+                       content = content.trim();
+                       _edge5 = content;
+                       _buffer = null;
+               } else if (qName.equals("edge-3p")) {
+                       _inEdge3 = false;
+                       String content = _buffer.toString();
+                       content = content.trim();
+                       _edge3 = content;
+                       _buffer = null;
+               } else if (qName.equals("molecule")) {
+                       _inMolecule = false;
+               } else {
+                       // We don't care too much about the rest ...
+               }
+       }
+
+       public void characters(char[] ch, int start, int length)
+                       throws SAXException {
+               String lecture = new String(ch, start, length);
+               if (_buffer != null)
+                       _buffer.append(lecture);
+       }
+
+       public void startDocument() throws SAXException {
+       }
+
+       public void endDocument() throws SAXException {
+               postProcess();
+       }
+
+       // Discarding stacking interactions...
+       private void discardStacking() {
+               Vector<BPTemp> result = new Vector<BPTemp>();
+               for (int i = 0; i < _molecules.get(_currentModel)._structure.size(); i++) {
+                       BPTemp bp = _molecules.get(_currentModel)._structure.get(i);
+                       if (bp.orientation.equals("c") || bp.orientation.equals("t")) {
+                               result.add(bp);
+                       }
+               }
+               _molecules.get(_currentModel)._structure = result;
+       }
+
+       public static boolean isSelfCrossing(int[] str) {
+               Stack<Point> intervals = new Stack<Point>();
+               intervals.add(new Point(0, str.length - 1));
+               while (!intervals.empty()) {
+                       Point p = intervals.pop();
+                       if (p.x <= p.y) {
+                               if (str[p.x] == -1) {
+                                       intervals.push(new Point(p.x + 1, p.y));
+                               } else {
+                                       int i = p.x;
+                                       int j = p.y;
+                                       int k = str[i];
+                                       if ((k <= i) || (k > j)) {
+                                               return true;
+                                       } else {
+                                               intervals.push(new Point(i + 1, k - 1));
+                                               intervals.push(new Point(k + 1, j));
+                                       }
+                               }
+                       }
+               }
+               return false;
+       }
+
+       @SuppressWarnings("unused")
+       private void debugPrintArray(Object[] str) {
+               StringBuffer s = new StringBuffer("[");
+               for (int i = 0; i < str.length; i++) {
+                       if (i != 0) {
+                               s.append(",");
+                       }
+                       s.append(str[i]);
+
+               }
+               s.append("]");
+               System.out.println(s.toString());
+       }
+
+       /**
+        * Computes and returns a maximal planar subset of the current structure.
+        * 
+        * @param str
+        *            A sequence of base-pairing positions
+        * @return A sequence of non-crossing base-pairing positions
+        */
+
+       public static int[] planarize(int[] str) {
+               if (!isSelfCrossing(str)) {
+                       return str;
+               }
+
+               int length = str.length;
+
+               int[] result = new int[length];
+               for (int i = 0; i < result.length; i++) {
+                       result[i] = -1;
+               }
+
+               short[][] tab = new short[length][length];
+               short[][] backtrack = new short[length][length];
+               int theta = 3;
+
+               for (int i = 0; i < result.length; i++) {
+                       for (int j = i; j < Math.min(i + theta, result.length); j++) {
+                               tab[i][j] = 0;
+                               backtrack[i][j] = -1;
+                       }
+               }
+               for (int n = theta; n < length; n++) {
+                       for (int i = 0; i < length - n; i++) {
+                               int j = i + n;
+                               tab[i][j] = tab[i + 1][j];
+                               backtrack[i][j] = -1;
+                               int k = str[i];
+                               if ((k != -1) && (k <= j) && (i < k)) {
+                                       int tmp = 1;
+                                       if (i + 1 <= k - 1) {
+                                               tmp += tab[i + 1][k - 1];
+                                       }
+                                       if (k + 1 <= j) {
+                                               tmp += tab[k + 1][j];
+                                       }
+                                       if (tmp > tab[i][j]) {
+                                               tab[i][j] = (short) tmp;
+                                               backtrack[i][j] = (short) k;
+                                       }
+                               }
+                       }
+               }
+               Stack<Point> intervals = new Stack<Point>();
+               intervals.add(new Point(0, length - 1));
+               while (!intervals.empty()) {
+                       Point p = intervals.pop();
+                       if (p.x <= p.y) {
+                               if (backtrack[p.x][p.y] == -1) {
+                                       result[p.x] = -1;
+                                       intervals.push(new Point(p.x + 1, p.y));
+                               } else {
+                                       int i = p.x;
+                                       int j = p.y;
+                                       int k = backtrack[p.x][p.y];
+                                       result[i] = k;
+                                       result[k] = i;
+                                       intervals.push(new Point(i + 1, k - 1));
+                                       intervals.push(new Point(k + 1, j));
+                               }
+                       }
+               }
+               return result;
+       }
+
+       public static void planarize(ArrayList<ModeleBP> input,
+                       ArrayList<ModeleBP> planar, ArrayList<ModeleBP> others, int length) {
+               // System.err.println("Planarize: Length:"+length);
+               Hashtable<Integer, ArrayList<ModeleBP>> index2BPs = new Hashtable<Integer, ArrayList<ModeleBP>>();
+               for (ModeleBP msbp : input) {
+                       int i = msbp.getPartner5().getIndex();
+                       if (!index2BPs.containsKey(i)) {
+                               index2BPs.put(i, new ArrayList<ModeleBP>());
+                       }
+                       index2BPs.get(i).add(msbp);
+               }
+               // System.err.println(index2BPs);
+
+               short[][] tab = new short[length][length];
+               short[][] backtrack = new short[length][length];
+               int theta = 3;
+
+               for (int i = 0; i < length; i++) {
+                       for (int j = i; j < Math.min(i + theta, length); j++) {
+                               tab[i][j] = 0;
+                               backtrack[i][j] = -1;
+                       }
+               }
+               for (int n = theta; n < length; n++) {
+                       for (int i = 0; i < length - n; i++) {
+                               int j = i + n;
+                               tab[i][j] = tab[i + 1][j];
+                               backtrack[i][j] = -1;
+                               if (index2BPs.containsKey(i)) {
+                                       ArrayList<ModeleBP> vi = index2BPs.get(i);
+                                       // System.err.print(".");
+                                       for (int numBP = 0; numBP < vi.size(); numBP++) {
+                                               ModeleBP mb = vi.get(numBP);
+                                               int k = mb.getPartner3().getIndex();
+                                               if ((k != -1) && (k <= j) && (i < k)) {
+                                                       int tmp = 1;
+                                                       if (i + 1 <= k - 1) {
+                                                               tmp += tab[i + 1][k - 1];
+                                                       }
+                                                       if (k + 1 <= j) {
+                                                               tmp += tab[k + 1][j];
+                                                       }
+                                                       if (tmp > tab[i][j]) {
+                                                               tab[i][j] = (short) tmp;
+                                                               backtrack[i][j] = (short) numBP;
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+               }
+               // System.err.println("DP table: "+tab[0][length-1]);
+
+               // Backtracking
+               Stack<Point> intervals = new Stack<Point>();
+               intervals.add(new Point(0, length - 1));
+               while (!intervals.empty()) {
+                       Point p = intervals.pop();
+                       if (p.x <= p.y) {
+                               if (backtrack[p.x][p.y] == -1) {
+                                       intervals.push(new Point(p.x + 1, p.y));
+                               } else {
+                                       int i = p.x;
+                                       int j = p.y;
+                                       int nb = backtrack[p.x][p.y];
+                                       ModeleBP mb = index2BPs.get(i).get(nb);
+                                       int k = mb.getPartner3().getIndex();
+                                       planar.add(mb);
+                                       intervals.push(new Point(i + 1, k - 1));
+                                       intervals.push(new Point(k + 1, j));
+                               }
+                       }
+               }
+
+               // Remaining base pairs
+               for (int i : index2BPs.keySet()) {
+                       ArrayList<ModeleBP> vi = index2BPs.get(i);
+                       for (ModeleBP mb : vi) {
+                               if (!planar.contains(mb)) {
+                                       others.add(mb);
+                               }
+                       }
+               }
+       }
+
+       private void postProcess() {
+               for (RNATmp r : _molecules.values()) {
+                       // First, check if base numbers were specified
+                       if (r._sequenceIDs.size() == 0) {
+                               Vector<Integer> results = new Vector<Integer>();
+                               for (int i = 0; i < r._sequence.size(); i++) {
+                                       results.add(new Integer(i + 1));
+                               }
+                               r._sequenceIDs = results;
+                       }
+                       // System.err.println("IDs: "+_sequenceIDs);
+                       // System.err.println("Before remapping: "+_structure);
+
+                       // Then, build inverse mapping ID => index
+                       Hashtable<Integer, Integer> ID2Index = new Hashtable<Integer, Integer>();
+                       for (int i = 0; i < r._sequenceIDs.size(); i++) {
+                               ID2Index.put(r._sequenceIDs.get(i), i);
+                       }
+
+                       // Translate BP coordinates into indices
+                       for (BPTemp bp : r._structure) {
+                               bp.pos3 = bp.pos3 - 1;
+                               bp.pos5 = bp.pos5 - 1;
+                       }
+                       // System.err.println("After remapping: "+_structure);
+
+                       discardStacking();
+                       // System.err.println("  Discard stacking (length="+r._sequence.size()+") => "+r._structure);
+
+                       // Eliminate redundancy
+                       Hashtable<Integer, Hashtable<Integer,BPTemp>> index2BPs = new Hashtable<Integer, Hashtable<Integer,BPTemp>>();
+                       for (BPTemp msbp : r._structure) {
+                               int i = msbp.pos5;
+                               if (!index2BPs.containsKey(i)) {
+                                       index2BPs.put(i, new Hashtable<Integer,BPTemp>());
+                               }
+                               if (!index2BPs.get(i).contains(msbp.pos3)) {
+                                       index2BPs.get(i).put(msbp.pos3,msbp);
+                               }
+                       }
+                       
+                       // Adding helices...
+                       for (int i = 0; i < r._helices.size(); i++) {
+                               HelixTemp h = r._helices.get(i);
+                               for (int j = 0; j < h.length; j++) {
+                                       // System.err.println("Looking for residues: "+(h.pos5+j-1)+" and "+(h.pos3-j-1));
+                                       int a = (h.pos5 + j - 1);
+                                       int b = (h.pos3 - j - 1);
+                                       BPTemp bp = new BPTemp(a, (b), "+", "+", "c");
+                                       if (!index2BPs.containsKey(a)) {
+                                               index2BPs.put(a, new Hashtable<Integer,BPTemp>());
+                                       }
+                                       if (!index2BPs.get(a).contains(b)) {
+                                               index2BPs.get(a).put(b,bp);
+                                       }
+                               }
+                       }
+
+                       Vector<BPTemp> newStructure = new Vector<BPTemp>();
+                       for (int i : index2BPs.keySet()) {
+                               for (int j : index2BPs.get(i).keySet()) {
+                                       BPTemp bp = index2BPs.get(i).get(j);
+                                       newStructure.add(bp);
+                               }
+                       }
+                       r._structure = newStructure;
+
+                       // System.err.println("After Helices => "+_structure);
+
+
+                       // System.err.println("After Postprocess => "+_structure);
+               }
+       }
+
+       public ArrayList<RNATmp> getMolecules() {
+               return new ArrayList<RNATmp>(_molecules.values());
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/utils/TranslateFormatRNaseP.java b/src2/fr/orsay/lri/varna/utils/TranslateFormatRNaseP.java
new file mode 100644 (file)
index 0000000..7c999e5
--- /dev/null
@@ -0,0 +1,53 @@
+/**
+ * File written by Raphael Champeimont
+ * UMR 7238 Genomique des Microorganismes
+ */
+package fr.orsay.lri.varna.utils;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class TranslateFormatRNaseP {
+       public static void main(String[] args) throws Exception {
+               File templatesDir = new File(new File(System.getProperty("user.dir")), "templates");
+               File infile = new File(new File(templatesDir, "RNaseP_bact_a"), "a_bacterial_rnas.gb");
+               File outfile = new File(new File(templatesDir, "RNaseP_bact_a"), "alignment.fasta");
+               
+               BufferedReader inbuf = new BufferedReader(new FileReader(infile));
+               String line = inbuf.readLine();
+               String seqname;
+               List<String> seqnames = new ArrayList<String>();
+               List<String> sequences = new ArrayList<String>();
+               while (line != null) {
+                       if (line.length() != 0) {
+                               if (line.startsWith("LOCUS")) {
+                                       String parts[] = line.split("\\s+");
+                                       seqname = parts[1];
+                                       seqnames.add(seqname);
+                                       sequences.add("");
+                               }
+                               if (line.startsWith(" ")) {
+                                       String parts[] = line.split("\\s+");
+                                       for (int i=2; i<parts.length; i++) {
+                                               sequences.set(sequences.size()-1, sequences.get(sequences.size()-1) + parts[i]);
+                                       }
+                               }
+                       }
+                       line = inbuf.readLine();
+               }
+               inbuf.close();
+               
+               BufferedWriter outbuf = new BufferedWriter(new FileWriter(outfile));
+               for (int i=2; i<seqnames.size(); i++) {
+                       outbuf.write(">" + seqnames.get(i) + "\n");
+                       outbuf.write(sequences.get(i) + "\n");
+               }
+               outbuf.close();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/utils/VARNASessionParser.java b/src2/fr/orsay/lri/varna/utils/VARNASessionParser.java
new file mode 100644 (file)
index 0000000..7eb510a
--- /dev/null
@@ -0,0 +1,481 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Universit� Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.utils;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Point;
+import java.awt.geom.Point2D;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Stack;
+import java.util.TreeSet;
+import java.util.Vector;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation.ChemProbAnnotationType;
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation.AnchorType;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBP.Edge;
+import fr.orsay.lri.varna.models.rna.ModeleBP.Stericity;
+import fr.orsay.lri.varna.models.rna.ModeleBPStyle;
+import fr.orsay.lri.varna.models.rna.ModeleBackbone;
+import fr.orsay.lri.varna.models.rna.ModeleBackboneElement;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleBasesComparison;
+import fr.orsay.lri.varna.models.rna.ModelBaseStyle;
+import fr.orsay.lri.varna.models.rna.RNA;
+import fr.orsay.lri.varna.models.rna.VARNAPoint;
+
+public class VARNASessionParser extends DefaultHandler {
+
+       StringBuffer _buffer = null;
+       ModeleBaseNucleotide mbn = null;
+       ModeleBasesComparison mbc = null;
+       ModeleBP mbp = null;
+       ModeleBPStyle mbps = null;
+       ModelBaseStyle msb = null;
+       TextAnnotation ta = null;
+       ModeleBackbone backbone = null;
+       HighlightRegionAnnotation hra = null;
+       RNA rna = null;
+       Font f = null;
+       VARNAConfig config = null;
+       
+    public VARNASessionParser() {
+               super();
+       }
+
+       public InputSource createSourceFromURL(String path)
+       {
+               URL url = null;
+               try {
+                       url = new URL(path);
+                       URLConnection connexion = url.openConnection();
+                       connexion.setUseCaches(false);
+                       InputStream r = connexion.getInputStream();
+                       InputStreamReader inr = new InputStreamReader(r);
+                       return new InputSource(inr);
+               }
+               catch(Exception e)
+               {
+                       e.printStackTrace();
+               }
+               return new InputSource(new StringReader(""));
+       }
+       
+       public InputSource resolveEntity(String publicId, String systemId) {
+                       return new InputSource(new StringReader(""));
+       }
+       
+
+       private TreeSet<String> _context = new TreeSet<String>();
+       
+       private void addToContext(String s)
+       {
+               _context.add(s);
+       }
+
+       private void removeFromContext(String s)
+       {
+               _context.remove(s);
+       }
+
+       private boolean contextContains(String s)
+       {
+               return _context.contains(s);
+       }
+
+       public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
+               if (qName.equals(VARNAPanel.XML_ELEMENT_NAME)) {
+               }
+               else if (qName.equals(VARNAConfig.XML_ELEMENT_NAME)){
+                       config = new VARNAConfig();
+                       config.loadFromXMLAttributes(attributes);
+               }
+               else if (qName.equals(RNA.XML_ELEMENT_NAME)){
+                       rna = new RNA();
+                       int mode = Integer.parseInt(attributes.getValue(RNA.XML_VAR_DRAWN_MODE_NAME));
+                       rna.setDrawMode(mode);
+               }
+               else if (qName.equals(ModeleBackbone.XML_ELEMENT_NAME)){
+                       backbone = new ModeleBackbone();
+                       rna.setBackbone(backbone);
+               }
+               else if (qName.equals(ModeleBackboneElement.XML_ELEMENT_NAME)){
+                       if (backbone!=null){
+                               int index = Integer.parseInt(attributes.getValue(ModeleBackboneElement.XML_VAR_INDEX_NAME));
+                               ModeleBackboneElement.BackboneType type = ModeleBackboneElement.BackboneType.getType(                   
+                                               (attributes.getValue(ModeleBackboneElement.XML_VAR_TYPE_NAME)));
+                               Color c = null;
+                               if (type == ModeleBackboneElement.BackboneType.CUSTOM_COLOR)
+                               {
+                                       c = Color.decode(attributes.getValue(TextAnnotation.XML_VAR_COLOR_NAME));
+                                       backbone.addElement(new ModeleBackboneElement(index, c));
+                               }
+                               else
+                               {
+                                       backbone.addElement(new ModeleBackboneElement(index, type));                                    
+                               }
+                       }
+               }
+               else if (qName.equals(ModeleBackbone.XML_ELEMENT_NAME)){
+                       backbone = new ModeleBackbone();
+               }
+               else if (qName.equals(ModeleBaseNucleotide.XML_ELEMENT_NAME)){
+                       if (rna!=null){
+                               mbn = new ModeleBaseNucleotide(rna.getSize());
+                               if (mbn.getIndex()!=Integer.parseInt(attributes.getValue(ModeleBase.XML_VAR_INDEX_NAME)))
+                                       throw new SAXException("Index mismatch for Base");
+                               mbn.setBaseNumber(Integer.parseInt(attributes.getValue(ModeleBase.XML_VAR_NUMBER_NAME)));
+                               mbn.setLabel(attributes.getValue(ModeleBase.XML_VAR_LABEL_NAME));
+                               mbn.setColorie(Boolean.parseBoolean(attributes.getValue(ModeleBase.XML_VAR_CUSTOM_DRAWN_NAME)));
+                               mbn.setValue(Double.parseDouble(attributes.getValue(ModeleBase.XML_VAR_VALUE_NAME)));
+                               rna.addBase(mbn);
+                       }
+               }
+               else if (qName.equals(XMLUtils.XML_FONT_ELEMENT_NAME)){
+                       f = XMLUtils.getFont(qName,attributes);
+                       if (contextContains(TextAnnotation.XML_ELEMENT_NAME))
+                       {
+                               ta.setFont(f);
+                               f=null;
+                       }
+                       else if (contextContains(VARNAConfig.XML_ELEMENT_NAME))
+                       {
+                               String role = attributes.getValue(XMLUtils.XML_ROLE_NAME);
+                               if (role.equals(VARNAConfig.XML_VAR_TITLE_FONT))
+                               {
+                                       config._titleFont = XMLUtils.getFont(qName, attributes);
+                               }
+                               else if (role.equals(VARNAConfig.XML_VAR_NUMBERS_FONT))
+                               {
+                                       config._numbersFont = XMLUtils.getFont(qName, attributes);
+                               }
+                               else if (role.equals(VARNAConfig.XML_VAR_FONT_BASES))
+                               {
+                                       config._fontBasesGeneral = XMLUtils.getFont(qName, attributes);
+                               }
+                       }
+               }
+               else if (qName.equals(ModeleBaseNucleotide.XML_VAR_CONTENT_NAME)){
+                       _buffer = new StringBuffer();
+               }
+               else if (qName.equals(ModeleBasesComparison.XML_VAR_FIRST_CONTENT_NAME)){
+                       _buffer = new StringBuffer();
+               }
+               else if (qName.equals(ModeleBasesComparison.XML_VAR_SECOND_CONTENT_NAME)){
+                       _buffer = new StringBuffer();
+               }
+               else if (qName.equals(ModeleBasesComparison.XML_ELEMENT_NAME)){
+                       if (rna!=null){
+                               mbc = new ModeleBasesComparison(rna.getSize());
+                               if (mbc.getIndex()!=Integer.parseInt(attributes.getValue(ModeleBase.XML_VAR_INDEX_NAME)))
+                                       throw new SAXException("Index mismatch for Base");
+                               mbc.setBaseNumber(Integer.parseInt(attributes.getValue(ModeleBase.XML_VAR_NUMBER_NAME)));
+                               mbc.setLabel(attributes.getValue(ModeleBase.XML_VAR_LABEL_NAME));
+                               mbc.set_appartenance(Integer.parseInt(attributes.getValue(ModeleBasesComparison.XML_VAR_MEMBERSHIP_NAME)));
+                               mbc.setColorie(Boolean.parseBoolean(attributes.getValue(ModeleBase.XML_VAR_CUSTOM_DRAWN_NAME)));
+                               mbc.setValue(Double.parseDouble(attributes.getValue(ModeleBase.XML_VAR_VALUE_NAME)));
+                               rna.addBase(mbc);
+                       }
+               }
+               else if (qName.equals(RNA.XML_VAR_NAME_NAME))
+               {
+                       if (rna!=null){
+                               _buffer = new StringBuffer();
+                       }                       
+               }
+               else if (qName.equals(ModeleBP.XML_ELEMENT_NAME))
+               {
+                       Edge e5 = Edge.valueOf(attributes.getValue(ModeleBP.XML_VAR_EDGE5_NAME));
+                       Edge e3 = Edge.valueOf(attributes.getValue(ModeleBP.XML_VAR_EDGE3_NAME));
+                       Stericity s = Stericity.valueOf(attributes.getValue(ModeleBP.XML_VAR_STERICITY_NAME));
+                       int i5 = Integer.parseInt(attributes.getValue(ModeleBP.XML_VAR_PARTNER5_NAME)); 
+                       int i3 = Integer.parseInt(attributes.getValue(ModeleBP.XML_VAR_PARTNER3_NAME)); 
+                       boolean inSecStr = Boolean.parseBoolean(attributes.getValue(ModeleBP.XML_VAR_SEC_STR_NAME)); 
+                       mbp = new ModeleBP(rna.getBaseAt(i5),rna.getBaseAt(i3),e5,e3,s);
+                       if (inSecStr)
+                               rna.addBP(i5,i3,mbp);
+                       else
+                               rna.addBPAux(i5,i3,mbp);
+               }
+               else if (qName.equals(ChemProbAnnotation.XML_ELEMENT_NAME))
+               {
+                       int i5 = Integer.parseInt(attributes.getValue(ChemProbAnnotation.XML_VAR_INDEX5_NAME)); 
+                       int i3 = Integer.parseInt(attributes.getValue(ChemProbAnnotation.XML_VAR_INDEX3_NAME));
+                       ChemProbAnnotation cpa = new ChemProbAnnotation(rna.getBaseAt(i5),rna.getBaseAt(i3));
+                       cpa.setColor(Color.decode(attributes.getValue(ChemProbAnnotation.XML_VAR_COLOR_NAME)));
+                       cpa.setIntensity(Double.parseDouble(attributes.getValue(ChemProbAnnotation.XML_VAR_INTENSITY_NAME)));
+                       cpa.setType(ChemProbAnnotationType.valueOf(attributes.getValue(ChemProbAnnotation.XML_VAR_TYPE_NAME)));
+                       cpa.setOut(Boolean.parseBoolean(attributes.getValue(ChemProbAnnotation.XML_VAR_OUTWARD_NAME)));
+                       rna.addChemProbAnnotation(cpa);
+               }
+               else if (qName.equals(TextAnnotation.XML_VAR_TEXT_NAME)){
+                       _buffer = new StringBuffer();
+               }
+               else if (qName.equals(VARNAConfig.XML_VAR_TITLE)){
+                       _buffer = new StringBuffer();
+               }
+               else if (qName.equals(VARNAConfig.XML_VAR_CM_CAPTION)){
+                       _buffer = new StringBuffer();
+               }
+               else if (qName.equals(TextAnnotation.XML_ELEMENT_NAME))
+               {
+                       AnchorType t = AnchorType.valueOf(attributes.getValue(TextAnnotation.XML_VAR_TYPE_NAME));
+                       ta = new TextAnnotation("");
+                       ta.setColor(Color.decode(attributes.getValue(TextAnnotation.XML_VAR_COLOR_NAME)));
+                       ta.setAngleInDegres(Double.parseDouble(attributes.getValue(TextAnnotation.XML_VAR_ANGLE_NAME)));
+                       ta.setType(t);
+               }
+               else if (qName.equals(HighlightRegionAnnotation.XML_ELEMENT_NAME))
+               {
+                       hra = new HighlightRegionAnnotation();
+                       rna.addHighlightRegion(hra);
+                       hra.setOutlineColor(Color.decode(attributes.getValue(HighlightRegionAnnotation.XML_VAR_OUTLINE_NAME)));
+                       hra.setFillColor(Color.decode(attributes.getValue(HighlightRegionAnnotation.XML_VAR_FILL_NAME)));
+                       hra.setRadius(Double.parseDouble(attributes.getValue(HighlightRegionAnnotation.XML_VAR_RADIUS_NAME)));
+               }
+               else if (qName.equals(XMLUtils.XML_BASELIST_ELEMENT_NAME))
+               {
+                       _buffer = new StringBuffer();                   
+               }
+               else if (qName.equals(VARNAPoint.XML_ELEMENT_NAME))
+               {
+                       Point2D.Double vp = new Point2D.Double();
+                       vp.x = Double.parseDouble(attributes.getValue(VARNAPoint.XML_VAR_X_NAME));
+                       vp.y = Double.parseDouble(attributes.getValue(VARNAPoint.XML_VAR_Y_NAME));
+                       String role = attributes.getValue(VARNAPoint.XML_VAR_ROLE_NAME);
+                       if (contextContains(ModeleBaseNucleotide.XML_ELEMENT_NAME))
+                       {
+                               if (role != null)
+                               {
+                                       if (role.equals(ModeleBase.XML_VAR_POSITION_NAME))
+                                       {
+                                               if (mbn!=null)
+                                               {  mbn.setCoords(vp);  }
+                                               else throw new SAXException("No Base model for this position Point");
+                                       }
+                                       else if (role.equals(ModeleBase.XML_VAR_CENTER_NAME))
+                                       {
+                                               if (mbn!=null)
+                                               {  mbn.setCenter(vp);  }
+                                               else throw new SAXException("No Base model for this center Point");
+                                       }
+                                       
+                               }                               
+                       }
+                       if (contextContains(ModeleBasesComparison.XML_ELEMENT_NAME))
+                       {
+                               if (role != null)
+                               {
+                                       if (role.equals(ModeleBase.XML_VAR_POSITION_NAME))
+                                       {
+                                               if (mbc!=null)
+                                               {  mbc.setCoords(vp);  }                                        
+                                               else throw new SAXException("No Base model for this position Point");
+                                       }
+                                       else if (role.equals(ModeleBase.XML_VAR_CENTER_NAME))
+                                       {
+                                               if (mbc!=null)
+                                               {  mbc.setCenter(vp);  }
+                                               else throw new SAXException("No Base model for this center Point");
+                                       }
+                               }
+                       }
+                       if (contextContains(TextAnnotation.XML_ELEMENT_NAME))
+                       {
+                               if (ta!=null)
+                               ta.setAncrage(vp.x,vp.y);
+                               else throw new SAXException("No TextAnnotation model for this Point");
+                       }
+               }
+               else if (qName.equals(ModelBaseStyle.XML_ELEMENT_NAME))
+               {
+                       msb = new ModelBaseStyle();
+                       msb.setBaseOutlineColor(Color.decode(attributes.getValue(ModelBaseStyle.XML_VAR_OUTLINE_NAME)));
+                       msb.setBaseInnerColor(Color.decode(attributes.getValue(ModelBaseStyle.XML_VAR_INNER_NAME)));
+                       msb.setBaseNameColor(Color.decode(attributes.getValue(ModelBaseStyle.XML_VAR_NAME_NAME)));
+                       msb.setBaseNumberColor(Color.decode(attributes.getValue(ModelBaseStyle.XML_VAR_NUMBER_NAME)));
+                       if (mbn!=null)
+                       {  mbn.setStyleBase(msb);  }
+                       else if (mbc!=null)
+                       {  mbc.setStyleBase(msb);  }
+                       msb = null;
+               }
+               else if (qName.equals(ModeleBPStyle.XML_ELEMENT_NAME))
+               {
+                       mbps = new ModeleBPStyle();
+                       boolean customColor = Boolean.parseBoolean(attributes.getValue(ModeleBPStyle.XML_VAR_CUSTOM_STYLED_NAME));
+                       if (customColor)
+                               mbps.setCustomColor(Color.decode(attributes.getValue(ModeleBPStyle.XML_VAR_COLOR_NAME)));
+                       mbps.setThickness(Double.parseDouble(attributes.getValue(ModeleBPStyle.XML_VAR_THICKNESS_NAME)));
+                       mbps.setBent(Double.parseDouble(attributes.getValue(ModeleBPStyle.XML_VAR_BENT_NAME)));
+                       if (mbp!=null)
+                       {  mbp.setStyle(mbps);  }
+                       mbps = null;
+               }
+               addToContext(qName);                                                                                                                                                       
+       }
+
+       
+       
+       public void endElement(String uri, String localName, String qName)
+                       throws SAXException {
+               if (qName.equals(ModeleBaseNucleotide.XML_VAR_CONTENT_NAME)){
+                       if (_buffer==null){
+                               throw new SAXException("Invalid location for tag "+ModeleBaseNucleotide.XML_VAR_CONTENT_NAME);
+                       }
+                       if (mbn==null){
+                               throw new SAXException("Invalid location for tag "+ModeleBaseNucleotide.XML_VAR_CONTENT_NAME);
+                       }
+                       String val = _buffer.toString();
+                       mbn.setContent(val);
+               }
+               else if (qName.equals(ModeleBasesComparison.XML_VAR_FIRST_CONTENT_NAME)){
+                       if (_buffer==null){
+                               throw new SAXException("Invalid location for tag "+ModeleBaseNucleotide.XML_VAR_CONTENT_NAME);
+                       }
+                       if (mbc==null){
+                               throw new SAXException("Invalid location for tag "+ModeleBaseNucleotide.XML_VAR_CONTENT_NAME);
+                       }
+                       String val = _buffer.toString();
+                       mbc.setBase1(val.trim().charAt(0));
+               }
+               else if (qName.equals(ModeleBasesComparison.XML_VAR_SECOND_CONTENT_NAME)){
+                       if (_buffer==null){
+                               throw new SAXException("Invalid location for tag "+ModeleBaseNucleotide.XML_VAR_CONTENT_NAME);
+                       }
+                       if (mbc==null){
+                               throw new SAXException("Invalid location for tag "+ModeleBaseNucleotide.XML_VAR_CONTENT_NAME);
+                       }
+                       String val = _buffer.toString();
+                       mbc.setBase2(val.trim().charAt(0));
+               }
+               else if (qName.equals(ModeleBaseNucleotide.XML_ELEMENT_NAME)){
+                       mbn = null;
+               }
+               else if (qName.equals(ModeleBP.XML_ELEMENT_NAME))
+               {
+                       mbp = null;
+               }
+               else if (qName.equals(HighlightRegionAnnotation.XML_ELEMENT_NAME))
+               {
+                       hra = null;
+               }
+               else if (qName.equals(TextAnnotation.XML_VAR_TEXT_NAME))
+               {
+                       String text = _buffer.toString();
+                       ta.setText(text);
+                       _buffer = null;                 
+               }
+               else if (qName.equals(RNA.XML_VAR_NAME_NAME))
+               {
+                       if (rna!=null){
+                               rna.setName(_buffer.toString());
+                               _buffer = null;
+                       }                       
+               }
+               else if (qName.equals(VARNAConfig.XML_VAR_CM_CAPTION)){
+                       config._colorMapCaption = _buffer.toString();
+                       _buffer = null;                 
+               }
+
+               else if (qName.equals(TextAnnotation.XML_ELEMENT_NAME))
+               {
+                       rna.addAnnotation(ta);
+                       ta = null;
+               }
+               else if (qName.equals(XMLUtils.XML_BASELIST_ELEMENT_NAME))
+               {
+                       String result = _buffer.toString();
+                       ArrayList<ModeleBase> al = XMLUtils.toModeleBaseArray(result, rna);
+                       if (contextContains(TextAnnotation.XML_ELEMENT_NAME))
+                       {
+                               switch(ta.getType())
+                               {
+                               case POSITION:
+                                       break;
+                               case BASE:
+                                       ta.setAncrage(al.get(0));
+                                       break;
+                               case HELIX:
+                               case LOOP:
+                                       try {
+                                               ta.setAncrage(al, ta.getType());
+                                       } catch (Exception e) {
+                                               // TODO Auto-generated catch block
+                                               e.printStackTrace();
+                                       }
+                                       break;
+                               default:
+                               }
+                       }
+                       if (contextContains(HighlightRegionAnnotation.XML_ELEMENT_NAME))
+                       {
+                         hra.setBases(al);
+                       }
+                       _buffer = null;
+               }
+
+               removeFromContext(qName);                                                                                                                                                       
+       }
+
+       public void characters(char[] ch, int start, int length)
+                       throws SAXException {
+               String lecture = new String(ch, start, length);
+               if (_buffer != null)
+                       _buffer.append(lecture);
+       }
+
+       public void startDocument() throws SAXException {
+       }
+
+       public void endDocument() throws SAXException {
+       }
+       
+       public RNA getRNA()
+       {
+               return rna;
+       }
+
+       public VARNAConfig getVARNAConfig()
+       {
+               return config;
+       }
+
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/utils/XMLUtils.java b/src2/fr/orsay/lri/varna/utils/XMLUtils.java
new file mode 100644 (file)
index 0000000..e3acefc
--- /dev/null
@@ -0,0 +1,148 @@
+package fr.orsay.lri.varna.utils;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.util.ArrayList;
+import java.util.Formatter;
+
+import javax.xml.transform.sax.TransformerHandler;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class XMLUtils {
+       public static String toHTMLNotation(Color c)
+       {
+               Formatter f = new Formatter();
+               f.format("#%02X%02X%02X", c.getRed(),c.getGreen(),c.getBlue());
+               return f.toString();
+       }
+
+       public static void toXML(TransformerHandler hd, Font f) throws SAXException
+       {
+               toXML(hd, f,"");
+       }
+       
+
+       public static String XML_BASELIST_ELEMENT_NAME = "baselist";
+       public static String XML_FONT_ELEMENT_NAME = "font";
+       public static String XML_ROLE_NAME = "role";
+       public static String XML_NAME_NAME = "name";
+       public static String XML_FAMILY_NAME = "family";
+       public static String XML_STYLE_NAME = "style";
+       public static String XML_SIZE_NAME = "size";
+       
+       public static void toXML(TransformerHandler hd, Font f, String role) throws SAXException
+       {
+               AttributesImpl atts = new AttributesImpl();
+               if (!role.equals(""))
+                 atts.addAttribute("","",XML_ROLE_NAME,"CDATA",""+role);
+               atts.addAttribute("","",XML_NAME_NAME,"CDATA",""+f.getName());
+               //atts.addAttribute("","",XML_FAMILY_NAME,"CDATA",""+f.getFamily());
+               atts.addAttribute("","",XML_STYLE_NAME,"CDATA",""+f.getStyle());
+               atts.addAttribute("","",XML_SIZE_NAME,"CDATA",""+f.getSize2D());
+               hd.startElement("","",XML_FONT_ELEMENT_NAME,atts);
+               hd.endElement("","",XML_FONT_ELEMENT_NAME);
+       }
+
+       public static Font getFont(String qName, Attributes attributes)
+       {
+               if (qName.equals(XMLUtils.XML_FONT_ELEMENT_NAME)){
+                       int style = Integer.parseInt(attributes.getValue(XMLUtils.XML_STYLE_NAME));                     
+                       String name = (attributes.getValue(XMLUtils.XML_NAME_NAME));                    
+                       double size = Double.parseDouble(attributes.getValue(XMLUtils.XML_SIZE_NAME));
+                       Font f = new Font(name, style, (int)size);
+                       return f.deriveFont((float)size);
+               }
+               return null;
+       }
+       
+
+       public static void toXML(TransformerHandler hd, ModeleBase mb) throws SAXException
+       {
+               ArrayList<ModeleBase> m = new ArrayList<ModeleBase>();
+               m.add(mb);
+               toXML(hd, m);
+       }
+
+
+       public static void toXML(TransformerHandler hd, ArrayList<ModeleBase> m) throws SAXException
+       {               
+               AttributesImpl atts = new AttributesImpl();
+               String result = "";
+               for (ModeleBase mb: m)
+               {
+                       if (!result.equals(""))
+                               result+= ",";
+                       result += mb.getIndex();
+                                       
+               }
+               hd.startElement("","",XML_BASELIST_ELEMENT_NAME,atts);
+               exportCDATAString(hd, result);
+               hd.endElement("","",XML_BASELIST_ELEMENT_NAME);
+       }
+
+       public static ArrayList<ModeleBase> toModeleBaseArray(String baselist, RNA rna)
+       {
+               ArrayList<ModeleBase> result = new ArrayList<ModeleBase>();
+               String[] data = baselist.trim().split(",");
+               for(int i=0;i<data.length;i++)
+               {
+                       int index = Integer.parseInt(data[i]);
+                       result.add(rna.getBaseAt(index));
+               }
+                       
+               return result;
+       }
+       
+       public static void exportCDATAElem(TransformerHandler hd,String elem, String s) throws SAXException
+       {
+               char[] t = s.toCharArray();
+               AttributesImpl atts = new AttributesImpl();
+               hd.startElement("","",elem,atts);
+               hd.startCDATA();
+               hd.characters(t, 0, t.length);
+               hd.endCDATA();
+               hd.endElement("","",elem);
+       }
+       
+       public static void exportCDATAString(TransformerHandler hd, String s) throws SAXException
+       {
+               char[] t = s.toCharArray();
+               hd.startCDATA();
+               hd.characters(t, 0, t.length);
+               hd.endCDATA();
+       }
+       public static boolean getBoolean(Attributes attributes, String attName, boolean defVal)
+       {
+               String val = attributes.getValue(attName);
+               if (val!=null)
+               {
+                       return Boolean.parseBoolean(val);
+               }
+               return defVal;
+       }
+       public static int getInt(Attributes attributes, String attName, int defVal)
+       {
+               String val = attributes.getValue(attName);
+               if (val!=null)
+               {
+                       return Integer.parseInt(val);
+               }
+               return defVal;
+       }
+       public static double getDouble(Attributes attributes, String attName, double defVal)
+       {
+               String val = attributes.getValue(attName);
+               if (val!=null)
+               {
+                       return Double.parseDouble(val);
+               }
+               return defVal;
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/views/Imprimer.java b/src2/fr/orsay/lri/varna/views/Imprimer.java
new file mode 100644 (file)
index 0000000..1d459e2
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */ 
+package fr.orsay.lri.varna.views;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.print.PageFormat;
+import java.awt.print.Printable;
+import java.awt.print.PrinterJob;
+
+public class Imprimer implements Printable {
+       private String phrase;
+
+       public Imprimer(String phrase) {
+               this.phrase = phrase;
+       }
+
+       public int print(Graphics g, PageFormat pf, int indexPage) {
+               if (indexPage > 0)
+                       return NO_SUCH_PAGE;
+               Graphics2D g2 = (Graphics2D) g;
+               g2.setPaint(Color.blue);
+               g2.setFont(new Font("Serif", Font.PLAIN, 64));
+               g2.drawString(phrase, 96, 144);
+               return PAGE_EXISTS;
+       }
+
+       public static void main(String args[]) {
+               PrinterJob tache = PrinterJob.getPrinterJob();
+               tache.setPrintable(new Imprimer(
+                               "Ceci est un teste d'impression en java!"));
+
+               // printDialog affiche la fenetre de sélection de l’imprimante,
+               // etc...
+
+               // il retourne true si on clique sur "Ok", false si on clique sur
+               // "Annuler"
+               //System.out.println(PrinterJob.getPrinterJob());
+               if (!tache.printDialog())
+                       return;
+               try {
+                       tache.print();
+               } catch (Exception e) {
+                       System.err.println("impossible d'imprimer");
+               }
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/views/PrintTest.java b/src2/fr/orsay/lri/varna/views/PrintTest.java
new file mode 100644 (file)
index 0000000..99bda20
--- /dev/null
@@ -0,0 +1,194 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.BorderLayout;
+import java.awt.Container;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Shape;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.font.FontRenderContext;
+import java.awt.font.TextLayout;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Line2D;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.awt.print.PageFormat;
+import java.awt.print.Printable;
+import java.awt.print.PrinterException;
+import java.awt.print.PrinterJob;
+
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+
+/**
+ * This program demonstrates how to print 2D graphics
+ */
+public class PrintTest {
+       @SuppressWarnings("deprecation")
+       public static void main(String[] args) {
+               JFrame frame = new PrintTestFrame();
+               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+               frame.show();
+       }
+}
+
+/**
+ * This frame shows a panel with 2D graphics and buttons to print the graphics
+ * and to set up the page format.
+ */
+
+@SuppressWarnings("serial")
+class PrintTestFrame extends JFrame {
+       public PrintTestFrame() {
+               setTitle("PrintTest");
+               setSize(WIDTH, HEIGHT);
+
+               Container contentPane = getContentPane();
+               canvas = new PrintPanel();
+               contentPane.add(canvas, BorderLayout.CENTER);
+
+               attributes = new HashPrintRequestAttributeSet();
+
+               JPanel buttonPanel = new JPanel();
+               JButton printButton = new JButton("Print");
+               buttonPanel.add(printButton);
+               printButton.addActionListener(new ActionListener() {
+
+                       public void actionPerformed(ActionEvent event) {
+                               try {
+                                       PrinterJob job = PrinterJob.getPrinterJob();
+                                       job.setPrintable(canvas);
+                                       if (job.printDialog(attributes)) {
+                                               job.print(attributes);
+                                       }
+                               } catch (PrinterException exception) {
+                                       JOptionPane.showMessageDialog(PrintTestFrame.this,
+                                                       exception);
+                               }
+                       }
+               });
+
+               JButton pageSetupButton = new JButton("Page setup");
+               buttonPanel.add(pageSetupButton);
+               pageSetupButton.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent event) {
+                               PrinterJob job = PrinterJob.getPrinterJob();
+                               job.pageDialog(attributes);
+                       }
+               });
+
+               contentPane.add(buttonPanel, BorderLayout.NORTH);
+       }
+
+       private PrintPanel canvas;
+
+       private PrintRequestAttributeSet attributes;
+
+       private static final int WIDTH = 300;
+
+       private static final int HEIGHT = 300;
+}
+
+/**
+ * This panel generates a 2D graphics image for screen display and printing.
+ */
+
+@SuppressWarnings("serial")
+class PrintPanel extends JPanel implements Printable {
+
+       public void paintComponent(Graphics g) {
+               super.paintComponent(g);
+               Graphics2D g2 = (Graphics2D) g;
+               drawPage(g2);
+       }
+
+       public int print(Graphics g, PageFormat pf, int page)
+                       throws PrinterException {
+               if (page >= 1)
+                       return Printable.NO_SUCH_PAGE;
+               Graphics2D g2 = (Graphics2D) g;
+               g2.translate(pf.getImageableX(), pf.getImageableY());
+               g2.draw(new Rectangle2D.Double(0, 0, pf.getImageableWidth(), pf
+                               .getImageableHeight()));
+
+               drawPage(g2);
+               return Printable.PAGE_EXISTS;
+       }
+
+       /**
+        * This method draws the page both on the screen and the printer graphics
+        * context.
+        * 
+        * @param g2
+        *            the graphics context
+        */
+       public void drawPage(Graphics2D g2) {
+               FontRenderContext context = g2.getFontRenderContext();
+               Font f = new Font("Serif", Font.PLAIN, 72);
+
+               boolean drawOutline = true;
+               /**
+                * textLayout is not implemented 
+                * 
+                * @j2sNative 
+                * 
+                *            drawOutline = false;
+                */
+               {}
+               if (drawOutline) {
+                       // BH: SwingJS HTML5 would have to use a different method for this
+
+                       GeneralPath clipShape = new GeneralPath();
+
+                       TextLayout layout = new TextLayout("Hello", f, context);
+                       AffineTransform transform = AffineTransform.getTranslateInstance(0, 72);
+                       Shape outline = layout.getOutline(transform);
+                       clipShape.append(outline, false);
+
+                       layout = new TextLayout("World", f, context);
+                       transform = AffineTransform.getTranslateInstance(0, 144);
+                       outline = layout.getOutline(transform);
+                       clipShape.append(outline, false);
+
+                       g2.draw(clipShape);
+                       g2.clip(clipShape);
+               } else {
+                       g2.setFont(f);
+                       g2.drawString("Hello", 0, 72);
+                       g2.drawString("World", 0, 144);
+               }
+
+               final int NLINES = 50;
+               Point2D p = new Point2D.Double(0, 0);
+               for (int i = 0; i < NLINES; i++) {
+                       double x = (2 * getWidth() * i) / NLINES;
+                       double y = (2 * getHeight() * (NLINES - 1 - i)) / NLINES;
+                       Point2D q = new Point2D.Double(x, y);
+                       g2.draw(new Line2D.Double(p, q));
+               }
+       }
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/views/VueAboutPanel.java b/src2/fr/orsay/lri/varna/views/VueAboutPanel.java
new file mode 100644 (file)
index 0000000..fffbc80
--- /dev/null
@@ -0,0 +1,210 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.ArrayList;
+
+import javax.swing.BorderFactory;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.Timer;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.models.VARNAConfig;
+
+/**
+ * BH j2s SwingJS replaces thread with simple javax.swing.Timer
+ * 
+ */
+public class VueAboutPanel extends JPanel {
+
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 4525998278180950602L;
+
+       private AboutAnimator _anim;
+       private JPanel _textPanel;
+       private JTextArea _textArea;
+
+       public VueAboutPanel() {
+               init();
+       }
+
+       private void init() {
+               try {
+                       setBorder(BorderFactory.createEtchedBorder());
+                       setLayout(new BorderLayout());
+                       setBackground(Color.WHITE);
+
+                       String message = "VARNA "
+                                       + VARNAConfig.MAJOR_VERSION
+                                       + "."
+                                       + VARNAConfig.MINOR_VERSION
+                                       + "\n"
+                                       + "\n"
+                                       + "Created by: Kevin Darty, Alain Denise and Yann Ponty\n"
+                                       + "Contact: ponty@lri.fr\n"
+                                       + "\n"
+                                       + "VARNA is freely distributed under the terms of the GNU GPL 3.0 license.\n"
+                                       + "\n"
+                                       + "Supported by the BRASERO project (ANR-06-BLAN-0045)\n";
+
+                       _textArea = new JTextArea();
+                       _textArea.setText(message);
+                       _textArea.setEditable(false);
+
+                       _textPanel = new JPanel();
+                       _textPanel.setBackground(Color.WHITE);
+                       _textPanel.setLayout(new BorderLayout());
+                       _textPanel.setBorder(BorderFactory.createMatteBorder(0, 15, 0, 15,
+                                       getBackground()));
+                       _textPanel.add(_textArea);
+
+                       VARNAPanel vp = new VARNAPanel("GGGGAAAACCCC", "((((....))))");
+                       vp.setModifiable(false);
+                       vp.setPreferredSize(new Dimension(100, 100));
+                       // vp.setBorder(BorderFactory.createLineBorder(Color.gray));
+
+                       _anim = new AboutAnimator(vp);
+                       _anim
+                                       .addRNA("GGGGAAGGGGAAAACCCCAACCCC",
+                                                       "((((..((((....))))..))))");
+                       _anim.addRNA("GGGGAAGGGGAAGGGGAAAACCCCAACCCCAACCCC",
+                                       "((((..((((..((((....))))..))))..))))");
+                       _anim
+                                       .addRNA(
+                                                       "GGGGAGGGGAAAACCCCAGGGGAGGGGAAAACCCCAGGGGAAAACCCCAGGGGAAAACCCCACCCCAGGGGAAAACCCCACCCC",
+                                                       "((((.((((....)))).((((.((((....)))).((((....)))).((((....)))).)))).((((....)))).))))");
+                       _anim
+                                       .addRNA(
+                                                       "GGGGGGGGAAAACCCCAGGGGAAAACCCCAGGGGGGGGAAAACCCCAGGGGAAAACCCCAGGGGAAAACCCCAGGGGAAAACCCCGGGGAAAACCCCACCCCAGGGGAAAACCCCAGGGGAAAACCCCCCCC",
+                                                       "((((((((....)))).((((....)))).((((((((....)))).((((....)))).((((....)))).((((....))))((((....)))).)))).((((....)))).((((....))))))))");
+                       _anim.addRNA("GGGGAAAACCCC", "((((....))))");
+                       _anim.addRNA("GGGGAAGGGGAAAACCCCAGGGGAAAACCCCACCCC",
+                                       "((((..((((....)))).((((....)))).))))");
+                       _anim.addRNA("GGGGAGGGGAAAACCCCAGGGGAAAACCCCAGGGGAAAACCCCACCCC",
+                                       "((((.((((....)))).((((....)))).((((....)))).))))");
+                       _anim
+                                       .addRNA(
+                                                       "GGGGAGGGGAAAAAAACCCCAGGGGAAAAAAACCCCAGGGGAAAAAAACCCCACCCC",
+                                                       "((((.((((.......)))).((((.......)))).((((.......)))).))))");
+                       _anim.start();
+
+                       add(vp, BorderLayout.WEST);
+                       add(_textPanel, BorderLayout.CENTER);
+               } catch (ExceptionNonEqualLength e) {
+               }
+       }
+
+       public void gracefulStop() {
+               _anim.gracefulStop();
+       }
+
+       private class AboutAnimator implements ActionListener {
+               VARNAPanel _vp;
+               ArrayList<String> _structures = new ArrayList<String>();
+               ArrayList<String> _sequences = new ArrayList<String>();
+               int _period = 2000;
+               boolean _over = false;
+
+               public AboutAnimator(VARNAPanel vp) {
+                       super();
+                       _vp = vp;
+               }
+
+               /**
+                * mode pointer for timer cycle -- DELAY1, TASK, DELAY2, STOP
+                */
+               int mode = 0;
+               
+               /**
+                * modes for run()
+                * 
+                */
+               final int DELAY1 = 0, TASK = 1, DELAY2 = 2, STOP = 3;
+               int i = 0;
+
+               @Override
+               public void actionPerformed(ActionEvent e) {
+                       run();
+               }
+
+               public void start() {
+                       int mode = DELAY1;
+                       run();
+               }
+
+               public void addRNA(String seq, String str) {
+                       _sequences.add(seq);
+                       _structures.add(str);
+               }
+
+               public void gracefulStop() {
+                       _over = true;
+               }
+
+               public void run() {
+                       int initialDelay;
+                       if (_over)
+                               mode = STOP;
+                       switch (mode) {
+                       case DELAY1:
+                               mode = TASK;
+                               initialDelay = _period;
+                               break;
+                       case TASK:
+                               String seq = _sequences.get(i);
+                               String str = _structures.get(i);
+                               try {
+                                       _vp.drawRNAInterpolated(seq, str);
+                                       mode = DELAY2;
+                                       initialDelay = 500;
+                               } catch (ExceptionNonEqualLength e) {
+                                       initialDelay = -1;
+                               }
+                               break;
+                       case DELAY2:
+                               i = (i + 1) % _sequences.size();
+                               mode = DELAY1;
+                               initialDelay = 0;
+                               break;
+                       case STOP:
+                       default:
+                               initialDelay = -1;
+                               break;
+                       }
+                       if (initialDelay >= 0) {
+                               Timer t = new Timer(initialDelay, this);
+                               t.setDelay(0);
+                               t.setRepeats(false);
+                               t.start();
+                       } else {
+                               System.out.println("VueAbout done");
+                       }
+
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueAnnotation.java b/src2/fr/orsay/lri/varna/views/VueAnnotation.java
new file mode 100644 (file)
index 0000000..95a8cce
--- /dev/null
@@ -0,0 +1,382 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
+import java.awt.geom.Point2D.Double;
+
+import javax.swing.JButton;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+import javax.swing.JTextArea;
+import javax.swing.border.Border;
+import javax.swing.plaf.basic.BasicBorders;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+import fr.orsay.lri.varna.controlers.ControleurVueAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+
+/**
+ * 
+ * BH SwingJS using asynchronous JOptionPane.showConfirmDialog
+ * 
+ * annoted text view for edition
+ * 
+ * @author Darty@lri.fr
+ * 
+ */
+public class VueAnnotation {
+
+       protected VARNAPanel _vp;
+       private JSlider ySlider, xSlider;
+       private JButton colorButton;
+       private JTextArea textArea;
+       private JPanel panel;
+       protected TextAnnotation textAnnotation, textAnnotationSave;
+       private VueFont vueFont;
+       private ControleurVueAnnotation _controleurVueAnnotation;
+       protected boolean newAnnotation, limited;
+       private Double position;
+       private JSlider rotationSlider;
+
+       /**
+        * creates a view for a new annoted text
+        * 
+        * @param vp
+        * @param limited
+        *            if true, lets custom position and angle.
+        */
+       public VueAnnotation(VARNAPanel vp, boolean limited) {
+               this(
+                               vp,
+                               (int) (vp.getExtendedRNABBox().x + vp.getExtendedRNABBox().width / 2.0),
+                               (int) (vp.getExtendedRNABBox().y + vp.getExtendedRNABBox().height / 2.0),
+                               limited);
+       }
+
+       /**
+        * creates a view for a new annoted text, without limited option
+        * 
+        * @param vp
+        */
+       public VueAnnotation(VARNAPanel vp) {
+               this(vp, false);
+       }
+
+       /**
+        * creates a view for a new annoted text at a given position, without
+        * limited option
+        * 
+        * @param vp
+        */
+       public VueAnnotation(VARNAPanel vp, int x, int y) {
+               this(vp, x, y, false);
+       }
+
+       /**
+        * creates a view for a new annoted text at a given position, without
+        * limited option
+        * 
+        * @param vp
+        */
+       public VueAnnotation(VARNAPanel vp, int x, int y, boolean limited) {
+               this(vp, new TextAnnotation("", x, y), false, true);
+       }
+
+       /**
+        * creates a view for an annoted text, without limited option
+        * 
+        * @param vp
+        * @param textAnnot
+        */
+       public VueAnnotation(VARNAPanel vp, TextAnnotation textAnnot,
+                       boolean newAnnotation) {
+               this(vp, textAnnot, (textAnnot.getType()!=TextAnnotation.AnchorType.POSITION), newAnnotation);
+       }
+
+       /**
+        * creates a view for an annoted text
+        * 
+        * 
+        * @param vp
+        * @param textAnnot
+        * @param reduite
+        *            if true, lets custom position and angle.
+        * @param newAnnotation
+        *            if true, deleted if cancelled.
+        */
+       public VueAnnotation(VARNAPanel vp, TextAnnotation textAnnot,
+                       boolean reduite, boolean newAnnotation) {
+               this.limited = reduite;
+               this.newAnnotation = newAnnotation;
+               _vp = vp;
+               textAnnotation = textAnnot;
+               textAnnotationSave = textAnnotation.clone();
+
+               if (!_vp.getListeAnnotations().contains(textAnnot)) {
+                       _vp.addAnnotation(textAnnotation);
+               }
+
+               _controleurVueAnnotation = new ControleurVueAnnotation(this);
+
+               position = textAnnotation.getCenterPosition();
+
+               /*
+                * if (textAnnotation.getType() != TextAnnotation.POSITION) { position =
+                * _vp.transformCoord(position); }
+                */
+
+               JPanel py = new JPanel();
+               JPanel px = new JPanel();
+               panel = new JPanel();
+               panel.setLayout(new GridLayout(0, 1));
+               py.setLayout(new FlowLayout(FlowLayout.LEFT));
+               px.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               ySlider = new JSlider(JSlider.HORIZONTAL, 0, (int) (_vp
+                               .getExtendedRNABBox().height), Math.max(0, Math.min((int) (_vp
+                               .getExtendedRNABBox().height), (int) (position.y - _vp
+                               .getExtendedRNABBox().y))));
+               // Turn on labels at major tick marks.
+               ySlider.setMajorTickSpacing(500);
+               ySlider.setMinorTickSpacing(100);
+               ySlider.setPaintTicks(true);
+               ySlider.setPaintLabels(true);
+               ySlider.setPreferredSize(new Dimension(400,
+                               ySlider.getPreferredSize().height));
+
+               JLabel yValueLabel = new JLabel(String.valueOf((int) position.y
+                               - _vp.getExtendedRNABBox().y));
+               yValueLabel.setPreferredSize(new Dimension(50, yValueLabel
+                               .getPreferredSize().height));
+               ySlider
+                               .addChangeListener(new ControleurSliderLabel(yValueLabel, false));
+               ySlider.addChangeListener(_controleurVueAnnotation);
+
+               xSlider = new JSlider(JSlider.HORIZONTAL, 0, (int) (_vp
+                               .getExtendedRNABBox().width), Math.max(0, Math.min((int) _vp
+                               .getExtendedRNABBox().width, (int) (position.x - _vp
+                               .getExtendedRNABBox().x))));
+               // Turn on labels at major tick marks.
+               xSlider.setMajorTickSpacing(500);
+               xSlider.setMinorTickSpacing(100);
+               xSlider.setPaintTicks(true);
+               xSlider.setPaintLabels(true);
+               xSlider.setPreferredSize(new Dimension(400,
+                               xSlider.getPreferredSize().height));
+
+               JLabel xValueLabel = new JLabel(String.valueOf((int) position.x
+                               - _vp.getExtendedRNABBox().x));
+               xValueLabel.setPreferredSize(new Dimension(50, xValueLabel
+                               .getPreferredSize().height));
+               xSlider
+                               .addChangeListener(new ControleurSliderLabel(xValueLabel, false));
+               xSlider.addChangeListener(_controleurVueAnnotation);
+
+               JLabel labelY = new JLabel("Y:");
+               JLabel labelX = new JLabel("X:");
+
+               py.add(labelY);
+               py.add(ySlider);
+               py.add(yValueLabel);
+               px.add(labelX);
+               px.add(xSlider);
+               px.add(xValueLabel);
+
+               /*if (!limited) {
+                       panel.add(px);
+                       panel.add(py);
+               }*/
+
+               JPanel panelTexte = new JPanel();
+               panelTexte.setLayout(new BorderLayout());
+               textArea = new JTextArea(textAnnotation.getTexte());
+               textArea.addCaretListener(_controleurVueAnnotation);
+               textArea.setPreferredSize(panelTexte.getSize());
+               Border border = new BasicBorders.FieldBorder(Color.black, Color.black,
+                               Color.black, Color.black);
+               textArea.setBorder(border);
+               JLabel labelTexte = new JLabel("Text:");
+               panelTexte.add(textArea, BorderLayout.CENTER);
+               panelTexte.add(labelTexte, BorderLayout.NORTH);
+               panel.add(panelTexte);
+
+               vueFont = new VueFont(textAnnot.getFont());
+               vueFont.getBoxPolice().addActionListener(_controleurVueAnnotation);
+               vueFont.getSizeSlider().addChangeListener(_controleurVueAnnotation);
+               vueFont.getStylesBox().addActionListener(_controleurVueAnnotation);
+
+               colorButton = new JButton("Set color");
+               colorButton.setActionCommand("setcolor");
+               colorButton.setForeground(textAnnot.getColor());
+               colorButton.addActionListener(_controleurVueAnnotation);
+
+               JPanel fontAndColor = new JPanel();
+               fontAndColor.add(vueFont.getPanel());
+               fontAndColor.add(colorButton);
+
+               panel.add(fontAndColor);
+
+               JPanel rotationPanel = new JPanel();
+
+               rotationSlider = new JSlider(JSlider.HORIZONTAL, -360, 360,
+                               (int) textAnnotation.getAngleInDegres());
+               rotationSlider.setMajorTickSpacing(60);
+               rotationSlider.setPaintTicks(true);
+               rotationSlider.setPaintLabels(true);
+               rotationSlider.setPreferredSize(new Dimension(500, 50));
+
+               JLabel rotationLabel = new JLabel(String.valueOf(0));
+               rotationLabel.setPreferredSize(new Dimension(50, rotationLabel
+                               .getPreferredSize().height));
+               rotationSlider.addChangeListener(new ControleurSliderLabel(
+                               rotationLabel, false));
+               rotationSlider.addChangeListener(_controleurVueAnnotation);
+
+               JLabel labelZ = new JLabel("Rotation (degrees):");
+
+               rotationPanel.add(labelZ);
+               rotationPanel.add(rotationSlider);
+               rotationPanel.add(rotationLabel);
+
+               /*
+                * if (!limited) { panel.add(rotationPanel); }
+                */
+
+               if (limited) {
+                       ySlider.setEnabled(false);
+                       xSlider.setEnabled(false);
+                       rotationSlider.setEnabled(false);
+               }
+               textArea.requestFocusInWindow();
+               
+       }
+
+       private void applyFont() {
+               textAnnotation.setFont(vueFont.getFont());
+       }
+
+       /**
+        * update the annoted text on the VARNAPanel
+        */
+       public void update() {
+               applyFont();
+               if (textAnnotation.getType() == TextAnnotation.AnchorType.POSITION)
+                       textAnnotation.setAncrage((double) xSlider.getValue()
+                                       + _vp.getExtendedRNABBox().x, ySlider.getValue()
+                                       + _vp.getExtendedRNABBox().y);
+               textAnnotation.setText(textArea.getText());
+               textAnnotation.setAngleInDegres(rotationSlider.getValue());
+               _vp.clearSelection();
+               _vp.repaint();
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       /**
+        * 
+        * @return the annoted text
+        */
+       public TextAnnotation getTextAnnotation() {
+               return textAnnotation;
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       /**
+        * shows the dialog which add it to the VARNAPanel for previsualization.
+        * <p>
+        * if validate, just update the annoted text
+        * <p>
+        * if cancelled : remove the annoted text if it was a new one, otherwise
+        * cancel modifications
+        * <p>
+        * 
+        */
+       public void show() {
+               _vp.set_selectedAnnotation(textAnnotation);
+               _vp.highlightSelectedAnnotation();
+               
+               // BH SwingjS using asynchronous dialog
+               Runnable ok = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               update();
+                       }
+                       
+               };
+
+               Runnable cancel = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               if (newAnnotation) {
+                                       _vp.set_selectedAnnotation(null);
+                                       if (!_vp.removeAnnotation(textAnnotation))
+                                               _vp.errorDialog(new Exception("Impossible de supprimer"));
+                               } else {
+                                       textAnnotation.copy(textAnnotationSave);
+                               }
+                       }
+                       
+               };
+
+               Runnable final_ = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               _vp.resetAnnotationHighlight();
+                               _vp.set_selectedAnnotation(null);
+                               _vp.repaint();
+                       }
+                       
+               };
+               
+               _vp.getVARNAUI().showConfirmDialog(getPanel(), "Add/edit annotation", ok, cancel, cancel, final_);
+       }
+
+       public boolean isLimited() {
+               return limited;
+       }
+
+       public void setLimited(boolean limited) {
+               this.limited = limited;
+       }
+
+       public boolean isNewAnnotation() {
+               return this.newAnnotation;
+       }
+
+       public void updateColor(Color c) {
+               colorButton.setForeground(c);
+               textAnnotation.setColor(c);
+
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueBPHeightIncrement.java b/src2/fr/orsay/lri/varna/views/VueBPHeightIncrement.java
new file mode 100644 (file)
index 0000000..342608f
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurBPHeightIncrement;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VueBPHeightIncrement {
+       private VARNAPanel _vp;
+       private JPanel panel;
+       private JSlider spaceSlider;
+
+       public VueBPHeightIncrement(VARNAPanel vp) {
+               _vp = vp;
+               panel = new JPanel();
+
+               spaceSlider = new JSlider(JSlider.HORIZONTAL, 10, 200, Integer
+                               .valueOf(String.valueOf(Math
+                                               .round(vp.getRNA().getBPHeightIncrement() * 100))));
+               // Turn on labels at major tick marks.
+               spaceSlider.setMajorTickSpacing(30);
+               spaceSlider.setPaintTicks(true);
+               spaceSlider.setPaintLabels(true);
+
+               JLabel spaceLabel = new JLabel(String
+                               .valueOf(vp.getRNA().getBPHeightIncrement() * 100.0));
+               spaceLabel.setPreferredSize(new Dimension(50, spaceLabel
+                               .getPreferredSize().height));
+               spaceSlider.addChangeListener(new ControleurSliderLabel(spaceLabel,
+                               false));
+               spaceSlider.addChangeListener(new ControleurBPHeightIncrement(this));
+
+               panel = new JPanel();
+               panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel labelS = new JLabel("HeighInc:");
+
+               panel.add(labelS);
+               panel.add(spaceSlider);
+               panel.add(spaceLabel);
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public Double getIncrement() {
+               return spaceSlider.getValue() / 100.0;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueBPList.java b/src2/fr/orsay/lri/varna/views/VueBPList.java
new file mode 100644 (file)
index 0000000..7c18d9c
--- /dev/null
@@ -0,0 +1,221 @@
+package fr.orsay.lri.varna.views;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyVetoException;
+import java.beans.VetoableChangeListener;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Vector;
+
+import javax.swing.DefaultCellEditor;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.event.TableModelEvent;
+import javax.swing.event.TableModelListener;
+import javax.swing.table.AbstractTableModel;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.ActionEditor;
+import fr.orsay.lri.varna.components.ActionRenderer;
+import fr.orsay.lri.varna.components.ColorRenderer;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VueBPList extends JPanel implements TableModelListener, ActionListener
+{
+
+       private JTable table;
+       private BPTableModel _tm;
+       private VARNAPanel _vp;
+       private ArrayList<ModeleBP> data;
+       private ArrayList<Double> _backup;
+       private ArrayList<Object> columns;
+       
+       
+       public enum Actions{
+               ACTION_DELETE,
+               ACTION_EDIT_STYLE;
+               
+               public String toString()
+               {
+                       switch(this)
+                       {
+                         case ACTION_DELETE:
+                                 return "Delete";
+                         case ACTION_EDIT_STYLE:
+                                 return "Edit Style";
+                       }
+                       return "N/A";
+               }
+       };
+       
+       public VueBPList(VARNAPanel vp)
+       {
+               super(new GridLayout(1, 0));
+               _vp = vp;
+               init();
+       }
+       
+       private void init()
+       {
+               Object[] col = {"Sec.Str.","5' partner","3' partner","5' edge","3' edge","Orientation","Remove"};
+               columns = new ArrayList<Object>();
+               for (int i = 0; i < col.length; i++)
+               {
+                       columns.add(col[i]);
+               }
+               
+               _backup = new ArrayList<Double>();
+               data = new ArrayList<ModeleBP>();
+               for (ModeleBP ms: _vp.getRNA().getAllBPs()) 
+               {
+                       data.add(ms);
+               }
+               Collections.sort(data);
+               _tm = new BPTableModel();
+               table = new JTable(_tm);
+               
+               table.setDefaultRenderer(Color.class, new ColorRenderer(true)); 
+               table.setDefaultRenderer(Actions.class, new ActionRenderer());
+               
+               table.setDefaultEditor(ModeleBP.Edge.class, new DefaultCellEditor(new JComboBox(ModeleBP.Edge.values())));
+               table.setDefaultEditor(ModeleBP.Stericity.class, new DefaultCellEditor(new JComboBox(ModeleBP.Stericity.values())));
+               table.setDefaultEditor(Actions.class, new ActionEditor(this));
+
+               table.setPreferredScrollableViewportSize(new Dimension(500, 500));
+               table.getModel().addTableModelListener(this);
+               
+               table.setRowHeight(25);
+               
+               JScrollPane scrollPane = new JScrollPane(table);
+               add(scrollPane);
+               setOpaque(true); // content panes must be opaque
+               this.doLayout();
+
+               JOptionPane.showMessageDialog(_vp, this, "Base pairs Edition", JOptionPane.PLAIN_MESSAGE);
+
+       }
+       
+       public void cancelChanges()
+       {
+               for (int i = 0; i < _vp.getRNA().get_listeBases().size(); i++) 
+               {
+                       ModeleBase mb = _vp.getRNA().get_listeBases().get(i);
+                       mb.setValue(_backup.get(i));
+               }
+         _vp.getRNA().rescaleColorMap(_vp.getColorMap());
+       }
+
+       private class BPTableModel extends AbstractTableModel {
+           /**
+                * 
+                */
+               private static final long serialVersionUID = 1L;
+               public String getColumnName(int col) {
+               return columns.get(col).toString();
+           }
+           public int getRowCount() { return data.size(); }
+           public int getColumnCount() { return columns.size(); }
+           public Object getValueAt(int row, int col) {
+               ModeleBP mb = data.get(row);
+               if (col==0)
+               {
+                       return new Boolean(mb.getPartner3().getElementStructure()==mb.getPartner5().getIndex());
+               }
+               else if (col==1)
+               {
+                       return new String(""+mb.getPartner5().getBaseNumber()+"-"+mb.getPartner5().getContent());
+               } 
+               else if (col==2)
+               {
+                       return new String(""+mb.getPartner3().getBaseNumber()+"-"+mb.getPartner3().getContent());
+               } 
+               else if (col==3)
+               {
+                       return mb.getEdgePartner5();
+               }
+               else if (col==4)
+               {
+                       return mb.getEdgePartner3();
+               }
+               else if (col==5)
+               {
+                       return mb.getStericity();
+               }
+               else if (col==6)
+               {
+                       return Actions.ACTION_DELETE;
+               }
+               return "N/A";
+           }
+           public boolean isCellEditable(int row, int col)
+               { 
+                       if ( col == 3 || col ==4 || col ==5 || col ==6) 
+                               return true;
+                       return false;
+               }
+           public void setValueAt(Object value, int row, int col) {
+               if ( col == 3 || col ==4 || col ==5) 
+               {
+                       ModeleBP mb = data.get(row);
+                       if ( col == 3)
+                       {
+                         mb.setEdge5((ModeleBP.Edge)value);    
+                       }
+                       else if ( col == 4)
+                       {
+                                 mb.setEdge3((ModeleBP.Edge)value);    
+                       }
+                       else if ( col == 5)
+                       {
+                                 mb.setStericity((ModeleBP.Stericity)value);                                   
+                       }
+                 fireTableCellUpdated(row, col);
+                 _vp.repaint();
+                 
+               }
+           }
+           
+           public Class getColumnClass(int c) {
+               return getValueAt(0, c).getClass();
+           }
+       }
+
+       public void tableChanged(TableModelEvent e) {
+               if (e.getType() == TableModelEvent.UPDATE)
+               {
+                       table.repaint();
+               }
+               
+       }
+
+       public void actionPerformed(ActionEvent arg0) {
+               //System.out.println(""+arg0.toString());
+               String[] data2 = arg0.getActionCommand().split("-");
+               int row = Integer.parseInt(data2[data2.length-1]);
+               if (data2[0].equals("Delete"))
+               {
+                       ModeleBP ms = data.get(row);
+                       _vp.getVARNAUI().UIRemoveBP(ms);
+                       
+                       
+                       data.remove(row);
+                       
+                       _tm.fireTableRowsDeleted(row, row);
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueBPThickness.java b/src2/fr/orsay/lri/varna/views/VueBPThickness.java
new file mode 100644 (file)
index 0000000..af35a03
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.util.ArrayList;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+public class VueBPThickness implements ChangeListener {
+
+       private VARNAPanel _vp;
+       ArrayList<ModeleBP> _msbp;
+       private JSlider _thicknessSlider;
+       private JPanel panel;
+
+       private ArrayList<Double> _backupThicknesses = new ArrayList<Double>();
+
+       private double FACTOR = 10.0;
+
+       public VueBPThickness(VARNAPanel vp, ArrayList<ModeleBP> msbp) {
+               _vp = vp;
+               _msbp = msbp;
+               backupThicknesses();
+
+               _thicknessSlider = new JSlider(JSlider.HORIZONTAL, 1, 100,
+                               (int) (msbp.get(0).getStyle().getThickness(
+                                               VARNAConfig.DEFAULT_BP_THICKNESS) * FACTOR));
+               _thicknessSlider.setMajorTickSpacing(10);
+               _thicknessSlider.setPaintTicks(true);
+               _thicknessSlider.setPaintLabels(false);
+               _thicknessSlider.setPreferredSize(new Dimension(500, 50));
+
+               JLabel thicknessLabel = new JLabel(String.valueOf(msbp.get(0).getStyle()
+                               .getThickness(VARNAConfig.DEFAULT_BP_THICKNESS)));
+               thicknessLabel.setPreferredSize(new Dimension(50, thicknessLabel
+                               .getPreferredSize().height));
+               _thicknessSlider.addChangeListener(new ControleurSliderLabel(
+                               thicknessLabel, 1.0 / FACTOR));
+               _thicknessSlider.addChangeListener(this);
+
+               panel = new JPanel();
+               panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel labelZ = new JLabel("Thickness:");
+
+               panel.add(labelZ);
+               panel.add(_thicknessSlider);
+               panel.add(thicknessLabel);
+       }
+
+       private void backupThicknesses() {
+               for (int i = 0; i < _msbp.size(); i++) {
+                       this._backupThicknesses.add(_msbp.get(i).getStyle().getThickness(
+                                       VARNAConfig.DEFAULT_BP_THICKNESS));
+               }
+       }
+
+       public void restoreThicknesses() {
+               for (int i = 0; i < _msbp.size(); i++) {
+                       _msbp.get(i).getStyle().setThickness(_backupThicknesses.get(i));
+               }
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public double getThickness() {
+               return (double) _thicknessSlider.getValue() / FACTOR;
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               for (int i = 0; i < _msbp.size(); i++) {
+                       _msbp.get(i).getStyle().setThickness(
+                                       ((double) _thicknessSlider.getValue()) / FACTOR);
+               }
+               _vp.repaint();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueBPType.java b/src2/fr/orsay/lri/varna/views/VueBPType.java
new file mode 100644 (file)
index 0000000..93d5b33
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JComboBox;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+
+
+public class VueBPType implements ActionListener {
+
+       private VARNAPanel _vp;
+       ModeleBP _msbp;
+       private JComboBox _edge5;
+       private JComboBox _edge3;
+       private JComboBox _stericity;
+       private JPanel panel;
+
+       public VueBPType(VARNAPanel vp, ModeleBP msbp) {
+               _vp = vp;
+               _msbp = msbp;
+
+               ModeleBP.Edge[] edges = ModeleBP.Edge.values();
+               ModeleBP.Edge bck = msbp.getEdgePartner5();
+               _edge5 = new JComboBox(edges);
+               for (int i = 0; i < edges.length; i++) {
+                       if (edges[i] == bck)
+                               _edge5.setSelectedIndex(i);
+               }
+
+               bck = msbp.getEdgePartner3();
+               _edge3 = new JComboBox(edges);
+               for (int i = 0; i < edges.length; i++) {
+                       if (edges[i] == bck)
+                               _edge3.setSelectedIndex(i);
+               }
+
+               ModeleBP.Stericity[] sters = ModeleBP.Stericity.values();
+               ModeleBP.Stericity bcks = msbp.getStericity();
+               _stericity = new JComboBox(sters);
+               for (int i = 0; i < sters.length; i++) {
+                       if (sters[i] == bcks)
+                               _stericity.setSelectedIndex(i);
+               }
+
+               _edge5.addActionListener(this);
+               _edge3.addActionListener(this);
+               _stericity.addActionListener(this);
+
+               panel = new JPanel();
+               panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel label5 = new JLabel("5' edge: ");
+               JLabel label3 = new JLabel("3' edge: ");
+               JLabel labelS = new JLabel("Stericity: ");
+
+               panel.add(label5);
+               panel.add(_edge5);
+               panel.add(label3);
+               panel.add(_edge3);
+               panel.add(labelS);
+               panel.add(_stericity);
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public ModeleBP.Edge getEdge5() {
+               return (ModeleBP.Edge) _edge5.getSelectedItem();
+       }
+
+       public ModeleBP.Edge getEdge3() {
+               return (ModeleBP.Edge) _edge3.getSelectedItem();
+       }
+
+       public ModeleBP.Stericity getStericity() {
+               return (ModeleBP.Stericity) _stericity.getSelectedItem();
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public void actionPerformed(ActionEvent e) {
+               _msbp.setEdge5(getEdge5());
+               _msbp.setEdge3(getEdge3());
+               _msbp.setStericity(getStericity());
+               _vp.repaint();
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueBaseValues.java b/src2/fr/orsay/lri/varna/views/VueBaseValues.java
new file mode 100644 (file)
index 0000000..980ac65
--- /dev/null
@@ -0,0 +1,134 @@
+package fr.orsay.lri.varna.views;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyVetoException;
+import java.beans.VetoableChangeListener;
+import java.util.ArrayList;
+import java.util.Vector;
+
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.event.TableModelEvent;
+import javax.swing.event.TableModelListener;
+import javax.swing.table.AbstractTableModel;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.ColorRenderer;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VueBaseValues extends JPanel implements TableModelListener {
+
+       private JTable table;
+       private ValueTableModel _tm;
+       private VARNAPanel _vp;
+       private ArrayList<ModeleBase> data;
+       private ArrayList<Double> _backup;
+       private ArrayList<Object> columns;
+       
+       
+       public VueBaseValues(VARNAPanel vp)
+       {
+               super(new GridLayout(1, 0));
+               _vp = vp;
+               init();
+       }
+       
+       private void init()
+       {
+               Object[] col = {"Number","Base","Value","Preview"};
+               columns = new ArrayList<Object>();
+               for (int i = 0; i < col.length; i++)
+               {
+                       columns.add(col[i]);
+               }
+               
+               _backup = new ArrayList<Double>();
+               data = new ArrayList<ModeleBase>();
+               for (int i = 0; i < _vp.getRNA().get_listeBases().size(); i++) 
+               {
+                       ModeleBase mb = _vp.getRNA().get_listeBases().get(i);
+                       data.add(mb);
+                       _backup.add(mb.getValue());
+               }
+               _tm = new ValueTableModel();
+               table = new JTable(_tm);
+               table.setDefaultRenderer(Color.class, new ColorRenderer(true)); 
+               table.setPreferredScrollableViewportSize(new Dimension(300, 300));
+               table.getModel().addTableModelListener(this);
+               
+               JScrollPane scrollPane = new JScrollPane(table);
+               this.add(scrollPane);
+       }
+       
+       public void cancelChanges()
+       {
+               for (int i = 0; i < _vp.getRNA().get_listeBases().size(); i++) 
+               {
+                       ModeleBase mb = _vp.getRNA().get_listeBases().get(i);
+                       mb.setValue(_backup.get(i));
+               }
+         _vp.getRNA().rescaleColorMap(_vp.getColorMap());
+       }
+
+       private class ValueTableModel extends AbstractTableModel {
+           public String getColumnName(int col) {
+               return columns.get(col).toString();
+           }
+           public int getRowCount() { return data.size(); }
+           public int getColumnCount() { return columns.size(); }
+           public Object getValueAt(int row, int col) {
+               ModeleBase mb = data.get(row);
+               if (col==0)
+               {
+                       return new Integer(mb.getBaseNumber());
+               }
+               else if (col==1)
+               {
+                       return new String(mb.getContent());
+               } 
+               else if (col==2)
+               {
+                       return new Double(mb.getValue());
+               } 
+               else if (col==3)
+               {
+                       return _vp.getColorMap().getColorForValue(mb.getValue());
+               }
+               return "N/A";
+           }
+           public boolean isCellEditable(int row, int col)
+               { 
+                       if (getColumnName(col).equals("Value")) 
+                               return true;
+                       return false;
+               }
+           public void setValueAt(Object value, int row, int col) {
+               if (getColumnName(col).equals("Value"))
+               {
+                 data.get(row).setValue(((Double)value));
+                 _vp.getRNA().rescaleColorMap(_vp.getColorMap());
+                 _vp.repaint();
+                 fireTableCellUpdated(row, col);
+               }
+           }
+           public Class getColumnClass(int c) {
+               return getValueAt(0, c).getClass();
+           }
+       }
+
+       public void tableChanged(TableModelEvent e) {
+               if (e.getType() == TableModelEvent.UPDATE)
+               {
+                       table.repaint();
+               }
+               
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueBases.java b/src2/fr/orsay/lri/varna/views/VueBases.java
new file mode 100644 (file)
index 0000000..6f9d95a
--- /dev/null
@@ -0,0 +1,215 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+import javax.swing.JComponent;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.event.TableModelEvent;
+import javax.swing.event.TableModelListener;
+
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.BaseSpecialColorEditor;
+import fr.orsay.lri.varna.components.BaseTableModel;
+import fr.orsay.lri.varna.components.ColorRenderer;
+import fr.orsay.lri.varna.models.BaseList;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+
+public class VueBases extends JPanel {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       /**
+        * for bases by kind
+        */
+       public final static int KIND_MODE = 1;
+       /**
+        * for all bases 
+        */
+       public final static int ALL_MODE = 2;
+       /**
+        * for base pairs by king
+        */
+       public final static int COUPLE_MODE = 3;
+
+       private int _mode;
+
+       private VARNAPanel _vp;
+
+       private ArrayList<BaseList> data = new ArrayList<BaseList>();
+       
+       private Hashtable<String,BaseList> revdata = new Hashtable<String,BaseList>();
+       
+       private JTable table;
+
+       private BaseTableModel specialTableModel;
+
+       public VueBases(VARNAPanel vp, int mode) {
+               super(new GridLayout(1, 0));
+               _vp = vp;
+               switch (mode) {
+               case (KIND_MODE):
+                       _mode = KIND_MODE;
+                       kindMode();
+                       break;
+               case (ALL_MODE):
+                       _mode = ALL_MODE;
+                       allMode();
+                       break;
+               case (COUPLE_MODE):
+                       _mode = COUPLE_MODE;
+                       coupleMode();
+                       break;
+               default:
+                       break;
+               }
+       }
+       
+       private BaseList locateOrAddList(String caption)
+       {
+         if (!revdata.containsKey(caption))
+         {
+                 BaseList mbl = new BaseList(caption);
+                 revdata.put(caption,mbl);
+                 data.add(mbl);
+         }
+         return revdata.get(caption);
+       }
+
+       private void coupleMode() {
+               String pairString;
+               for (int i = 0; i < _vp.getRNA().get_listeBases().size(); i++) {
+                       
+                       int j = _vp.getRNA().get_listeBases().get(i).getElementStructure();
+                       if (j > i) {
+                               String tmp1 = (_vp.getRNA().get_listeBases().get(i).getContent()); 
+                               String tmp2 = (_vp.getRNA().get_listeBases().get(j).getContent()); 
+                               pairString = tmp1 +"-"+ tmp2;
+                               BaseList bl = locateOrAddList(pairString);
+                               bl.addBase(_vp.getRNA().get_listeBases().get(i));
+                               bl.addBase(_vp.getRNA().get_listeBases().get(j));
+                       }
+               }
+               createView();
+       }
+
+       private void allMode() {
+               for (int i = 0; i < _vp.getRNA().get_listeBases().size(); i++) {
+                       ModeleBase mb = _vp.getRNA().get_listeBases().get(i);
+                       BaseList bl = locateOrAddList(""+i);
+                       bl.addBase(mb);
+               }
+               createView();
+       }
+
+       private void kindMode() {
+               for (int i = 0; i < _vp.getRNA().get_listeBases().size(); i++) {
+                       ModeleBase mb = _vp.getRNA().get_listeBases().get(i);
+                       String tmp1 = (mb.getContent()); 
+                       BaseList bl = locateOrAddList(tmp1);
+                       bl.addBase(mb);
+               }
+               createView();
+       }
+
+       private void createView() {
+               specialTableModel = new BaseTableModel(data);
+               table = new JTable(specialTableModel);
+               table.setPreferredScrollableViewportSize(new Dimension(500, 300));
+               // TODO: Find equivalent in JRE 1.5
+               //table.setFillsViewportHeight(true);
+               // Create the scroll pane and add the table to it.
+               JScrollPane scrollPane = new JScrollPane(table);
+
+               // Set up renderer and editor for the Favorite Color column.
+               table.setDefaultRenderer(Color.class, new ColorRenderer(true));
+               table.setDefaultEditor(Color.class, new BaseSpecialColorEditor(this));
+               specialTableModel.addTableModelListener(new TableModelListener(){
+
+                       public void tableChanged(TableModelEvent e) {
+                               _vp.repaint();
+                       }
+                       
+               });
+
+               // Add the scroll pane to this panel.
+               add(scrollPane);
+
+               UIvueBases();
+       }
+
+       /**
+        * Create the GUI and show it. For thread safety, this method should be
+        * invoked from the event-dispatching thread.
+        */
+       public void UIvueBases() {
+               // Create and set up the content pane.
+               JComponent newContentPane = this;
+               newContentPane.setOpaque(true); // content panes must be opaque
+
+               JOptionPane.showMessageDialog(_vp, newContentPane,
+                               "Base Colors Edition", JOptionPane.PLAIN_MESSAGE);
+
+       }
+
+       public int getMode() {
+               return _mode;
+       }
+
+       public BaseList getDataAt(int i) {
+               return data.get(i);
+       }
+
+       
+       public ArrayList<BaseList> getData() {
+               return data;
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public JTable getTable() {
+               return table;
+       }
+
+       public void setTable(JTable table) {
+               this.table = table;
+       }
+
+       public BaseTableModel getSpecialTableModel() {
+               return specialTableModel;
+       }
+
+       public void setSpecialTableModel(BaseTableModel specialTableModel) {
+               this.specialTableModel = specialTableModel;
+       }
+       
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueBorder.java b/src2/fr/orsay/lri/varna/views/VueBorder.java
new file mode 100644 (file)
index 0000000..b0f9ca6
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurBorder;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+
+public class VueBorder {
+
+       private VARNAPanel _vp;
+       private JSlider borderHeightSlider, borderWidthSlider;
+       private JPanel panel;
+
+       public VueBorder(VARNAPanel vp) {
+               _vp = vp;
+
+               JPanel pup = new JPanel();
+               JPanel pdown = new JPanel();
+               panel = new JPanel();
+               panel.setLayout(new GridLayout(2, 1));
+               pup.setLayout(new FlowLayout(FlowLayout.LEFT));
+               pdown.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               borderHeightSlider = new JSlider(JSlider.HORIZONTAL, 0,
+                               _vp.getHeight() / 2 - 10, _vp.getBorderSize().height);
+               // Turn on labels at major tick marks.
+               borderHeightSlider.setMajorTickSpacing(50);
+               borderHeightSlider.setMinorTickSpacing(10);
+               borderHeightSlider.setPaintTicks(true);
+               borderHeightSlider.setPaintLabels(true);
+               JLabel borderHeightLabel = new JLabel(String.valueOf(_vp
+                               .getBorderSize().height));
+               borderHeightLabel.setPreferredSize(new Dimension(50, borderHeightLabel
+                               .getPreferredSize().height));
+               borderHeightSlider.addChangeListener(new ControleurSliderLabel(
+                               borderHeightLabel, false));
+               borderHeightSlider.addChangeListener(new ControleurBorder(this));
+
+               borderWidthSlider = new JSlider(JSlider.HORIZONTAL, 0,
+                               _vp.getWidth() / 2 - 10, _vp.getBorderSize().width);
+               // Turn on labels at major tick marks.
+               borderWidthSlider.setMajorTickSpacing(50);
+               borderWidthSlider.setMinorTickSpacing(10);
+               borderWidthSlider.setPaintTicks(true);
+               borderWidthSlider.setPaintLabels(true);
+               JLabel borderWidthLabel = new JLabel(String
+                               .valueOf(_vp.getBorderSize().width));
+               borderWidthLabel.setPreferredSize(new Dimension(50, borderWidthLabel
+                               .getPreferredSize().height));
+               borderWidthSlider.addChangeListener(new ControleurSliderLabel(
+                               borderWidthLabel, false));
+               borderWidthSlider.addChangeListener(new ControleurBorder(this));
+
+               JLabel labelW = new JLabel("Width:");
+               JLabel labelH = new JLabel("Height:");
+
+               pup.add(labelW);
+               pup.add(borderWidthSlider);
+               pup.add(borderWidthLabel);
+
+               pdown.add(labelH);
+               pdown.add(borderHeightSlider);
+               pdown.add(borderHeightLabel);
+
+               panel.add(pup);
+               panel.add(pdown);
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public Dimension getDimension() {
+               return new Dimension(borderWidthSlider.getValue(), borderHeightSlider
+                               .getValue());
+       }
+
+       public int getHeight() {
+               return borderHeightSlider.getValue();
+       }
+
+       public int getWidth() {
+               return borderWidthSlider.getValue();
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueChemProbAnnotation.java b/src2/fr/orsay/lri/varna/views/VueChemProbAnnotation.java
new file mode 100644 (file)
index 0000000..536d3fa
--- /dev/null
@@ -0,0 +1,172 @@
+       package fr.orsay.lri.varna.views;
+
+
+       import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JSpinner;
+import javax.swing.SpinnerNumberModel;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+
+
+public class VueChemProbAnnotation implements ChangeListener, ActionListener, ItemListener {
+
+               protected VARNAPanel _vp;
+               private JPanel panel;
+               protected ChemProbAnnotation _an;
+               private static int CONTROL_HEIGHT = 50;
+               private static int TITLE_WIDTH = 70;
+               private static int CONTROL_WIDTH = 200;
+               protected JButton color  = new JButton();
+               JSpinner intensity;
+               JComboBox outward = new JComboBox(new String[]{"Inward","Outward"});
+               JComboBox type = new JComboBox(ChemProbAnnotation.ChemProbAnnotationType.values());
+
+               public VueChemProbAnnotation(VARNAPanel vp, ChemProbAnnotation an) {
+                       _an = an;
+                       _vp = vp;
+
+                       panel = new JPanel();
+                       panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+
+                       JPanel outlinep = new JPanel();
+                       JLabel l1 = new JLabel("Color: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       color.setContentAreaFilled(false);
+                       color.setOpaque(true);
+                       color.setPreferredSize(new Dimension(CONTROL_WIDTH,CONTROL_HEIGHT));
+                       color.setBackground(_an.getColor());
+                       color.addActionListener(this);
+                       color.setActionCommand("outline");
+                       outlinep.add(l1);
+                       outlinep.add(color);
+                       
+                       
+                       JPanel radiusp = new JPanel();
+                       l1 = new JLabel("Intensity: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       SpinnerNumberModel jm = new SpinnerNumberModel(_an.getIntensity(),0.01,10.0,0.01);
+                       intensity = new JSpinner(jm);
+                       radiusp.add(l1);
+                       radiusp.add(intensity);
+                       intensity.addChangeListener(this);
+
+                       JPanel dirp = new JPanel();
+                       l1 = new JLabel("Direction: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       outward.addItemListener(this);
+                       dirp.add(l1);
+                       dirp.add(outward);
+
+                       JPanel typep = new JPanel();
+                       l1 = new JLabel("Type: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       type.addItemListener(this);
+                       typep.add(l1);
+                       typep.add(type);
+                       
+                       
+                       
+                       JPanel jp = new JPanel();
+                       jp.setLayout(new GridLayout(4,1));
+                       jp.add(outlinep);
+                       jp.add(radiusp);
+                       jp.add(dirp);
+                       jp.add(typep);
+                       panel.add(jp);
+               }
+
+               public JPanel getPanel() {
+                       return panel;
+               }
+
+               public VARNAPanel get_vp() {
+                       return _vp;
+               }
+               
+               HighlightRegionAnnotation _backup = null;
+               
+               public boolean show() {
+                       boolean accept = false;
+                       intensity.setValue(_an.getIntensity());
+                       color.setBackground(_an.getColor());
+                       type.setSelectedItem(_an.getType());
+                       outward.setSelectedItem((_an.isOut()?"Inward":"Outward"));
+                       
+                       if (JOptionPane.showConfirmDialog(_vp, getPanel(),
+                                       "Edit chemical probing annotation", JOptionPane.OK_CANCEL_OPTION,
+                                       JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) 
+                       {
+                               accept = true;
+                       } 
+                       _vp.repaint();
+                       return accept;
+               }
+
+               public void stateChanged(ChangeEvent e) {
+                       if (e.getSource().equals(intensity))
+                       {
+                               Object val = intensity.getValue();
+                               if (val instanceof Double)
+                               {                                       
+                                       _an.setIntensity(((Double)val).doubleValue());
+                                       _vp.repaint();
+                               }
+                       }
+                       
+               }
+
+       public void actionPerformed(ActionEvent e) {
+               if (e.getActionCommand().equals("outline")) {
+                       // BH j2s SwingJS asynchronous for JavaScript; synchronous for Java
+                       _vp.getVARNAUI().showColorDialog("Choose new outline color", _an.getColor(), new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       Color c = (Color) _vp.getVARNAUI().dialogReturnValue;
+                                       if (c != null) {
+                                               _an.setColor(c);
+                                               color.setBackground(_an.getColor());
+                                               _vp.repaint();
+                                       }
+                               }
+
+                       });
+               }
+
+       }
+
+               public void itemStateChanged(ItemEvent e) {
+                       if (e.getSource()==outward)
+                       {
+                               _an.setOut(!e.getItem().equals("Outward"));
+                               _vp.repaint();
+                       }
+                       else if ((e.getSource()==type)&&(e.getItem() instanceof ChemProbAnnotation.ChemProbAnnotationType))
+                       {
+                               ChemProbAnnotation.ChemProbAnnotationType t = (ChemProbAnnotation.ChemProbAnnotationType) e.getItem();
+                               _an.setType(t);
+                               _vp.repaint();
+                       }
+                       
+               }
+       }
+
+
diff --git a/src2/fr/orsay/lri/varna/views/VueColorMapStyle.java b/src2/fr/orsay/lri/varna/views/VueColorMapStyle.java
new file mode 100644 (file)
index 0000000..6a1a836
--- /dev/null
@@ -0,0 +1,305 @@
+package fr.orsay.lri.varna.views;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Cursor;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Arrays;
+import java.util.Comparator;
+
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JColorChooser;
+import javax.swing.JComboBox;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+import javax.swing.filechooser.FileFilter;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.GradientEditorPanel;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap.NamedColorMapTypes;
+
+public class VueColorMapStyle extends JPanel implements ActionListener, ItemListener, PropertyChangeListener {
+       private VARNAPanel _vp;
+       private GradientEditorPanel _gp;
+       private JComboBox _cb; 
+       private JTextField _code; 
+       private ModeleColorMap _backup;
+       // TODO BH SwingJS note that the save dialog is never used in JavaScript 
+       private static JFileChooser fc = new JFileChooser(){
+           public void approveSelection(){
+               File f = getSelectedFile();
+               if(f.exists() && getDialogType() == SAVE_DIALOG){
+                   int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?","Existing file",JOptionPane.YES_NO_OPTION);
+                   switch(result){
+                       case JOptionPane.YES_OPTION:
+                           super.approveSelection();
+                           return;
+                       case JOptionPane.NO_OPTION:
+                           return;
+                       case JOptionPane.CLOSED_OPTION:
+                           return;
+                       case JOptionPane.CANCEL_OPTION:
+                           cancelSelection();
+                           return;
+                   }
+               }
+               super.approveSelection();
+           }        
+       };
+       
+       public VueColorMapStyle(VARNAPanel vp)
+       {
+               super();
+               _vp = vp;
+               init();
+       }
+
+       private void init()
+       {
+               JLabel gradientCaption = new JLabel("Click gradient to add new color...");
+               _gp = new GradientEditorPanel(_vp.getColorMap().clone());
+               _backup = _vp.getColorMap();
+               _gp.setPreferredSize(new Dimension(300,70));
+               _gp.addPropertyChangeListener(this);
+
+               JPanel codePanel = new JPanel();
+               JLabel codeCaption = new JLabel("Param. code: ");
+               codeCaption.setVisible(true);
+               _code = new JTextField("");
+               _code.setFont(Font.decode("Monospaced-PLAIN-12"));
+               _code.setEditable(true);
+               _code.addFocusListener(new FocusListener(){
+
+                       public void focusGained(FocusEvent arg0) {
+                                               _code.setSelectionStart(0);
+                                               _code.setSelectionEnd(_code.getText().length());
+                       }
+
+                       public void focusLost(FocusEvent arg0) {
+                       }                       
+               });             
+               _code.setVisible(false);
+               
+               NamedColorMapTypes[] palettes =  ModeleColorMap.NamedColorMapTypes.values();
+               Arrays.sort(palettes,new Comparator<ModeleColorMap.NamedColorMapTypes>(){
+                       public int compare(ModeleColorMap.NamedColorMapTypes arg0, ModeleColorMap.NamedColorMapTypes arg1) {
+                               return arg0.getId().compareTo(arg1.getId());
+                       }                       
+               });
+               Object[] finalArray = new Object[palettes.length+1];
+               int selected = -1;
+               for (int i=0;i<palettes.length;i++)
+               { 
+                       if (palettes[i].getColorMap().equals(_vp.getColorMap()))
+                       {
+                               selected = i; 
+                               //System.out.println(selected);
+                       }
+                       finalArray[i] = palettes[i]; 
+               }
+               String custom = new String("Custom...");
+               finalArray[palettes.length] = custom;
+               _cb = new JComboBox(finalArray);
+               if (selected!=-1)
+               {
+                       _cb.setSelectedIndex(selected);
+               }
+               else
+               {
+                       _cb.setSelectedItem(finalArray.length-1);
+               }
+               _cb.addItemListener(this);
+               
+               _code.setText(getTextRepresentation());
+               
+               
+               
+               FileFilter CMSFiles = new FileFilter(){
+                       public boolean accept(File f) {
+                               return f.getName().toLowerCase().endsWith(".cms") || f.isDirectory();
+                       }
+
+                       public String getDescription() {
+                               return "Color Map (*.cms) Files";
+                       }
+                       
+               };
+               fc.addChoosableFileFilter(CMSFiles);
+               fc.setFileFilter(CMSFiles);
+               
+               codePanel.setLayout(new BoxLayout(codePanel,BoxLayout.LINE_AXIS));
+               codePanel.add(codeCaption);
+               codePanel.add(_code);
+               JButton loadStyleButton = new JButton("Load");
+               loadStyleButton.addActionListener(new ActionListener(){
+                       public void actionPerformed(ActionEvent e) {
+                               if (fc.showOpenDialog(VueColorMapStyle.this)==JFileChooser.APPROVE_OPTION)
+                               {
+                                       File file = fc.getSelectedFile();
+                                       try {
+                                               FileInputStream fis = new FileInputStream(file);
+                                               byte[] data = new byte[(int) file.length()];
+                                               fis.read(data);
+                                               fis.close();
+                                               String str = new String(data).trim();
+                                               ModeleColorMap ns = ModeleColorMap.parseColorMap(str);
+                                               _gp.setColorMap(ns);
+                                               refreshCode();
+                                       } catch (FileNotFoundException e1) {
+                                               e1.printStackTrace();
+                                       } catch (IOException e1) {
+                                               e1.printStackTrace();
+                                       }
+                               }
+                       }
+                       
+               });
+               JButton saveStyleButton = new JButton("Save");
+               saveStyleButton.addActionListener(new ActionListener(){
+                       public void actionPerformed(ActionEvent e) {
+                               if (fc.showSaveDialog(VueColorMapStyle.this)==JFileChooser.APPROVE_OPTION)
+                               {
+                                       try {
+                                               PrintWriter out = new PrintWriter(fc.getSelectedFile());
+                                               out.println(_gp.getColorMap().getParamEncoding());
+                                               out.close();
+                                       } catch (FileNotFoundException e1) {
+                                               e1.printStackTrace();
+                                       } catch (IOException e1) {
+                                               e1.printStackTrace();
+                                       }
+                               }
+                       }
+                       
+               });
+               saveStyleButton.setAlignmentX(CENTER_ALIGNMENT);
+               loadStyleButton.setAlignmentX(CENTER_ALIGNMENT);
+
+               JPanel jp = new JPanel(new BorderLayout());
+               jp.add(_cb,BorderLayout.CENTER);
+               JPanel jp2 = new JPanel();
+               jp2.setLayout(new BoxLayout(jp2,BoxLayout.X_AXIS));
+               jp2.add(Box.createRigidArea(new Dimension(5,0)));
+               jp2.add(loadStyleButton);
+               jp2.add(Box.createRigidArea(new Dimension(5,0)));
+               jp2.add(saveStyleButton);
+               jp.add(jp2,BorderLayout.EAST);
+               
+               setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
+               add(jp);
+               add(Box.createVerticalStrut(10));
+               add(_gp);
+               add(gradientCaption);
+               //add(Box.createVerticalStrut(10));
+               //add(codePanel);
+       }
+       
+       public String getTextRepresentation()
+       {
+               int selected = _cb.getSelectedIndex();
+               if ((selected!=-1) && (selected<_cb.getItemCount()-1))
+               {
+                       return ((NamedColorMapTypes) _cb.getSelectedItem()).getId(); 
+               }
+               else
+               {
+                       return _gp.getColorMap().getParamEncoding();
+               }
+       }
+       
+       public void cancelChanges()
+       {
+               _vp.setColorMap(_backup);
+       }
+       
+       public ModeleColorMap getColorMap()
+       {
+               return _gp.getColorMap();
+       }
+       
+       public void actionPerformed(ActionEvent e) {
+               // TODO Auto-generated method stub
+               
+       }
+       
+       
+       private void refreshCode()
+       {
+               int selected = -1;
+               NamedColorMapTypes n = null;
+               for (int i=0;i<_cb.getItemCount()-1;i++)
+               { 
+                       Object o = _cb.getItemAt(i);
+                       if (o instanceof NamedColorMapTypes)
+                       {
+                               NamedColorMapTypes ni = (NamedColorMapTypes) o;
+                               if (ni.getColorMap().equals(_gp.getColorMap()))
+                               { 
+                                       selected = i;   n = ni;
+                               }
+                       }
+               }
+               if (selected!=-1)
+               {
+                       _code.setText(n.getId());
+               }
+               _code.setText(getTextRepresentation());
+               _vp.setColorMap(_gp.getColorMap());
+               _gp.repaint();
+       }
+
+       public void itemStateChanged(ItemEvent arg0) {
+               if (arg0.getStateChange()==ItemEvent.SELECTED)
+               {
+               Object o = arg0.getItem();
+               if (o instanceof ModeleColorMap.NamedColorMapTypes)
+               {
+                       ModeleColorMap.NamedColorMapTypes n = ((ModeleColorMap.NamedColorMapTypes) o);
+                       ModeleColorMap m = n.getColorMap().clone();
+                       m.setMinValue(_backup.getMinValue());
+                       m.setMaxValue(_backup.getMaxValue());
+                       _gp.setColorMap(m);
+                       refreshCode();
+               }
+               }
+       }
+
+       public void propertyChange(PropertyChangeEvent arg0) {
+               if (arg0.getPropertyName().equals("PaletteChanged"))
+               {
+                       _cb.setSelectedIndex(_cb.getItemCount()-1);
+                       refreshCode();
+               };
+       }
+
+
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueFont.java b/src2/fr/orsay/lri/varna/views/VueFont.java
new file mode 100644 (file)
index 0000000..7e9bd29
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Font;
+import java.awt.GraphicsEnvironment;
+
+import javax.swing.JComboBox;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+public class VueFont {
+
+       private VARNAPanel _vp;
+       private Font font;
+       private JComboBox stylesBox;
+       private JComboBox boxPolice;
+       private JPanel panel;
+       private JSlider sizeSlider;
+
+       public VueFont(VARNAPanel vp) {
+               _vp = vp;
+               init();
+               buildViewVPTitle();
+       }
+
+       public VueFont(Font f) {
+               font = f;
+               init();
+               buildViewFont();
+       }
+
+       private void init() {
+               GraphicsEnvironment ge = GraphicsEnvironment
+                               .getLocalGraphicsEnvironment();
+               String[] polices = ge.getAvailableFontFamilyNames();
+               boxPolice = new JComboBox(polices);
+
+               sizeSlider = new JSlider(JSlider.HORIZONTAL, 4, 88, 14);
+               // Turn on labels at major tick marks.
+               sizeSlider.setMajorTickSpacing(10);
+               sizeSlider.setMinorTickSpacing(5);
+               sizeSlider.setPaintTicks(true);
+               sizeSlider.setPaintLabels(true);
+
+               String[] styles = { "Plain", "Italic", "Bold" };
+               stylesBox = new JComboBox(styles);
+
+               panel = new JPanel();
+               panel.add(boxPolice);
+               panel.add(sizeSlider);
+               panel.add(stylesBox);
+       }
+
+       private void buildViewFont() {
+               boxPolice.setSelectedItem(font.getFamily());
+               sizeSlider.setValue(font.getSize());
+               stylesBox.setSelectedItem(styleIntToString(font.getStyle()));
+       }
+
+       private void buildViewVPTitle() {
+               boxPolice.setSelectedItem(_vp.getTitleFont().getFamily());
+               sizeSlider.setValue(_vp.getTitleFont().getSize());
+               stylesBox.setSelectedItem(styleIntToString(_vp.getTitleFont()
+                               .getStyle()));
+       }
+
+       public String styleIntToString(int styleInt) {
+               switch (styleInt) {
+               case Font.PLAIN:// Plain
+                       return "Plain";
+               case Font.ITALIC:// Italic
+                       return "Italic";
+               case Font.BOLD:// Bold
+                       return "Bold";
+               default:// Plain
+                       return "Plain";
+               }
+       }
+
+       public JComboBox getStylesBox() {
+               return stylesBox;
+       }
+
+       public JComboBox getBoxPolice() {
+               return boxPolice;
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public JSlider getSizeSlider() {
+               return sizeSlider;
+       }
+
+       public Font getFont() {
+               int style;
+               switch (getStylesBox().getSelectedIndex()) {
+               case 0:// Plain
+                       style = Font.PLAIN;
+                       break;
+               case 1:// Italic
+                       style = Font.ITALIC;
+                       break;
+               case 2:// Bold
+                       style = Font.BOLD;
+                       break;
+               default:// Plain
+                       style = Font.PLAIN;
+                       break;
+               }
+               return new Font((String) getBoxPolice().getSelectedItem(), style,
+                               getSizeSlider().getValue());
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueGlobalRescale.java b/src2/fr/orsay/lri/varna/views/VueGlobalRescale.java
new file mode 100644 (file)
index 0000000..02eba49
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurGlobalRescale;
+import fr.orsay.lri.varna.controlers.ControleurGlobalRotation;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+
+public class VueGlobalRescale {
+
+       private VARNAPanel _vp;
+       private JSlider rescaleSlider;
+       private JPanel panel;
+
+       public VueGlobalRescale(VARNAPanel vp) {
+               _vp = vp;
+               rescaleSlider = new JSlider(JSlider.HORIZONTAL, 1, 500, 100);
+               rescaleSlider.setMajorTickSpacing(100);
+               rescaleSlider.setPaintTicks(true);
+               rescaleSlider.setPaintLabels(true);
+               rescaleSlider.setPreferredSize(new Dimension(500, 50));
+
+               JLabel rescaleLabel = new JLabel(String.valueOf(0));
+               rescaleLabel.setPreferredSize(new Dimension(50, rescaleLabel
+                               .getPreferredSize().height));
+               rescaleSlider.addChangeListener(new ControleurSliderLabel(
+                               rescaleLabel, false));
+               rescaleSlider.addChangeListener(new ControleurGlobalRescale(this,vp));
+
+               panel = new JPanel();
+               panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel labelZ = new JLabel("Scale (%):");
+
+               panel.add(labelZ);
+               panel.add(rescaleSlider);
+               panel.add(rescaleLabel);
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public double getScale() {
+               return rescaleSlider.getValue()/100.0;
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueGlobalRotation.java b/src2/fr/orsay/lri/varna/views/VueGlobalRotation.java
new file mode 100644 (file)
index 0000000..5459d33
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurGlobalRotation;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+
+public class VueGlobalRotation {
+
+       private VARNAPanel _vp;
+       private JSlider rotationSlider;
+       private JPanel panel;
+
+       public VueGlobalRotation(VARNAPanel vp) {
+               _vp = vp;
+               rotationSlider = new JSlider(JSlider.HORIZONTAL, -360, 360, 0);
+               rotationSlider.setMajorTickSpacing(60);
+               rotationSlider.setPaintTicks(true);
+               rotationSlider.setPaintLabels(true);
+               rotationSlider.setPreferredSize(new Dimension(500, 50));
+
+               JLabel rotationLabel = new JLabel(String.valueOf(0));
+               rotationLabel.setPreferredSize(new Dimension(50, rotationLabel
+                               .getPreferredSize().height));
+               rotationSlider.addChangeListener(new ControleurSliderLabel(
+                               rotationLabel, false));
+               rotationSlider.addChangeListener(new ControleurGlobalRotation(this,vp));
+
+               panel = new JPanel();
+               panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel labelZ = new JLabel("Rotation (degrees):");
+
+               panel.add(labelZ);
+               panel.add(rotationSlider);
+               panel.add(rotationLabel);
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public double getAngle() {
+               return rotationSlider.getValue();
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueHighlightRegionEdit.java b/src2/fr/orsay/lri/varna/views/VueHighlightRegionEdit.java
new file mode 100644 (file)
index 0000000..ca01a25
--- /dev/null
@@ -0,0 +1,200 @@
+package fr.orsay.lri.varna.views;
+
+
+       import java.awt.Color;
+import java.awt.Dimension;
+       import java.awt.FlowLayout;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.ArrayList;
+
+import javax.swing.JButton;
+import javax.swing.JColorChooser;
+       import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+       import javax.swing.JPanel;
+       import javax.swing.JSlider;
+import javax.swing.JSpinner;
+import javax.swing.SpinnerNumberModel;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+
+       public class VueHighlightRegionEdit implements ChangeListener, ActionListener {
+
+               private VARNAPanel _vp;
+               private JSlider _fromSlider;
+               private JSlider _toSlider;
+               private JPanel panel;
+               private HighlightRegionAnnotation _an;
+               private static int CONTROL_HEIGHT = 50;
+               private static int TITLE_WIDTH = 70;
+               private static int CONTROL_WIDTH = 200;
+               private JButton fillShow  = new JButton();
+               private JButton outlineShow  = new JButton();
+               JSpinner rad;
+
+               public VueHighlightRegionEdit(VARNAPanel vp, HighlightRegionAnnotation an) {
+                       _an = an;
+                       _vp = vp;
+                       _toSlider = new JSlider(JSlider.HORIZONTAL, 0,vp.getRNA().getSize()-1,0);
+                       _toSlider.setMajorTickSpacing(10);
+                       _toSlider.setPaintTicks(true);
+                       _toSlider.setPaintLabels(true);
+                       _toSlider.setPreferredSize(new Dimension(CONTROL_WIDTH, CONTROL_HEIGHT));
+
+                       _fromSlider = new JSlider(JSlider.HORIZONTAL, 0,vp.getRNA().getSize()-1,0);
+                       _fromSlider.setMajorTickSpacing(10);
+                       _fromSlider.setPaintTicks(true);
+                       _fromSlider.setPaintLabels(true);
+                       _fromSlider.setPreferredSize(new Dimension(CONTROL_WIDTH, CONTROL_HEIGHT));
+
+                       _fromSlider.addChangeListener(this);
+                       _toSlider.addChangeListener(this);
+
+                       panel = new JPanel();
+                       panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+                       JPanel fromp = new JPanel();
+                       JLabel l1 = new JLabel("From: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       fromp.add(l1);
+                       fromp.add(_fromSlider);
+
+                       JPanel top = new JPanel();
+                       l1 = new JLabel("To: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       top.add(l1);
+                       top.add(_toSlider);
+
+                       JPanel outlinep = new JPanel();
+                       l1 = new JLabel("Outline color: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       outlineShow.setContentAreaFilled(false);
+                       outlineShow.setOpaque(true);
+                       outlineShow.setPreferredSize(new Dimension(CONTROL_WIDTH,CONTROL_HEIGHT));
+                       outlineShow.setBackground(an.getOutlineColor());
+                       outlineShow.addActionListener(this);
+                       outlineShow.setActionCommand("outline");
+                       outlinep.add(l1);
+                       outlinep.add(outlineShow);
+                       
+                       JPanel fillp = new JPanel();
+                       l1 = new JLabel("Fill color: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       fillShow.setContentAreaFilled(false);
+                       fillShow.setOpaque(true);
+                       fillShow.setPreferredSize(new Dimension(CONTROL_WIDTH,CONTROL_HEIGHT));
+                       fillShow.setBackground(an.getFillColor());
+                       fillShow.addActionListener(this);
+                       fillShow.setActionCommand("fill");
+                       fillp.add(l1);
+                       fillp.add(fillShow);
+                       
+                       JPanel radiusp = new JPanel();
+                       l1 = new JLabel("Radius: ");
+                       l1.setPreferredSize(new Dimension(TITLE_WIDTH,CONTROL_HEIGHT));
+                       SpinnerNumberModel jm = new SpinnerNumberModel(_an.getRadius(),1.0,50.0,0.1);
+                       rad = new JSpinner(jm);
+                       rad.setPreferredSize(new Dimension(CONTROL_WIDTH,CONTROL_HEIGHT));
+                       radiusp.add(l1);
+                       radiusp.add(rad);
+                       rad.addChangeListener(this);
+                       
+                       JPanel jp = new JPanel();
+                       jp.setLayout(new GridLayout(5,1));
+                       jp.add(fromp);
+                       jp.add(top);
+                       jp.add(outlinep);
+                       jp.add(fillp);
+                       jp.add(radiusp);
+                       panel.add(jp);
+               }
+
+               public JPanel getPanel() {
+                       return panel;
+               }
+
+               public double getAngle() {
+                       return _toSlider.getValue();
+               }
+
+               public VARNAPanel get_vp() {
+                       return _vp;
+               }
+               
+               HighlightRegionAnnotation _backup = null;
+               
+               public boolean show() {
+                       boolean accept = false;
+                       int from = _an.getMinIndex();
+                       int to = _an.getMaxIndex();
+                       _fromSlider.setValue(from);
+                       _toSlider.setValue(to );
+                       if (JOptionPane.showConfirmDialog(_vp, getPanel(),
+                                       "Edit region annotation", JOptionPane.OK_CANCEL_OPTION,
+                                       JOptionPane.PLAIN_MESSAGE) == JOptionPane.OK_OPTION) 
+                       {
+                               accept = true;
+                       } 
+                       _vp.repaint();
+                       return accept;
+               }
+
+               public void stateChanged(ChangeEvent e) {
+                       if ((e.getSource()==_toSlider)||(e.getSource()==_fromSlider))
+                       {
+                       int from  = _fromSlider.getValue(); 
+                       int to  = _toSlider.getValue(); 
+                       if (from>to)
+                       {
+                               if (e.getSource().equals(_fromSlider))
+                               {
+                                       _toSlider.setValue(from);
+                               }
+                               else if (e.getSource().equals(_toSlider))
+                               {
+                                       _fromSlider.setValue(to);
+                               }
+                       }
+                       from  = _fromSlider.getValue(); 
+                       to  = _toSlider.getValue(); 
+                       _an.setBases(_vp.getRNA().getBasesBetween(from, to));
+                       _vp.repaint();
+                       }
+                       else if (e.getSource().equals(rad))
+                       {
+                               Object val = rad.getValue();
+                               if (val instanceof Double)
+                               {                                       
+                                       _an.setRadius(((Double)val).doubleValue());
+                               }
+                       }
+                       
+               }
+
+               public void actionPerformed(ActionEvent e) {
+                       if (e.getActionCommand().equals("outline"))
+                       {
+                         Color c = JColorChooser.showDialog(getPanel(), "Choose new outline color", _an.getOutlineColor());
+                         if (c!= null)
+                         {   _an.setOutlineColor(c);  }
+                       }
+                       else if (e.getActionCommand().equals("fill"))
+                       {
+                                 Color c = JColorChooser.showDialog(getPanel(), "Choose new fill color", _an.getFillColor());
+                                 if (c!= null)
+                                 {  _an.setFillColor(c); }
+                       }
+                       outlineShow.setBackground(_an.getOutlineColor());
+                       fillShow.setBackground(_an.getFillColor());
+                       _vp.repaint();
+                       
+               }
+       }
+
diff --git a/src2/fr/orsay/lri/varna/views/VueJPEG.java b/src2/fr/orsay/lri/varna/views/VueJPEG.java
new file mode 100644 (file)
index 0000000..e6741a9
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+public class VueJPEG {
+       private JSlider qualitySlider;
+       private JSlider scaleSlider;
+       private JPanel panel;
+
+       // Turn on labels at major tick marks.
+//     public VueJPEG() {
+//     }
+
+       public VueJPEG(boolean showQuality, boolean showScale) {
+               qualitySlider = new JSlider(JSlider.HORIZONTAL, 10, 100, 75);
+               qualitySlider.setMajorTickSpacing(5);
+               qualitySlider.setPaintTicks(true);
+               qualitySlider.setPaintLabels(true);
+               qualitySlider.setPreferredSize(new Dimension(400, 50));
+               scaleSlider = new JSlider(JSlider.HORIZONTAL, 0, 600, 100);
+               scaleSlider.setPreferredSize(new Dimension(400, 50));
+               scaleSlider.setMajorTickSpacing(100);
+               scaleSlider.setPaintTicks(true);
+               scaleSlider.setPaintLabels(true);
+               panel = new JPanel();
+               JPanel pup = new JPanel();
+               JPanel pdown = new JPanel();
+               int nbPanels = 0;
+               if (showQuality)
+                       nbPanels++;
+               if (showScale)
+                       nbPanels++;
+               panel.setLayout(new GridLayout(nbPanels, 1));
+               pup.setLayout(new FlowLayout(FlowLayout.LEFT));
+               pdown.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel lseq = new JLabel("Resolution:");
+               JLabel lstr = new JLabel("Quality:");
+               pup.add(lseq);
+               pup.add(scaleSlider);
+               pdown.add(lstr);
+               pdown.add(qualitySlider);
+               if (showQuality) {
+                       panel.add(pup);
+               }
+               if (showScale) {
+                       panel.add(pdown);
+               }
+       }
+
+       public JSlider getQualitySlider() {
+               return qualitySlider;
+       }
+
+       public JSlider getScaleSlider() {
+               return scaleSlider;
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueListeAnnotations.java b/src2/fr/orsay/lri/varna/views/VueListeAnnotations.java
new file mode 100644 (file)
index 0000000..6fecd1d
--- /dev/null
@@ -0,0 +1,249 @@
+/*
+ * VARNA is a tool for the automated drawing, visualization and annotation
+ * of the secondary structure of RNA, designed as a companion software for
+ * web servers and databases. Copyright (C) 2008 Kevin Darty, Alain Denise
+ * and Yann Ponty. electronic mail : Yann.Ponty@lri.fr paper mail : LRI, bat
+ * 490 Université Paris-Sud 91405 Orsay Cedex France
+ * 
+ * This file is part of VARNA version 3.1. VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+ * 
+ * VARNA version 3.1 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 VARNA version 3.1. If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.filechooser.FileFilter;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.AnnotationTableModel;
+import fr.orsay.lri.varna.controlers.ControleurTableAnnotations;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+
+/**
+ * a view for all annoted texts on the VARNAPanel
+ * 
+ * @author Darty@lri.fr
+ * 
+ */
+public class VueListeAnnotations extends JPanel {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       /**
+        * if this view is for removing annoted texts
+        */
+       public static final int REMOVE = 0;
+       /**
+        * if this view is for editing annoted texts
+        */
+       public static final int EDIT = 1;
+
+       private VARNAPanel _vp;
+       private ArrayList<Object> data;
+       private JTable table;
+       private int type;
+       private AnnotationTableModel specialTableModel;
+       // BH SwingJS - this is never used in JavaScript
+       private static JFileChooser fc = new JFileChooser(){
+           public void approveSelection(){
+               File f = getSelectedFile();
+               if(f.exists() && getDialogType() == SAVE_DIALOG){
+                   int result = JOptionPane.showConfirmDialog(this,"The file exists, overwrite?","Existing file",JOptionPane.YES_NO_OPTION);
+                   switch(result){
+                       case JOptionPane.YES_OPTION:
+                           super.approveSelection();
+                           return;
+                       case JOptionPane.NO_OPTION:
+                           return;
+                       case JOptionPane.CLOSED_OPTION:
+                           return;
+                       case JOptionPane.CANCEL_OPTION:
+                           cancelSelection();
+                           return;
+                   }
+               }
+               super.approveSelection();
+           }        
+       };
+
+
+       /**
+        * creates the view
+        * 
+        * @param vp
+        * @param type
+        *            (REMOVE or EDIT)
+        */
+       public VueListeAnnotations(VARNAPanel vp, int type) {
+               super(new BorderLayout());
+               this.type = type;
+               _vp = vp;
+               data = new ArrayList<Object>();
+               data.addAll(_vp.getListeAnnotations());
+               data.addAll(_vp.getRNA().getHighlightRegion());
+               data.addAll(_vp.getRNA().getChemProbAnnotations());
+               createView();
+       }
+
+       private void createView() {
+               specialTableModel = new AnnotationTableModel(data);
+               table = new JTable(specialTableModel);
+               ControleurTableAnnotations ctrl = new ControleurTableAnnotations(table,
+                               _vp, type);
+               table.addMouseListener(ctrl);
+               table.addMouseMotionListener(ctrl);
+               // table.setPreferredScrollableViewportSize(new Dimension(500, 100));
+               // TODO: Find equivalent in JRE 1.5
+               // table.setFillsViewportHeight(true);
+               // Create the scroll pane and add the table to it.
+               JScrollPane scrollPane = new JScrollPane(table);
+
+               add(scrollPane, BorderLayout.CENTER);
+               
+               FileFilter CPAFiles = new FileFilter(){
+                       public boolean accept(File f) {
+                               return f.getName().toLowerCase().endsWith(".cpa") || f.isDirectory();
+                       }
+
+                       public String getDescription() {
+                               return "Chemical Probing Annotations (*.cpa) Files";
+                       }
+                       
+               };
+               fc.addChoosableFileFilter(CPAFiles);
+               fc.setFileFilter(CPAFiles);
+
+               
+               JButton loadStyleButton = new JButton("Load");
+               loadStyleButton.addActionListener(new ActionListener(){
+                       public void actionPerformed(ActionEvent e) {
+                               if (fc.showOpenDialog(VueListeAnnotations.this)==JFileChooser.APPROVE_OPTION)
+                               {
+                                       File file = fc.getSelectedFile();
+                                       try {
+                                               BufferedReader br = new BufferedReader(new FileReader(file));
+                                               String s = br.readLine();
+                                               while(s != null)
+                                               {
+                                                       if (s.startsWith(TextAnnotation.HEADER_TEXT))
+                                                       s = br.readLine();
+                                               }
+                                               // TODO
+                                       } catch (FileNotFoundException e1) {
+                                               e1.printStackTrace();
+                                       } catch (IOException e1) {
+                                               e1.printStackTrace();
+                                       }
+                               }
+                       }
+                       
+               });
+               JButton saveStyleButton = new JButton("Save");
+               saveStyleButton.addActionListener(new ActionListener(){
+                       public void actionPerformed(ActionEvent e) {
+                               if (fc.showSaveDialog(VueListeAnnotations.this)==JFileChooser.APPROVE_OPTION)
+                               {
+                                       try {
+                                               PrintWriter out = new PrintWriter(fc.getSelectedFile());
+                                               // TODO out.println(_gp.getColorMap().getParamEncoding());
+                                               out.close();
+                                       } catch (FileNotFoundException e1) {
+                                               e1.printStackTrace();
+                                       } catch (IOException e1) {
+                                               e1.printStackTrace();
+                                       }
+                               }
+                       }
+                       
+               });
+               saveStyleButton.setAlignmentX(CENTER_ALIGNMENT);
+               loadStyleButton.setAlignmentX(CENTER_ALIGNMENT);
+
+               JPanel jp2 = new JPanel();
+               BoxLayout bl = new BoxLayout(jp2, BoxLayout.X_AXIS);
+               jp2.setLayout(bl);
+               jp2.setAlignmentX(CENTER_ALIGNMENT);
+               jp2.add(loadStyleButton);
+               jp2.add(Box.createRigidArea(new Dimension(5,0)));
+               jp2.add(saveStyleButton);
+               this.add(jp2,BorderLayout.SOUTH);
+
+               
+
+               UIvueListeAnnotations();
+       }
+
+       /**
+        * Create the GUI and show it. For thread safety, this method should be
+        * invoked from the event-dispatching thread.
+        */
+       public void UIvueListeAnnotations() {
+               JComponent newContentPane = this;
+               newContentPane.setOpaque(true); 
+               JOptionPane.showMessageDialog(_vp, newContentPane,
+                               "Annotation edition", JOptionPane.PLAIN_MESSAGE);
+       }
+
+       public ArrayList<Object> getData() {
+               return data;
+       }
+
+       public void setData(ArrayList<Object> data) {
+               this.data = data;
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public JTable getTable() {
+               return table;
+       }
+
+       public void setTable(JTable table) {
+               this.table = table;
+       }
+
+       public AnnotationTableModel getSpecialTableModel() {
+               return specialTableModel;
+       }
+
+       public void setSpecialTableModel(AnnotationTableModel specialTableModel) {
+               this.specialTableModel = specialTableModel;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueLoadColorMapValues.java b/src2/fr/orsay/lri/varna/views/VueLoadColorMapValues.java
new file mode 100644 (file)
index 0000000..3bfb27a
--- /dev/null
@@ -0,0 +1,116 @@
+package fr.orsay.lri.varna.views;
+
+import java.awt.CardLayout;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+import javax.swing.ButtonGroup;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JFileChooser;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.JTextField;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+public class VueLoadColorMapValues extends JPanel implements ActionListener {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = -1648400107478203724L;
+       VARNAPanel _vp;
+       
+  public VueLoadColorMapValues(VARNAPanel vp)
+  {
+         _vp = vp;
+         init();
+  }
+  JRadioButton urlCB = new JRadioButton("URL"); 
+  JRadioButton fileCB = new JRadioButton("File");
+  JPanel urlAux = new JPanel();
+  JPanel fileAux = new JPanel();
+  CardLayout l = new CardLayout();
+  JPanel input = new JPanel();
+  JTextField urlTxt = new JTextField(); 
+  JTextField fileTxt = new JTextField(); 
+  JButton load = new JButton("Choose file");
+  
+  private void init()
+  {
+         setLayout(new GridLayout(2,1));
+         JPanel choice = new JPanel();
+         urlCB.addActionListener(this);
+         fileCB.addActionListener(this);
+         ButtonGroup group = new ButtonGroup();
+         group.add(urlCB);
+         group.add(fileCB);
+         choice.add(new JLabel("Choose input source:"));
+         choice.add(urlCB);
+         choice.add(fileCB);
+         input.setLayout(l);
+         urlTxt.setPreferredSize(new Dimension(300,30));
+         fileTxt.setPreferredSize(new Dimension(300,30));
+         urlAux.add(urlTxt);
+         fileAux.add(fileTxt);
+         fileAux.add(load);
+         input.add(fileAux,"file");
+         input.add(urlAux,"url");
+         group.setSelected(fileCB.getModel(), true);
+         load.addActionListener(this);
+         this.add(choice);
+         this.add(input);
+  }
+
+public void actionPerformed(ActionEvent e) {
+       if (e.getSource() instanceof JRadioButton)
+       {
+               if (urlCB.isSelected())
+               {
+                       l.show(input, "url");
+               }
+               else
+               {
+                       l.show(input, "file");
+               }
+       }
+       else if (e.getSource() instanceof JButton)
+       {
+               JFileChooser fc = new JFileChooser();
+               if (fc.showOpenDialog(_vp) == JFileChooser.APPROVE_OPTION)
+               {
+                       this.fileTxt.setText(fc.getSelectedFile().getAbsolutePath());
+               }
+       }
+}
+
+public Reader getReader() throws IOException
+{
+       if (urlCB.isSelected())
+       {
+               URL url = new URL(urlTxt.getText());
+               URLConnection connexion = url.openConnection();
+               connexion.setUseCaches(false);
+               InputStream r = connexion.getInputStream();
+               return new InputStreamReader(r);
+       }
+       else
+       {
+         return new FileReader(fileTxt.getText());
+       }
+       
+}
+
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueManualInput.java b/src2/fr/orsay/lri/varna/views/VueManualInput.java
new file mode 100644 (file)
index 0000000..07aef4a
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Font;
+import java.awt.GridLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+
+import fr.orsay.lri.varna.VARNAPanel;
+
+
+public class VueManualInput {
+
+       private VARNAPanel _vp;
+       private JPanel panel;
+       private JTextField tseq, tstr;
+
+       public VueManualInput(VARNAPanel vp) {
+               _vp = vp;
+               buildView();
+       }
+
+       private void buildView() {
+               panel = new JPanel();
+               JPanel pup = new JPanel();
+               JPanel pdown = new JPanel();
+               panel.setLayout(new GridLayout(2, 1));
+               pup.setLayout(new FlowLayout(FlowLayout.LEFT));
+               pdown.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               Font _textFieldsFont = Font.decode("MonoSpaced-PLAIN-12");
+
+               JLabel lseq = new JLabel("Sequence:");
+               tseq = new JTextField(_vp.getRNA().getListeBasesToString());
+               JLabel lstr = new JLabel("Structure:");
+               tstr = new JTextField(_vp.getRNA().getStructDBN());
+               tstr
+                               .setPreferredSize(new Dimension(400,
+                                               tstr.getPreferredSize().height));
+               tseq
+                               .setPreferredSize(new Dimension(400,
+                                               tseq.getPreferredSize().height));
+               tstr.setFont(_textFieldsFont);
+               tseq.setFont(_textFieldsFont);
+               pup.add(lseq);
+               pup.add(tseq);
+               pdown.add(lstr);
+               pdown.add(tstr);
+               panel.add(pup);
+               panel.add(pdown);
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public void setPanel(JPanel panel) {
+               this.panel = panel;
+       }
+
+       public JTextField getTseq() {
+               return tseq;
+       }
+
+       public JTextField getTstr() {
+               return tstr;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueMenu.java b/src2/fr/orsay/lri/varna/views/VueMenu.java
new file mode 100644 (file)
index 0000000..f7ee43f
--- /dev/null
@@ -0,0 +1,495 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Universit� Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Font;
+import java.awt.Point;
+import java.awt.event.KeyEvent;
+import java.util.ArrayList;
+
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JComponent;
+import javax.swing.JLabel;
+import javax.swing.JMenu;
+import javax.swing.JMenuItem;
+import javax.swing.JPopupMenu;
+import javax.swing.JSeparator;
+import javax.swing.KeyStroke;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurMenu;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VueMenu extends JPopupMenu {
+       /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+
+       private VARNAPanel _vp;
+
+       private ControleurMenu _controlerMenu;
+
+       private JCheckBoxMenuItem _itemOptionSpecialBaseColored = new JCheckBoxMenuItem(
+                       "Custom colored", false);
+       private JCheckBoxMenuItem _itemShowWarnings = new JCheckBoxMenuItem(
+                       "Show warnings", false);
+       private JCheckBoxMenuItem _itemDrawBackbone = new JCheckBoxMenuItem(
+                       "Draw backbone", true);
+       private JCheckBoxMenuItem _itemOptionGapsBaseColored = new JCheckBoxMenuItem(
+                       "Custom colored", false);
+       private JCheckBoxMenuItem _itemOptionBondsColored = new JCheckBoxMenuItem(
+                       "Use base color for base-pairs", false);
+       private JCheckBoxMenuItem _itemShowNCBP = new JCheckBoxMenuItem(
+                       "Show non-canonical BPs", true);
+       private JCheckBoxMenuItem _itemShowOnlyPlanar = new JCheckBoxMenuItem(
+                       "Hide tertiary BPs", false);
+       private JCheckBoxMenuItem _itemFlatExteriorLoop = new JCheckBoxMenuItem(
+                       "Flat exterior loop", false);
+       
+       private JCheckBoxMenuItem _itemShowColorMap = new JCheckBoxMenuItem(
+                       "Show color map", false);
+       private JMenuItem _dashBasesColor;
+
+       private ArrayList<JComponent> _disabled = new ArrayList<JComponent>();
+
+       private JMenuItem _rotation;
+       private JMenuItem _bpHeightIncrement;
+
+       private Point _spawnOrigin = new Point(-1,-1);
+       
+       public VueMenu(VARNAPanel vp) {
+               _vp = vp;
+               _controlerMenu = new ControleurMenu(_vp, this);
+       }
+
+       private void addTitle(String title, boolean keep) {
+               // TOD BH SwingJS -- this should not be necessary
+               JSeparator sep = new JPopupMenu.Separator(); // BH SWingJS needs JPopupMenu.Separator
+               //JSeparator sep = new JSeparator();
+               JMenuItem titleItem = new JMenuItem(" " + title);//BH SwingJS was JLabel -- need to be able to do this.
+               // titleItem.setAlignmentX(0.5f);
+               Font previousFont = titleItem.getFont();
+               Font futureFont = previousFont.deriveFont(Font.BOLD).deriveFont(
+                               (float) previousFont.getSize() + 1.0f);
+
+               titleItem.setFont(futureFont);
+               Color current = titleItem.getForeground();
+               Color future = current.brighter().brighter();
+               // titleItem.setBackground(future);
+               titleItem.setForeground(future);
+               add(titleItem);
+               add(sep);
+               if (!keep) {
+                       _disabled.add(sep);
+                       _disabled.add(titleItem);
+               }
+       }
+       
+       private void configMenuItem(JMenuItem mi, String command, String keyStroke, Container par)
+       { configMenuItem(mi,command,keyStroke,par,false); }
+
+       private void configMenuItem(JMenuItem mi, String command, String keyStroke, Container par, boolean disabled)
+       { 
+               mi.setActionCommand(command);
+               mi.addActionListener(_controlerMenu);
+               if (keyStroke!=null)
+                       if (!keyStroke.equals(""))
+                               mi.setAccelerator(KeyStroke.getKeyStroke(keyStroke));
+               if (disabled)
+               { _disabled.add(mi);}
+               par.add(mi);
+       }
+       
+       private JMenuItem createMenuItem(String caption, String command, String keyStroke, Container par, boolean disabled)
+       {
+               JMenuItem mi = new JMenuItem(caption);
+               configMenuItem(mi, command,keyStroke, par, disabled);
+               return mi;
+       }
+
+       private JMenuItem createMenuItem(String caption, String command, String keyStroke, Container par)
+       { return createMenuItem(caption, command, keyStroke, par,false); }
+
+
+       public void updateDialog() {
+               for (int i = 0; i < _disabled.size(); i++) {
+                       JComponent j = _disabled.get(i);
+                       j.setVisible(_vp.isModifiable());
+               }
+               _itemOptionSpecialBaseColored.setState(_vp.getColorSpecialBases());
+               _itemShowWarnings.setState(_vp.getShowWarnings());
+               _itemOptionGapsBaseColored.setState(_vp.getColorGapsBases());
+               _itemOptionGapsBaseColored.setEnabled(_vp.isComparisonMode());
+               _dashBasesColor.setEnabled(_vp.isComparisonMode());
+               
+               _rotation.setEnabled(_vp.getDrawMode() != RNA.DRAW_MODE_LINEAR);
+               _bpHeightIncrement.setEnabled(_vp.getDrawMode() == RNA.DRAW_MODE_LINEAR);
+
+               _itemOptionBondsColored.setState(_vp.getUseBaseColorsForBPs());
+               _itemShowNCBP.setState(_vp.getShowNonCanonicalBP());
+               _itemShowOnlyPlanar.setState(!_vp.getShowNonPlanarBP());
+               _itemShowColorMap.setState(_vp.getColorMapVisible());
+               _itemFlatExteriorLoop.setState(_vp.getFlatExteriorLoop());
+               _itemFlatExteriorLoop.setEnabled(_vp.getDrawMode() == RNA.DRAW_MODE_RADIATE);
+       }
+
+       /**
+        * Builds the popup menu
+        */
+       public void buildPopupMenu() {
+               addTitle("File", true);
+               fileMenu();
+               exportMenu();
+               createMenuItem("Print...", "print", "control P", this);
+               addSeparator();
+
+               addTitle("Display", true);
+               viewMenu();
+               displayMenu();
+               //JSeparator sep = new JSeparator();
+               // TODO BH SwingJS - this should not be necessary
+               JSeparator sep = new JPopupMenu.Separator(); // BH SWingJS needs JPopupMenu.Separator
+               add(sep);
+               _disabled.add(sep);
+
+               addTitle("Edit", false);
+               editRNAMenu();
+               redrawMenu();
+               colorClassesMenu();
+               annotationMenu();
+               _disabled.add(_itemShowNCBP);
+               _disabled.add(_itemShowOnlyPlanar);
+               aboutMenu();
+       }
+
+       private void annotationMenu() {
+               JMenu submenuAnnotations = new JMenu("Annotations");
+               JMenu addAnnotations = new JMenu("New");
+               createMenuItem("Here", "annotationsaddPosition", "", addAnnotations);
+               createMenuItem("Base", "annotationsaddBase", "", addAnnotations);
+               createMenuItem("Loop", "annotationsaddLoop", "", addAnnotations);
+               createMenuItem("Helix", "annotationsaddHelix", "", addAnnotations);
+               //JSeparator sep = new JSeparator();
+               JSeparator sep = new JPopupMenu.Separator(); // BH SWingJS needs JPopupMenu.Separator
+
+               addAnnotations.add(sep);
+               createMenuItem("Region", "annotationsaddRegion", "", addAnnotations);
+               createMenuItem("Chem. prob.", "annotationsaddChemProb", "", addAnnotations);
+               submenuAnnotations.add(addAnnotations);
+               createMenuItem("Edit from list...", "annotationsedit", "", submenuAnnotations);
+               createMenuItem("Remove from list...", "annotationsremove", "", submenuAnnotations);
+               submenuAnnotations.addSeparator();
+               createMenuItem("Auto 5'/3'", "annotationsautoextremites", "control alt Q", submenuAnnotations);
+               createMenuItem("Auto helices", "annotationsautohelices", "control Q", submenuAnnotations);
+               createMenuItem("Auto interior loops", "annotationsautointerior", "alt shift Q", submenuAnnotations);
+               createMenuItem("Auto terminal loops", "annotationsautoterminal", "control shift Q", submenuAnnotations);
+               add(submenuAnnotations);
+       }
+
+       private void fileMenu() {
+               createMenuItem("New...", "userInput", "control N", this,true);
+               createMenuItem("Open...", "file", "control O", this,true);
+               createMenuItem("Save...", "saveas", "control S", this,true);
+               JMenu submenuSave = new JMenu("Save as");
+               createMenuItem("DBN (Vienna)", "dbn", "", submenuSave);
+               createMenuItem("BPSEQ", "bpseq", "", submenuSave);
+               createMenuItem("CT", "ct", "", submenuSave);
+               add(submenuSave);
+       }
+
+       private void exportMenu() {
+               // Export menu
+               JMenu submenuExport = new JMenu("Export");
+               createMenuItem("SVG", "svg", "", submenuExport);
+               createMenuItem("PGF/TIKZ", "tikz", "", submenuExport);
+               createMenuItem("XFIG", "xfig", "", submenuExport);
+               submenuExport.addSeparator();
+               createMenuItem("EPS", "eps", "", submenuExport);
+               submenuExport.addSeparator();
+               createMenuItem("PNG", "png", "", submenuExport);
+               createMenuItem("JPEG", "jpeg", "", submenuExport);
+               add(submenuExport);
+       }
+
+
+       private void displayMenu() {
+               
+               // SubMenu Base-pairs
+               JMenu subMenuBasePairs = new JMenu("Base Pairs");
+               createMenuItem("BP style...", "bpstyle", "control shift P", subMenuBasePairs);
+               configMenuItem(_itemShowNCBP, "shownc", "control W", subMenuBasePairs);
+               configMenuItem(_itemShowOnlyPlanar, "shownp", "control E", subMenuBasePairs);
+               // SubMenu Non standard Bases
+               JMenu subMenuNSBases = new JMenu("Non-standard bases");
+               configMenuItem(_itemOptionSpecialBaseColored, "specialbasecolored", "control J", subMenuNSBases);
+               createMenuItem("Color", "specialBasesColor", "control shift J", subMenuNSBases);
+               // SubMenu Gaps Bases
+               JMenu subMenuGapsBases = new JMenu("'Gaps' bases");
+               configMenuItem(_itemOptionGapsBaseColored, "dashbasecolored", "control D", subMenuGapsBases);           
+               _dashBasesColor = createMenuItem("Color", "dashBasesColor", "control shift D", subMenuGapsBases);
+               // Removable separator 
+               //JSeparator sep = new JSeparator();
+               JSeparator sep = new JPopupMenu.Separator(); // BH SWingJS needs JPopupMenu.Separator
+               _disabled.add(sep);
+               
+               // Style menu
+               JMenu submenuStyle = new JMenu("RNA style");
+               createMenuItem("Toggle draw bases", "gaspin", "alt G", submenuStyle,true);
+               submenuStyle.add(subMenuBasePairs);
+               submenuStyle.addSeparator();
+               submenuStyle.add(subMenuNSBases);
+               submenuStyle.add(subMenuGapsBases);
+               submenuStyle.add(sep);
+               createMenuItem("Backbone color", "backbone", "control K", submenuStyle,true);
+               configMenuItem(_itemDrawBackbone, "showbackbone", "alt B", submenuStyle);
+               
+               // Submenu Title
+               JMenu submenuTitle = new JMenu("Title");                
+               createMenuItem("Set Title", "setTitle", "control T", submenuTitle, true);
+               createMenuItem("Font", "titleDisplay", "control shift T", submenuTitle, true);
+               createMenuItem("Color", "titleColor", "control alt T", submenuTitle, true);
+               _disabled.add(submenuTitle);
+
+               // Color map menu
+               JMenu submenuColorMap = new JMenu("Color map");
+               configMenuItem(_itemShowColorMap, "toggleshowcolormap", "control shift L", submenuColorMap, false);
+               createMenuItem("Caption", "colormapcaption", "control shift C", submenuColorMap,true);
+               createMenuItem("Style...", "colormapstyle", "control L", submenuColorMap,false);
+               submenuColorMap.addSeparator();
+               createMenuItem("Edit values...", "colormapvalues", "shift L", submenuColorMap,true);
+               createMenuItem("Load values...", "colormaploadvalues", "control shift K", submenuColorMap,true);
+               _disabled.add(submenuColorMap);
+               
+               // Menu Misc
+               JMenu submenuMisc = new JMenu("Misc");
+               createMenuItem("Num. period.", "numPeriod", "control M", submenuMisc);
+               createMenuItem("Background color", "background", "control G", submenuMisc);
+               submenuMisc.add(submenuTitle);
+               
+               // Main menu
+               add(submenuStyle);              
+               add(submenuColorMap);
+               add(submenuMisc);
+
+       }
+       
+       private void editRNAMenu()
+       {
+               createMenuItem("Bases...","editallbases","",this,true);
+               createMenuItem("BasePairs...","editallbps","",this,true);
+       }
+
+       private void redrawMenu() {
+               JMenu submenuRedraw = new JMenu("Redraw");
+               _disabled.add(submenuRedraw);
+
+               JMenu submenuAlgorithms = new JMenu("Algorithm");
+               _disabled.add(submenuAlgorithms);
+
+               createMenuItem("Linear","line","control 1",submenuAlgorithms,true);
+               createMenuItem("Circular","circular","control 2",submenuAlgorithms,true);
+               createMenuItem("Radiate","radiate","control 3",submenuAlgorithms,true);
+               createMenuItem("NAView","naview","control 4",submenuAlgorithms,true);
+               //createMenuItem("VARNAView","varnaview","control 5",submenuAlgorithms,true);
+               //createMenuItem("MOTIFView","motifview","control 6",submenuAlgorithms,true);
+               submenuRedraw.add(submenuAlgorithms);
+               
+               // Sets the height increment in LINEAR_MODE type of drawing
+               _bpHeightIncrement = createMenuItem("BP height increment","bpheightincrement","control H",submenuRedraw);
+               configMenuItem(_itemFlatExteriorLoop, "flat", "control F", submenuRedraw, true);
+
+               // Item pour le r�glage de l'espace entre chaques bases
+               createMenuItem("Space between bases","spaceBetweenBases","control shift S",submenuRedraw,true);         
+               createMenuItem("Reset","reset","control shift R",submenuRedraw,true);           
+
+               add(submenuRedraw);
+       }
+
+       @SuppressWarnings("unused")
+       private void warningMenu() {
+               // Menu showWarning
+               configMenuItem(_itemShowWarnings, "showwarnings", "", this, true);
+       }
+
+       private void viewMenu() {
+               // View menu
+               JMenu submenuView = new JMenu("View");
+
+               // Zoom submenu
+               JMenu zoomDisplay = new JMenu("Zoom");
+               createMenuItem("25%","zoom25","",zoomDisplay);
+               createMenuItem("50%","zoom50","",zoomDisplay);
+               createMenuItem("100%","zoom100","",zoomDisplay);
+               createMenuItem("150%","zoom150","",zoomDisplay);
+               createMenuItem("200%","zoom200","",zoomDisplay);
+               createMenuItem("Custom","zoom","control Z",zoomDisplay);
+               submenuView.add(zoomDisplay);           
+               _rotation = createMenuItem("Rotation...","rotation","control R",submenuView);
+               createMenuItem("Rescale...","rescale","",submenuView);
+               submenuView.addSeparator();             
+               createMenuItem("Border size","borderSize","control B",submenuView);
+               
+               add(submenuView);
+
+       }
+
+       JMenu _subMenuBases;
+
+       private Component _selectionMenuIndex = null;
+
+       public void addSelectionMenu(JMenuItem s) {
+               _selectionMenuIndex = s;
+               _disabled.add(s);
+               insert(s, getComponentCount() - 2);
+       }
+
+       public void removeSelectionMenu() {
+               if (_selectionMenuIndex != null) {
+                       this.remove(_selectionMenuIndex);
+                       _selectionMenuIndex = null;
+               }
+       }
+
+       private void colorClassesMenu() {
+               // Menu Bases
+               _subMenuBases = new JMenu("Colors");
+               _disabled.add(_subMenuBases);
+               createMenuItem("By Base","eachKind","control U",_subMenuBases,true);
+               createMenuItem("By BP","eachCouple","shift U",_subMenuBases,true);
+               createMenuItem("By Position","eachBase","alt U",_subMenuBases,true);
+               add(_subMenuBases);
+       }
+
+       /**
+        * add default color options to a menu
+        */
+       public void addColorOptions(JMenu submenu) {
+               createMenuItem("Fill Color",submenu.getActionCommand() + ",InnerColor","",submenu,true);
+               createMenuItem("Stroke Color",submenu.getActionCommand() + ",OutlineColor","",submenu,true);
+               createMenuItem("Label Color",submenu.getActionCommand() + ",NameColor","",submenu,true);                
+               submenu.addSeparator();
+               createMenuItem("BP Color",submenu.getActionCommand() + ",BPColor","",submenu,true);             
+               createMenuItem("BP Thickness",submenu.getActionCommand() + ",BPThickness","",submenu,true);             
+               submenu.addSeparator();
+               createMenuItem("Number Color",submenu.getActionCommand() + ",NumberColor","",submenu,true);             
+       }
+
+       private void aboutMenu() {
+               addSeparator();
+               createMenuItem("About VARNA", "about", "control A", this);
+       }
+
+       public void addAnnotationMenu(JMenu menu) {
+               addAnnotationMenu(menu, false);
+       }       
+       
+       public void addAnnotationMenu(JMenu menu, boolean existingAnnot) {
+               String title = "Annotation";
+               if (existingAnnot)
+               {
+                       String debut = "";
+                       String texte = _vp.get_selectedAnnotation().getTexte();
+                       if (texte.length() < 5)
+                               debut = texte;
+                       else
+                               debut = texte.substring(0, 5) + "...";
+                       title = "Annotation: " + debut;                 
+               }
+               JMenu menuAnnotation = new JMenu(title);
+               if (!existingAnnot)
+                       createMenuItem("Add",menu.getActionCommand() + "annotationadd","",menuAnnotation,true);         
+               createMenuItem("Edit",menu.getActionCommand() + "annotationedit","",menuAnnotation,true);               
+               createMenuItem("Remove",menu.getActionCommand() + "annotationremove","",menuAnnotation,true);           
+               menu.add(menuAnnotation);
+       }       
+       
+       
+       public static long getSerialVersionUID() {
+               return serialVersionUID;
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public ControleurMenu get_controleurMenu() {
+               return _controlerMenu;
+       }
+
+       public JCheckBoxMenuItem get_itemOptionSpecialBaseColored() {
+               return _itemOptionSpecialBaseColored;
+       }
+
+       public JCheckBoxMenuItem get_itemShowWarnings() {
+               return _itemShowWarnings;
+       }
+
+       public JCheckBoxMenuItem get_itemOptionDashBaseColored() {
+               return _itemOptionGapsBaseColored;
+       }
+
+       public void set_controleurMenu(ControleurMenu menu) {
+               _controlerMenu = menu;
+       }
+
+       public void set_itemOptionSpecialBaseColored(
+                       JCheckBoxMenuItem optionSpecialBaseColored) {
+               _itemOptionSpecialBaseColored = optionSpecialBaseColored;
+       }
+
+       public void set_itemShowWarnings(JCheckBoxMenuItem showWarnings) {
+               _itemShowWarnings = showWarnings;
+       }
+
+       public void set_itemOptionDashBaseColored(
+                       JCheckBoxMenuItem optionDashBaseColored) {
+               _itemOptionGapsBaseColored = optionDashBaseColored;
+       }
+
+       public JMenuItem get_rotation() {
+               return _rotation;
+       }
+
+       public void set_rotation(JMenuItem _rotation) {
+               this._rotation = _rotation;
+       }
+
+       public JCheckBoxMenuItem get_itemOptionBondsColored() {
+               return _itemOptionBondsColored;
+       }
+
+       public void set_itemOptionBondsColored(JCheckBoxMenuItem optionBondsColored) {
+               _itemOptionBondsColored = optionBondsColored;
+       }
+
+
+       public void show(Component invoker,int x,int y) {
+                _spawnOrigin = new Point(x,y);
+                super.show(invoker,x,y); 
+        }
+       
+       public Point getSpawnPoint()
+       {
+               return _spawnOrigin ;
+       }
+
+}
\ No newline at end of file
diff --git a/src2/fr/orsay/lri/varna/views/VueNumPeriod.java b/src2/fr/orsay/lri/varna/views/VueNumPeriod.java
new file mode 100644 (file)
index 0000000..e092304
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurNumPeriod;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+
+public class VueNumPeriod {
+       private VARNAPanel _vp;
+       private JPanel panel;
+       private JSlider numPeriodSlider;
+
+       public VueNumPeriod(VARNAPanel vp) {
+               _vp = vp;
+               panel = new JPanel();
+
+               int maxPeriod = _vp.getRNA().get_listeBases().size();
+               numPeriodSlider = new JSlider(JSlider.HORIZONTAL, 1, maxPeriod, Math
+                               .min(_vp.getNumPeriod(), maxPeriod));
+               // Turn on labels at major tick marks.
+               numPeriodSlider.setMajorTickSpacing(10);
+               numPeriodSlider.setMinorTickSpacing(5);
+               numPeriodSlider.setPaintTicks(true);
+               numPeriodSlider.setPaintLabels(true);
+
+               JLabel numLabel = new JLabel(String.valueOf(_vp.getNumPeriod()));
+               numLabel.setPreferredSize(new Dimension(50,
+                               numLabel.getPreferredSize().height));
+               numPeriodSlider.addChangeListener(new ControleurSliderLabel(numLabel,
+                               false));
+               numPeriodSlider.addChangeListener(new ControleurNumPeriod(this));
+
+               panel = new JPanel();
+               panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel labelS = new JLabel("NumPeriod:");
+
+               panel.add(labelS);
+               panel.add(numPeriodSlider);
+               panel.add(numLabel);
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public int getNumPeriod() {
+               return numPeriodSlider.getValue();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueRNAList.java b/src2/fr/orsay/lri/varna/views/VueRNAList.java
new file mode 100644 (file)
index 0000000..1fc7e28
--- /dev/null
@@ -0,0 +1,195 @@
+package fr.orsay.lri.varna.views;
+
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyVetoException;
+import java.beans.VetoableChangeListener;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Vector;
+
+import javax.swing.JButton;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTable;
+import javax.swing.event.TableModelEvent;
+import javax.swing.event.TableModelListener;
+import javax.swing.table.AbstractTableModel;
+import javax.swing.table.TableColumn;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.components.ColorRenderer;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleColorMap;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+public class VueRNAList extends JPanel implements TableModelListener, ActionListener {
+
+       private JTable table;
+       private ValueTableModel _tm;
+       private ArrayList<RNA> data;
+       private ArrayList<Object> columns;
+       private ArrayList<Boolean> included;
+       
+       
+       public VueRNAList( ArrayList<RNA> rnas)
+       {
+               super(new BorderLayout());
+               data = rnas;
+               init();
+       }
+       
+       public ArrayList<RNA> getSelectedRNAs()
+       {
+               ArrayList<RNA> result = new ArrayList<RNA>();
+               for (int i = 0; i < data.size(); i++)
+               {
+                       if (included.get(i))
+                       {
+                               result.add(data.get(i));
+                       }
+               }               
+               return result;
+       }
+       
+       private void init()
+       {
+               Object[] col = {"Num","Selected","Name","ID","Length"};
+               columns = new ArrayList<Object>();
+               for (int i = 0; i < col.length; i++)
+               {
+                       columns.add(col[i]);
+               }
+               included = new ArrayList<Boolean>();
+               for (int i = 0; i < data.size(); i++)
+               {
+                       included.add(new Boolean(true));
+               }
+               
+               
+               _tm = new ValueTableModel();
+               table = new JTable(_tm);
+               table.setDefaultRenderer(Color.class, new ColorRenderer(true)); 
+               table.setPreferredScrollableViewportSize(new Dimension(600, 300));
+               table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
+               TableColumn c0 = table.getColumnModel().getColumn(0);
+               c0.setPreferredWidth(30);
+               TableColumn c1 = table.getColumnModel().getColumn(1);
+               c1.setPreferredWidth(30);
+               TableColumn c2 = table.getColumnModel().getColumn(2);
+               c2.setPreferredWidth(200);
+               TableColumn c3 = table.getColumnModel().getColumn(3);
+               c3.setPreferredWidth(200);
+               TableColumn c4 = table.getColumnModel().getColumn(4);
+               c4.setPreferredWidth(30);
+               table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
+               table.getModel().addTableModelListener(this);
+               
+               JScrollPane scrollPane = new JScrollPane(table);
+               this.add(scrollPane,BorderLayout.CENTER);
+               JPanel jp = new JPanel();
+               JPanel jpl = new JPanel();
+               JPanel jpr = new JPanel();
+               jp.setLayout(new BorderLayout());
+               jp.add(jpl,BorderLayout.WEST);
+               jp.add(jpr,BorderLayout.EAST);
+               jp.add(new JLabel("Please select which model(s) should be imported." ),BorderLayout.SOUTH);
+               JButton selectAll = new JButton("Select All");
+               selectAll.addActionListener(this);
+               selectAll.setActionCommand("all");
+               JButton deselectAll = new JButton("Deselect All");
+               deselectAll.addActionListener(this);
+               deselectAll.setActionCommand("none");
+               jpl.add(selectAll);
+               jpr.add(deselectAll);
+               
+               add(scrollPane,BorderLayout.CENTER);
+               add(jp,BorderLayout.SOUTH);
+               }
+       
+
+
+       private class ValueTableModel extends AbstractTableModel {
+           public String getColumnName(int col) {
+               return columns.get(col).toString();
+           }
+           public int getRowCount() { return data.size(); }
+           public int getColumnCount() { return columns.size(); }
+           public Object getValueAt(int row, int col) {
+               RNA r = data.get(row);
+               if (col==0)
+               {
+                       return new Integer(row+1);
+               }
+               else if (col==1)
+               {
+                       return new Boolean(included.get(row));
+               }
+               else if (col==2)
+               {
+                       return new String(r.getName());
+               } 
+               else if (col==3)
+               {
+                       return new String(r.getID());
+               } 
+               else if (col==4)
+               {
+                       return new Integer(r.getSize());
+               } 
+               return "N/A";
+           }
+           public boolean isCellEditable(int row, int col)
+               { 
+                       if (col==1) 
+                               return true;
+                       return false;
+               }
+           public void setValueAt(Object value, int row, int col) {
+               if (col==1)
+               {
+                 included.set(row, (Boolean)value);
+                 fireTableCellUpdated(row, col);
+               }
+           }
+           public Class getColumnClass(int c) {
+               return getValueAt(0, c).getClass();
+           }
+       }
+
+       public void tableChanged(TableModelEvent e) {
+               if (e.getType() == TableModelEvent.UPDATE)
+               {
+                       table.repaint();
+               }
+               
+       }
+
+       public void actionPerformed(ActionEvent e) {
+               if (e.getActionCommand().equals("none"))
+               {
+                       for(int i=0;i<this.included.size();i++)
+                       {
+                               included.set(i, false);
+                       }
+                       _tm.fireTableRowsUpdated(0, included.size()-1);
+               }
+               else if (e.getActionCommand().equals("all"))
+               {
+                       for(int i=0;i<this.included.size();i++)
+                       {
+                               included.set(i, true);
+                       }
+                       _tm.fireTableRowsUpdated(0, included.size()-1);
+               }
+       }
+
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueSpaceBetweenBases.java b/src2/fr/orsay/lri/varna/views/VueSpaceBetweenBases.java
new file mode 100644 (file)
index 0000000..0492b55
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+import fr.orsay.lri.varna.controlers.ControleurSpaceBetweenBases;
+
+public class VueSpaceBetweenBases {
+       private VARNAPanel _vp;
+       private JPanel panel;
+       private JSlider spaceSlider;
+
+       public VueSpaceBetweenBases(VARNAPanel vp) {
+               _vp = vp;
+               panel = new JPanel();
+
+               spaceSlider = new JSlider(JSlider.HORIZONTAL, 10, 200, Integer
+                               .valueOf(String.valueOf(Math.round(_vp.getSpaceBetweenBases() * 100))));
+               // Turn on labels at major tick marks.
+               spaceSlider.setMajorTickSpacing(30);
+               spaceSlider.setPaintTicks(true);
+               spaceSlider.setPaintLabels(true);
+
+               JLabel spaceLabel = new JLabel(String.valueOf(100.0 * _vp.getSpaceBetweenBases()));
+               spaceLabel.setPreferredSize(new Dimension(50, spaceLabel
+                               .getPreferredSize().height));
+               spaceSlider.addChangeListener(new ControleurSliderLabel(spaceLabel,
+                               false));
+               spaceSlider.addChangeListener(new ControleurSpaceBetweenBases(this));
+
+               panel = new JPanel();
+               panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel labelS = new JLabel("Space:");
+
+               panel.add(labelS);
+               panel.add(spaceSlider);
+               panel.add(spaceLabel);
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public Double getSpace() {
+               return spaceSlider.getValue() / 100.0;
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueStyleBP.java b/src2/fr/orsay/lri/varna/views/VueStyleBP.java
new file mode 100644 (file)
index 0000000..a0876d6
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JComboBox;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.models.VARNAConfig;
+
+
+public class VueStyleBP implements ActionListener {
+
+       private VARNAPanel _vp;
+       private JComboBox _cmb;
+       private JPanel panel;
+
+       public VueStyleBP(VARNAPanel vp) {
+               _vp = vp;
+               VARNAConfig.BP_STYLE[] styles = VARNAConfig.BP_STYLE.values();
+               VARNAConfig.BP_STYLE bck = vp.getConfig()._mainBPStyle;
+               _cmb = new JComboBox(styles);
+               for (int i = 0; i < styles.length; i++) {
+                       if (styles[i] == bck)
+                               _cmb.setSelectedIndex(i);
+               }
+               _cmb.addActionListener(this);
+
+               panel = new JPanel();
+               panel.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               JLabel labelZ = new JLabel("Base pair style: ");
+
+               panel.add(labelZ);
+               panel.add(_cmb);
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public VARNAConfig.BP_STYLE getStyle() {
+               return (VARNAConfig.BP_STYLE) _cmb.getSelectedItem();
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public void actionPerformed(ActionEvent e) {
+               VARNAConfig.BP_STYLE newSel = (VARNAConfig.BP_STYLE) _cmb
+                               .getSelectedItem();
+               _vp.setBPStyle(newSel);
+               _vp.repaint();
+       }
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueUI.java b/src2/fr/orsay/lri/varna/views/VueUI.java
new file mode 100644 (file)
index 0000000..e8d7fd1
--- /dev/null
@@ -0,0 +1,1932 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Universit� Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Graphics2D;
+import java.awt.Point;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Point2D;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.FileImageOutputStream;
+import javax.swing.JColorChooser;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.filechooser.FileFilter;
+import javax.swing.plaf.UIResource;
+import javax.swing.undo.UndoManager;
+import javax.swing.undo.UndoableEditSupport;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.applications.FileNameExtensionFilter;
+import fr.orsay.lri.varna.applications.VARNAPrinter;
+import fr.orsay.lri.varna.exceptions.ExceptionExportFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionFileFormatOrSyntax;
+import fr.orsay.lri.varna.exceptions.ExceptionJPEGEncoding;
+import fr.orsay.lri.varna.exceptions.ExceptionLoadingFailed;
+import fr.orsay.lri.varna.exceptions.ExceptionNAViewAlgorithm;
+import fr.orsay.lri.varna.exceptions.ExceptionNonEqualLength;
+import fr.orsay.lri.varna.exceptions.ExceptionPermissionDenied;
+import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
+import fr.orsay.lri.varna.exceptions.ExceptionWritingForbidden;
+import fr.orsay.lri.varna.factories.RNAFactory;
+import fr.orsay.lri.varna.models.FullBackup;
+import fr.orsay.lri.varna.models.VARNAConfig;
+import fr.orsay.lri.varna.models.VARNAEdits;
+import fr.orsay.lri.varna.models.annotations.ChemProbAnnotation;
+import fr.orsay.lri.varna.models.annotations.HighlightRegionAnnotation;
+import fr.orsay.lri.varna.models.annotations.TextAnnotation;
+import fr.orsay.lri.varna.models.rna.ModeleBP;
+import fr.orsay.lri.varna.models.rna.ModeleBase;
+import fr.orsay.lri.varna.models.rna.ModeleBaseNucleotide;
+import fr.orsay.lri.varna.models.rna.ModeleBasesComparison;
+import fr.orsay.lri.varna.models.rna.RNA;
+
+
+public class VueUI {
+       
+       /**
+        *
+        * BH SwingJS
+        * 
+        *      JavaScript cannot wait on a thread and so cannot wait for the result
+        *      of a customized modal JOptionPane.
+        * 
+        *      Instead, we make any JPanel that is placed in the JOptionPane
+        *      implement Runnable. In Java, we simply run that runnable here when an OK
+        *      response is delivered; in JavaScript, we run the runnable within the
+        *      JavaScript version of JOptionPane as an asynchronous callback.
+        *      
+        *      Same for a CANCEL, CLOSED, ERROR, or FINAL response.
+        *      
+        *      Note that for simple error or warning messages, this is not required; they will use simple HTML5 messages.
+        * 
+        */
+   public Runnable okBtnCallback, cancelBtnCallback, closeBtnCallback, errorCallback, finalCallback, noBtnCallback, objectCallback;
+
+   public Object dialogReturnValue;
+       
+   public Object getDialogReturnValue() {
+               return dialogReturnValue;
+       }
+
+       public Throwable dialogError;
+       
+       /**
+        * BH SwingJS
+        * 
+        * 
+        * @return
+        */
+       public Throwable getDialogError() {
+               return dialogError;
+       }
+
+
+       /**
+        * BH SwingJS
+        * 
+        * Initiate a message dialog with callback for OK and close.
+        * 
+        * @param messagePanel
+        * @param title
+        * @param ok
+        * @param close
+        */
+       private void showMessageDialog(Object messagePanel, String title, int messageType, Runnable ok, Runnable close) {
+               okBtnCallback = ok;
+               closeBtnCallback = close;
+               JOptionPane.showMessageDialog(_vp, messagePanel, title, messageType);
+       }
+
+
+
+
+       /**
+        * BH SwingJS
+        * 
+        * Initiate a confirm dialog with callbacks.
+        * 
+        * @param optionPanel
+        * @param title
+        * @param ok
+        * @param cancel
+        * @param close_final_error optional close,finally,error
+        */
+       public void showConfirmDialog(JPanel optionPanel, String title, Runnable ok, Runnable cancel, Runnable... close_final_error) {
+               okBtnCallback = ok;
+               cancelBtnCallback = cancel;
+               closeBtnCallback = (close_final_error.length > 0 ? close_final_error[0] : null);
+               finalCallback = (close_final_error.length > 1 ? close_final_error[1] : null);
+               errorCallback = (close_final_error.length > 2 ? close_final_error[2] : null);           
+               onDialogReturn(JOptionPane.showConfirmDialog(_vp, optionPanel, title, JOptionPane.OK_CANCEL_OPTION));
+       }
+
+       /**
+        * BH SwingJS
+        * 
+        * Initiate an input dialog with callbacks.
+        * 
+        * @param message
+        * @param initialValue
+        * @param input
+        * @param close_final_error optional [close,finally,error]
+        */
+       public void showInputDialog(String message, Object initialValue, Runnable input, Runnable... close_final_error) {
+               objectCallback = input;
+               closeBtnCallback = (close_final_error.length > 0 ? close_final_error[0] : null);
+               finalCallback = (close_final_error.length > 1 ? close_final_error[1] : null);
+               errorCallback = (close_final_error.length > 2 ? close_final_error[2] : null);           
+               onDialogReturn(JOptionPane.showInputDialog(_vp, message, initialValue));
+       }
+
+       /**
+        * BH SwingJS
+        * 
+        * Initiate an color chooser dialog with callbacks.
+        * 
+        * @param message
+        * @param initialValue
+        * @param input
+        * @param close_final_error optional [close,finally,error]
+        */
+       public void showColorDialog(String message, Object initialValue, Runnable ret) {
+               objectCallback = ret;
+               onDialogReturn(JColorChooser.showDialog(_vp, message, (Color) initialValue));
+       }
+
+       
+       /**
+        * BH SwingJS
+        * 
+        * A general method to handle all the showInputDialog, JFileChooser, and JColorChooser callbacks from all the VueXXX classes.
+        * 
+        * The initial return to be ignored is an object that is an instanceof UIResource.
+        * 
+        */
+       public void onDialogReturn(Object value) {
+               dialogReturnValue = value;
+               if (objectCallback != null && !(value instanceof UIResource))
+                       objectCallback.run();
+       }
+       
+       /**
+        * BH SwingJS
+        * 
+        * A general method to handle all the showConfirmDialog callbacks from all
+        * the VueXXX classes.
+        * 
+        * The initial return to be ignored is NaN, testable as 
+        * value != Math.floor(value).
+        * 
+        */
+       public void onDialogReturn(int value) {
+               try {
+                       switch (value) {
+                       case JOptionPane.OK_OPTION | JOptionPane.YES_OPTION:
+                               if (okBtnCallback != null)
+                                       okBtnCallback.run();
+                               break;
+                       case JOptionPane.NO_OPTION:
+                               if (noBtnCallback != null)
+                                       noBtnCallback.run();
+                               break;
+                       case JOptionPane.CANCEL_OPTION:
+                               if (cancelBtnCallback != null)
+                                       cancelBtnCallback.run();
+                               break;
+                       case JOptionPane.CLOSED_OPTION:
+                               if (closeBtnCallback != null)
+                                       closeBtnCallback.run();
+                               break;
+                       }
+               } catch (Throwable e) {
+                       dialogError = e;
+                       if (errorCallback != null)
+                               errorCallback.run();
+               } finally {
+                       if (value != Math.floor(value)) {
+                               // asynchronous deferred
+                               return;
+                       }
+                       if (finalCallback != null)
+                               finalCallback.run();
+                       okBtnCallback = noBtnCallback = cancelBtnCallback = closeBtnCallback = errorCallback = objectCallback = null;
+                       dialogError = null;
+               }
+       }
+       
+       
+    protected VARNAPanel _vp;
+       private File _fileChooserDirectory = null;
+       private UndoableEditSupport _undoableEditSupport;
+
+       public VueUI(VARNAPanel vp) {
+               _vp = vp;
+               _undoableEditSupport = new UndoableEditSupport(_vp);
+       }
+
+       public void addUndoableEditListener(UndoManager manager) {
+               _undoableEditSupport.addUndoableEditListener(manager);
+       }
+
+       public void UIToggleColorMap() {
+               if (_vp.isModifiable()) {
+                       _vp.setColorMapVisible(!_vp.getColorMapVisible());
+                       _vp.repaint();
+               }
+       }
+
+       public void UIToggleDrawBackbone() {
+               if (_vp.isModifiable()) {
+                       _vp.setDrawBackbone(!_vp.getDrawBackbone());
+                       _vp.repaint();
+               }
+       }
+
+       public Hashtable<Integer, Point2D.Double> backupAllCoords() {
+               Hashtable<Integer, Point2D.Double> tmp = new Hashtable<Integer, Point2D.Double>();
+               for (int i = 0; i < _vp.getRNA().getSize(); i++) {
+                       tmp.put(i, _vp.getRNA().getCoords(i));
+               }
+               return tmp;
+       }
+
+       public void UIToggleFlatExteriorLoop() {
+               if (_vp.isModifiable()
+                               && _vp.getRNA().get_drawMode() == RNA.DRAW_MODE_RADIATE) {
+                       Hashtable<Integer, Point2D.Double> bck = backupAllCoords();
+                       _undoableEditSupport.postEdit(new VARNAEdits.RedrawEdit(
+                                       RNA.DRAW_MODE_RADIATE, _vp, !_vp.getFlatExteriorLoop()));
+                       _vp.setFlatExteriorLoop(!_vp.getFlatExteriorLoop());
+                       _vp.reset();
+                       _vp.drawRNA(_vp.getRNA(), RNA.DRAW_MODE_RADIATE);
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(bck);
+               }
+       }
+
+       public void UIRadiate() {
+               if (_vp.isModifiable()) {
+                       Hashtable<Integer, Point2D.Double> bck = backupAllCoords();
+                       _undoableEditSupport.postEdit(new VARNAEdits.RedrawEdit(
+                                       RNA.DRAW_MODE_RADIATE, _vp));
+                       _vp.reset();
+                       _vp.drawRNA(_vp.getRNA(), RNA.DRAW_MODE_RADIATE);
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(bck);
+               }
+       }
+
+       public void UIMOTIFView() {
+               if (_vp.isModifiable()) {
+                       Hashtable<Integer, Point2D.Double> bck = backupAllCoords();
+                       _undoableEditSupport.postEdit(new VARNAEdits.RedrawEdit(
+                                       RNA.DRAW_MODE_MOTIFVIEW, _vp));
+                       _vp.reset();
+                       _vp.drawRNA(_vp.getRNA(), RNA.DRAW_MODE_MOTIFVIEW);
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(bck);
+               }
+       }
+
+       public void UILine() {
+               if (_vp.isModifiable()) {
+                       Hashtable<Integer, Point2D.Double> bck = backupAllCoords();
+                       _undoableEditSupport.postEdit(new VARNAEdits.RedrawEdit(
+                                       RNA.DRAW_MODE_LINEAR, _vp));
+                       _vp.reset();
+                       _vp.drawRNA(_vp.getRNA(), RNA.DRAW_MODE_LINEAR);
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(bck);
+               }
+       }
+
+       public void UICircular() {
+               if (_vp.isModifiable()) {
+                       Hashtable<Integer, Point2D.Double> bck = backupAllCoords();
+                       _undoableEditSupport.postEdit(new VARNAEdits.RedrawEdit(
+                                       RNA.DRAW_MODE_CIRCULAR, _vp));
+                       _vp.reset();
+                       _vp.drawRNA(_vp.getRNA(), RNA.DRAW_MODE_CIRCULAR);
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(bck);
+               }
+       }
+
+       public void UINAView() {
+               if (_vp.isModifiable()) {
+                       Hashtable<Integer, Point2D.Double> bck = backupAllCoords();
+                       _undoableEditSupport.postEdit(new VARNAEdits.RedrawEdit(
+                                       RNA.DRAW_MODE_NAVIEW, _vp));
+                       _vp.reset();
+                       _vp.drawRNA(_vp.getRNA(), RNA.DRAW_MODE_NAVIEW);
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(bck);
+               }
+       }
+
+       public void UIVARNAView() {
+               if (_vp.isModifiable()) {
+                       Hashtable<Integer, Point2D.Double> bck = backupAllCoords();
+                       _undoableEditSupport.postEdit(new VARNAEdits.RedrawEdit(
+                                       RNA.DRAW_MODE_VARNA_VIEW, _vp));
+                       _vp.reset();
+                       _vp.drawRNA(_vp.getRNA(), RNA.DRAW_MODE_VARNA_VIEW);
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(bck);
+               }
+       }
+
+       public void UIReset() {
+               if (_vp.isModifiable()) {
+                       Hashtable<Integer, Point2D.Double> bck = backupAllCoords();
+                       _undoableEditSupport.postEdit(new VARNAEdits.RedrawEdit(_vp
+                                       .getRNA().get_drawMode(), _vp));
+                       _vp.reset();
+                       _vp.drawRNA(_vp.getRNA(), _vp.getRNA().get_drawMode());
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(bck);
+               }
+       }
+
+       private void savePath(JFileChooser jfc) {
+               _fileChooserDirectory = jfc.getCurrentDirectory();
+       }
+
+       private void loadPath(JFileChooser jfc) {
+               if (_fileChooserDirectory != null) {
+                       jfc.setCurrentDirectory(_fileChooserDirectory);
+               }
+       }
+
+       public void UIChooseRNAs(ArrayList<RNA> rnas) {
+               if (rnas.size() > 5) {
+                       final VueRNAList vrna = new VueRNAList(rnas);
+                       Runnable ok = new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       for (RNA r : vrna.getSelectedRNAs()) {
+                                               try {
+                                                       r.drawRNA(_vp.getConfig());
+                                               } catch (ExceptionNAViewAlgorithm e) {
+                                                       e.printStackTrace();
+                                               }
+                                               _vp.showRNA(r);
+                                       }
+                                       _vp.repaint();
+                               }
+
+                       };
+                       showConfirmDialog(vrna, "Select imported sequence/structures", ok, null);
+               } else {
+                       for (RNA r : rnas) {
+                               try {
+                                       r.drawRNA(_vp.getConfig());
+                               } catch (ExceptionNAViewAlgorithm e) {
+                                       e.printStackTrace();
+                               }
+                               _vp.showRNA(r);
+                       }
+                       _vp.repaint();
+               }
+       }
+
+       public void UIFile() throws ExceptionNonEqualLength {
+               if (_vp.isModifiable()) {
+                       JFileChooser fc = new JFileChooser();
+                       fc.setFileSelectionMode(JFileChooser.OPEN_DIALOG);
+                       fc.setDialogTitle("Open...");
+                       loadPath(fc);
+                       if (fc.showOpenDialog(_vp) == JFileChooser.APPROVE_OPTION) {
+                               try {
+                                       savePath(fc);
+                                       String path = fc.getSelectedFile().getAbsolutePath();
+                                       if (!path.toLowerCase().endsWith(".varna")) {
+                                               ArrayList<RNA> rnas = RNAFactory.loadSecStr(path);
+                                               if (rnas.isEmpty()) {
+                                                       throw new ExceptionFileFormatOrSyntax("No RNA could be parsed from that source.");
+                                               } else {
+                                                       UIChooseRNAs(rnas);
+                                               }
+                                       } else {
+                                               FullBackup bck = _vp.loadSession(fc.getSelectedFile()); // was path
+                                       }
+                               } catch (ExceptionExportFailed e1) {
+                                       _vp.errorDialog(e1);
+                               } catch (ExceptionPermissionDenied e1) {
+                                       _vp.errorDialog(e1);
+                               } catch (ExceptionLoadingFailed e1) {
+                                       _vp.errorDialog(e1);
+                               } catch (ExceptionFileFormatOrSyntax e1) {
+                                       _vp.errorDialog(e1);
+                               } catch (ExceptionUnmatchedClosingParentheses e1) {
+                                       _vp.errorDialog(e1);
+                               } catch (FileNotFoundException e) {
+                                       _vp.errorDialog(e);
+                               }
+                       }
+               }
+       }
+
+       public void UISetColorMapStyle() {
+               final VueColorMapStyle vcms = new VueColorMapStyle(_vp);
+               Runnable ok = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               _vp.setColorMap(vcms.getColorMap());
+                       }
+                       
+               };
+               Runnable cancel = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               vcms.cancelChanges();
+                       }
+                                               
+               };
+               showConfirmDialog(vcms, "Choose color map style", ok, cancel, cancel, null, null);
+       }
+
+       public void UILoadColorMapValues() {
+               final VueLoadColorMapValues vcmv = new VueLoadColorMapValues(_vp);
+               Runnable ok = new Runnable(){
+                       
+                       @Override
+                       public void run() {
+                               _vp.setColorMapVisible(true);
+                               try {
+                                       _vp.readValues(vcmv.getReader());
+                               } catch (IOException e) {
+                                       _vp.errorDialog((Exception) getDialogError());
+                               }
+                       }
+                       
+               };
+               showConfirmDialog(vcmv, "Load base values", ok, null);
+       }
+
+       public void UISetColorMapValues() {
+               final VueBaseValues vbv = new VueBaseValues(_vp);
+               Runnable cancel = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               vbv.cancelChanges();
+                       }
+                                               
+               };
+               showConfirmDialog(vbv, "Choose base values", null, cancel);
+       }
+
+       public void UIManualInput() throws ParseException, ExceptionNonEqualLength {
+               if (_vp.isModifiable()) {
+                       final VueManualInput manualInput = new VueManualInput(_vp);
+                       Runnable ok = new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       if (_vp.getRNA().getSize() == 0) {
+
+                                       }
+                                       try {
+                                               RNA r = new RNA();
+                                               VARNAConfig cfg = new VARNAConfig();
+                                               r.setRNA(manualInput.getTseq().getText(), manualInput.getTstr().getText());
+                                               r.drawRNA(_vp.getRNA().get_drawMode(), cfg);
+                                               _vp.drawRNAInterpolated(r);
+                                               _vp.repaint();
+                                       } catch (ExceptionFileFormatOrSyntax e) {
+                                               // TODO Auto-generated catch block
+                                               e.printStackTrace();
+                                       } catch (ExceptionNAViewAlgorithm e) {
+                                               // TODO Auto-generated catch block
+                                               e.printStackTrace();
+                                       } catch (ExceptionUnmatchedClosingParentheses e) {
+                                               // TODO Auto-generated catch block
+                                               e.printStackTrace();
+                                       }
+                               }
+                               
+                       };
+                       showConfirmDialog(manualInput.getPanel(), "Input sequence/structure", ok, null);
+               }
+       }
+
+       public void UISetTitle() {
+               if (_vp.isModifiable()) {
+                       Runnable input = new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       String res = (String) getDialogReturnValue();
+                                       if (res != null) {
+                               _vp.setTitle(res);
+                                               _vp.repaint();
+                                       }
+                               }
+                               
+                       };
+                       
+                       showInputDialog("Input title", _vp.getTitle(), input);
+               }
+       }
+
+       public void UISetColorMapCaption() {
+               if (_vp.isModifiable()) {
+                       Runnable input = new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       String res = (String) getDialogReturnValue();                                           
+                                       if (res != null) {
+                                               _vp.setColorMapCaption(res);
+                                               _vp.repaint();
+                                       }
+                               }
+                               
+                       };
+                       showInputDialog("Input new color map caption", _vp.getColorMapCaption(), input);
+               }
+       }
+
+       public void UISetBaseCharacter() {
+               if (_vp.isModifiable()) {
+                       final int i = _vp.getNearestBase();
+
+                       if (_vp.isComparisonMode()) {
+
+                               Runnable input = new Runnable() {
+
+                                       @Override
+                                       public void run() {
+                                               String res = (String) getDialogReturnValue();
+                                               if (res != null) {
+                                                       ModeleBasesComparison mb = (ModeleBasesComparison) _vp.getRNA().get_listeBases().get(i);
+                                                       String bck = mb.getBase1() + "|" + mb.getBase2();
+                                                       mb.setBase1(((res.length() > 0) ? res.charAt(0) : ' '));
+                                                       mb.setBase2(((res.length() > 1) ? res.charAt(1) : ' '));
+                                                       _vp.repaint();
+                                                       _vp.fireSequenceChanged(i, bck, res);
+                                               }
+                                       }
+
+                               };
+
+                               
+                               
+                               showInputDialog("Input base", ((ModeleBasesComparison) _vp.getRNA().get_listeBases().get(i)).getBases(),  input);
+
+                       } else {
+
+                               Runnable input = new Runnable() {
+
+                                       @Override
+                                       public void run() {
+                                               String res = (String) getDialogReturnValue();
+                                               if (res != null) {
+                                                       ModeleBaseNucleotide mb = (ModeleBaseNucleotide) _vp.getRNA().get_listeBases().get(i);
+                                                       String bck = mb.getBase();
+                                                       mb.setBase(res);
+                                                       _vp.repaint();
+                                                       _vp.fireSequenceChanged(i, bck, res);
+                                               }
+                                       }
+
+                               };
+                               showInputDialog("Input base", ((ModeleBaseNucleotide) _vp.getRNA().get_listeBases().get(i)).getBase(), input);
+                       }
+               }
+       }
+
+       FileNameExtensionFilter _varnaFilter = new FileNameExtensionFilter(
+                       "VARNA Session File", "varna", "VARNA");
+       FileNameExtensionFilter _bpseqFilter = new FileNameExtensionFilter(
+                       "BPSeq (CRW) File", "bpseq", "BPSEQ");
+       FileNameExtensionFilter _ctFilter = new FileNameExtensionFilter(
+                       "Connect (MFold) File", "ct", "CT");
+       FileNameExtensionFilter _dbnFilter = new FileNameExtensionFilter(
+                       "Dot-bracket notation (Vienna) File", "dbn", "DBN", "faa", "FAA");
+
+       FileNameExtensionFilter _jpgFilter = new FileNameExtensionFilter(
+                       "JPEG Picture", "jpeg", "jpg", "JPG", "JPEG");
+       FileNameExtensionFilter _pngFilter = new FileNameExtensionFilter(
+                       "PNG Picture", "png", "PNG");
+       FileNameExtensionFilter _epsFilter = new FileNameExtensionFilter(
+                       "EPS File", "eps", "EPS");
+       FileNameExtensionFilter _svgFilter = new FileNameExtensionFilter(
+                       "SVG Picture", "svg", "SVG");
+       FileNameExtensionFilter _xfigFilter = new FileNameExtensionFilter(
+                       "XFig Diagram", "fig", "xfig", "FIG", "XFIG");
+       FileNameExtensionFilter _tikzFilter = new FileNameExtensionFilter(
+                       "PGF/Tikz diagram", "tex", "pgf");
+
+       public void UIExport() throws ExceptionExportFailed,
+                       ExceptionPermissionDenied, ExceptionWritingForbidden,
+                       ExceptionJPEGEncoding {
+               ArrayList<FileNameExtensionFilter> v = new ArrayList<FileNameExtensionFilter>();
+               v.add(_epsFilter);
+               v.add(_svgFilter);
+               v.add(_tikzFilter);
+               v.add(_xfigFilter);
+               v.add(_jpgFilter);
+               v.add(_pngFilter);
+               String dest = UIChooseOutputFile(v);
+               if (dest != null) {
+                       String extLower = dest.substring(dest.lastIndexOf('.'))
+                                       .toLowerCase();
+                       // System.out.println(extLower);
+                       if (extLower.equals(".eps")) {
+                               _vp.getRNA().saveRNAEPS(dest, _vp.getConfig());
+                       } else if (extLower.equals(".svg")) {
+                               _vp.getRNA().saveRNASVG(dest, _vp.getConfig());
+                       } else if (extLower.equals(".fig") || extLower.equals(".xfig")) {
+                               _vp.getRNA().saveRNAXFIG(dest, _vp.getConfig());
+                       } else if (extLower.equals(".pgf") || extLower.equals(".tex")) {
+                               _vp.getRNA().saveRNATIKZ(dest, _vp.getConfig());
+                       } else if (extLower.equals(".png")) {
+                               saveToPNG(dest);
+                       } else if (extLower.equals(".jpg") || extLower.equals(".jpeg")) {
+                               saveToJPEG(dest);
+                       }
+               }
+       }
+
+       public void UIExportJPEG() throws ExceptionJPEGEncoding,
+                       ExceptionExportFailed {
+               String dest = UIChooseOutputFile(_jpgFilter);
+               if (dest != null) {
+                       saveToJPEG(dest);
+               }
+       }
+
+       public void UIPrint() {
+               VARNAPrinter.printComponent(_vp);
+       }
+
+       public void UIExportPNG() throws ExceptionExportFailed {
+               String dest = UIChooseOutputFile(_pngFilter);
+               if (dest != null) {
+                       saveToPNG(dest);
+               }
+       }
+
+       public void UIExportXFIG() throws ExceptionExportFailed,
+                       ExceptionWritingForbidden {
+               String dest = UIChooseOutputFile(_xfigFilter);
+               if (dest != null) {
+                       _vp.getRNA().saveRNAXFIG(dest, _vp.getConfig());
+               }
+       }
+
+       public void UIExportTIKZ() throws ExceptionExportFailed,
+                       ExceptionWritingForbidden {
+               String dest = UIChooseOutputFile(_tikzFilter);
+               if (dest != null) {
+                       _vp.getRNA().saveRNATIKZ(dest, _vp.getConfig());
+               }
+       }
+
+       public void UIExportEPS() throws ExceptionExportFailed,
+                       ExceptionWritingForbidden {
+               String dest = UIChooseOutputFile(_epsFilter);
+               if (dest != null) {
+                       _vp.getRNA().saveRNAEPS(dest, _vp.getConfig());
+               }
+       }
+
+       public void UIExportSVG() throws ExceptionExportFailed,
+                       ExceptionWritingForbidden {
+               String dest = UIChooseOutputFile(_svgFilter);
+               if (dest != null) {
+                       _vp.getRNA().saveRNASVG(dest, _vp.getConfig());
+               }
+       }
+
+       public void UISaveAsDBN() throws ExceptionExportFailed,
+                       ExceptionPermissionDenied {
+               String name = _vp.getVARNAUI().UIChooseOutputFile(_dbnFilter);
+               if (name != null)
+                       _vp.getRNA().saveAsDBN(name, _vp.getTitle());
+       }
+
+       public void UISaveAsCT() throws ExceptionExportFailed,
+                       ExceptionPermissionDenied {
+               String name = _vp.getVARNAUI().UIChooseOutputFile(_ctFilter);
+               if (name != null)
+                       _vp.getRNA().saveAsCT(name, _vp.getTitle());
+       }
+
+       public void UISaveAsBPSEQ() throws ExceptionExportFailed,
+                       ExceptionPermissionDenied {
+               String name = _vp.getVARNAUI().UIChooseOutputFile(_bpseqFilter);
+               if (name != null)
+                       _vp.getRNA().saveAsBPSEQ(name, _vp.getTitle());
+       }
+
+       public void UISaveAs() throws ExceptionExportFailed,
+                       ExceptionPermissionDenied {
+               ArrayList<FileNameExtensionFilter> v = new ArrayList<FileNameExtensionFilter>();
+               v.add(_bpseqFilter);
+               v.add(_dbnFilter);
+               v.add(_ctFilter);
+               v.add(_varnaFilter);
+               String dest = UIChooseOutputFile(v);
+               if (dest != null) {
+                       String extLower = dest.substring(dest.lastIndexOf('.'))
+                                       .toLowerCase();
+                       if (extLower.endsWith("bpseq")) {
+                               _vp.getRNA().saveAsBPSEQ(dest, _vp.getTitle());
+                       } else if (extLower.endsWith("ct")) {
+                               _vp.getRNA().saveAsCT(dest, _vp.getTitle());
+                       } else if (extLower.endsWith("dbn") || extLower.endsWith("faa")) {
+                               _vp.getRNA().saveAsDBN(dest, _vp.getTitle());
+                       } else if (extLower.endsWith("varna")) {
+                               _vp.saveSession(dest);
+                       }
+               }
+       }
+
+       public String UIChooseOutputFile(FileNameExtensionFilter filtre) {
+               ArrayList<FileNameExtensionFilter> v = new ArrayList<FileNameExtensionFilter>();
+               v.add(filtre);
+               return UIChooseOutputFile(v);
+       }
+
+       /**
+        * Opens a save dialog with right extensions and return the absolute path
+        * 
+        * @param filtre
+        *            Allowed extensions
+        * @return <code>null</code> if the user doesn't approve the save dialog,<br>
+        *         <code>absolutePath</code> if the user approve the save dialog
+        */
+       public String UIChooseOutputFile(ArrayList<FileNameExtensionFilter> filtre) {
+               JFileChooser fc = new JFileChooser();
+               loadPath(fc);
+               String absolutePath = null;
+               // applique le filtre
+               for (int i = 0; i < filtre.size(); i++) {
+                       fc.addChoosableFileFilter(filtre.get(i));
+               }
+               // en mode open dialog pour voir les autres fichiers avec la meme
+               // extension
+               fc.setFileSelectionMode(JFileChooser.OPEN_DIALOG);
+               fc.setDialogTitle("Save...");
+               // Si l'utilisateur a valider
+               if (fc.showSaveDialog(_vp) == JFileChooser.APPROVE_OPTION) {
+                       savePath(fc);
+                       absolutePath = fc.getSelectedFile().getAbsolutePath();
+                       String extension = _vp.getPopupMenu().get_controleurMenu()
+                                       .getExtension(fc.getSelectedFile());
+                       FileFilter f = fc.getFileFilter();
+                       if (f instanceof FileNameExtensionFilter) {
+                               ArrayList<String> listeExtension = new ArrayList<String>();
+                               listeExtension.addAll(Arrays
+                                               .asList(((FileNameExtensionFilter) f).getExtensions()));
+                               // si l'extension du fichier ne fait pas partie de la liste
+                               // d'extensions acceptées
+                               if (!listeExtension.contains(extension)) {
+                                       absolutePath += "." + listeExtension.get(0);
+                               }
+                       }
+               }
+               return absolutePath;
+       }
+
+       public void UISetBorder() {
+               VueBorder border = new VueBorder(_vp);
+               final Dimension oldBorder = _vp.getBorderSize();
+               _vp.drawBBox(true);
+               _vp.drawBorder(true);
+               _vp.repaint();
+               Runnable cancel = new Runnable () {
+
+                       @Override
+                       public void run() {
+                               _vp.setBorderSize(oldBorder);
+                       }
+                       
+               };
+               Runnable final_ = new Runnable () {
+
+                       @Override
+                       public void run() {
+                               _vp.drawBorder(false);
+                               _vp.drawBBox(false);
+                               _vp.repaint();
+                       }
+                       
+               };
+               
+               showConfirmDialog(border.getPanel(), "Set new border size", null, cancel, cancel, final_);
+       }
+
+       public void UISetBackground() {
+               showColorDialog("Choose new background color", _vp.getBackground(), new Runnable() {
+
+                       @Override
+                       public void run() {
+                               if (dialogReturnValue != null) {
+                                       _vp.setBackground((Color) dialogReturnValue);
+                                       _vp.repaint();
+                               }
+                       }
+                       
+               });
+       }
+
+       public void UIZoomIn() {
+               double _actualZoom = _vp.getZoom();
+               double _actualAmount = _vp.getZoomIncrement();
+               Point _actualTranslation = _vp.getTranslation();
+               double newZoom = Math.min(VARNAConfig.MAX_ZOOM, _actualZoom
+                               * _actualAmount);
+               double ratio = newZoom / _actualZoom;
+               Point newTrans = new Point((int) (_actualTranslation.x * ratio),
+                               (int) (_actualTranslation.y * ratio));
+               _vp.setZoom(newZoom);
+               _vp.setTranslation(newTrans);
+               // verification que la translation ne pose pas de problemes
+               _vp.checkTranslation();
+               // System.out.println("Zoom in");
+               _vp.repaint();
+       }
+
+       public void UIZoomOut() {
+               double _actualZoom = _vp.getZoom();
+               double _actualAmount = _vp.getZoomIncrement();
+               Point _actualTranslation = _vp.getTranslation();
+               double newZoom = Math.max(_actualZoom / _actualAmount,
+                               VARNAConfig.MIN_ZOOM);
+               double ratio = newZoom / _actualZoom;
+               Point newTrans = new Point((int) (_actualTranslation.x * ratio),
+                               (int) (_actualTranslation.y * ratio));
+               _vp.setZoom(newZoom);
+               _vp.setTranslation(newTrans);
+               // verification que la translation ne pose pas de problemes
+               _vp.checkTranslation();
+               _vp.repaint();
+       }
+
+       public void UICustomZoom() {
+               VueZoom zoom = new VueZoom(_vp);
+               final double oldZoom = _vp.getZoom();
+               final double oldZoomAmount = _vp.getZoomIncrement();
+               _vp.drawBBox(true);
+               _vp.repaint();
+               Runnable cancel = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               _vp.setZoom(oldZoom);
+                               _vp.setZoomIncrement(oldZoomAmount);
+                       }
+                       
+               };
+               Runnable final_ = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               _vp.drawBBox(false);
+                               _vp.repaint();
+                       }
+                       
+               };
+               showConfirmDialog(zoom.getPanel(), "Set zoom", null, cancel, cancel, final_);
+       }
+
+       public void UIGlobalRescale() {
+               if (_vp.isModifiable()) {
+                       if (_vp.getRNA().get_listeBases().size() > 0) {
+                               final VueGlobalRescale rescale = new VueGlobalRescale(_vp);
+                               Runnable cancel = new Runnable() {
+
+                                       @Override
+                                       public void run() {
+                                               UIGlobalRescale(1. / rescale.getScale());
+                                       }
+                                       
+                               };
+                               Runnable final_ = new Runnable() {
+
+                                       @Override
+                                       public void run() {
+                                               _vp.drawBBox(false);
+                                               _vp.repaint();
+                                       }
+                                       
+                               };
+                               showConfirmDialog(rescale.getPanel(), "Rescales the whole RNA (No redraw)", null, cancel, cancel, final_);
+                       }
+               }
+       }
+
+       public void UIGlobalRescale(double d) {
+               if (_vp.isModifiable()) {
+                       if (_vp.getRNA().get_listeBases().size() > 0) {
+                               _vp.globalRescale(d);
+                               _undoableEditSupport.postEdit(new VARNAEdits.RescaleRNAEdit(d,
+                                               _vp));
+                       }
+               }
+       }
+
+       public void UIGlobalRotation() {
+               if (_vp.isModifiable()) {
+                       if (_vp.getRNA().get_listeBases().size() > 0) {
+                               _vp.drawBBox(true);
+                               _vp.repaint();
+                               final VueGlobalRotation rotation = new VueGlobalRotation(_vp);
+                               Runnable cancel = new Runnable() {
+
+                                       @Override
+                                       public void run() {
+                                               UIGlobalRotation(-rotation.getAngle());
+                                       }
+                                       
+                               };
+                               Runnable final_ = new Runnable() {
+
+                                       @Override
+                                       public void run() {
+                                               _vp.drawBBox(false);
+                                               _vp.repaint();
+                                       }
+                                       
+                               };
+                               showConfirmDialog(rotation.getPanel(), "Rotates the whole RNA", null, cancel, cancel, final_, null);
+                       }
+               }
+       }
+
+       public void UIGlobalRotation(double d) {
+               if (_vp.isModifiable()) {
+                       if (_vp.getRNA().get_listeBases().size() > 0) {
+                               _vp.globalRotation(d);
+                               _undoableEditSupport.postEdit(new VARNAEdits.RotateRNAEdit(d,
+                                               _vp));
+                       }
+               }
+       }
+
+       public void UISetBPStyle() {
+               if (_vp.getRNA().get_listeBases().size() > 0) {
+                       VueStyleBP bpstyle = new VueStyleBP(_vp);
+                       final VARNAConfig.BP_STYLE bck = _vp.getBPStyle();
+                       Runnable cancel = new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       _vp.setBPStyle(bck);
+                                       _vp.repaint();
+                               }
+                               
+                       };
+                       showConfirmDialog(bpstyle.getPanel(), "Set main base pair style", null, cancel, cancel);
+               }
+       }
+
+       public void UISetTitleColor() {
+               if (_vp.isModifiable()) {
+                       showColorDialog("Choose new title color", _vp.getTitleColor(), new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       if (dialogReturnValue != null) {
+                                               _vp.setTitleColor((Color) dialogReturnValue);
+                                               _vp.repaint();
+                                       }
+                               }
+                               
+                       });
+               }
+       }
+
+       public void UISetBackboneColor() {
+               if (_vp.isModifiable()) {
+                       showColorDialog("Choose new backbone color", _vp.getBackboneColor(), new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       if (dialogReturnValue != null) {
+                                               _vp.setBackboneColor((Color) dialogReturnValue);
+                                               _vp.repaint();
+                                       }
+                               }
+                               
+                       });
+               }
+       }
+
+       public void UISetTitleFont() {
+               if (_vp.isModifiable()) {
+                       final VueFont font = new VueFont(_vp);
+                       Runnable ok = new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       _vp.setTitleFont(font.getFont());
+                                       _vp.repaint();
+                               }
+
+                       };
+                       showConfirmDialog(font.getPanel(), "New Title font", ok, null);
+               }
+       }
+
+       public void UISetSpaceBetweenBases() {
+               if (_vp.isModifiable()) {
+
+                       final VueSpaceBetweenBases vsbb = new VueSpaceBetweenBases(_vp);
+                       final Double oldSpace = _vp.getSpaceBetweenBases();
+                       Runnable cancel = new Runnable () {
+
+                               @Override
+                               public void run() {
+                                       _vp.setSpaceBetweenBases(oldSpace);
+                                       _vp.drawRNA(_vp.getRNA());
+                                       _vp.repaint();
+                               }
+                               
+                       };
+                       showConfirmDialog(vsbb.getPanel(), "Set the space between each base", null, cancel, cancel);                    
+               }
+       }
+
+       public void UISetBPHeightIncrement() {
+               if (_vp.isModifiable()) {
+
+                       VueBPHeightIncrement v = new VueBPHeightIncrement(_vp);
+                       final Double oldSpace = _vp.getBPHeightIncrement();
+                       Runnable cancel = new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       _vp.setBPHeightIncrement(oldSpace);
+                                       _vp.drawRNA(_vp.getRNA());
+                                       _vp.repaint();
+                               }
+                               
+                       };
+                       showConfirmDialog(v.getPanel(), "Set the vertical increment in linear mode", null, cancel, cancel);
+               }
+       }
+
+       public void UISetNumPeriod() {
+               if (_vp.getRNA().get_listeBases().size() != 0) {
+                       final int oldNumPeriod = _vp.getNumPeriod();
+                       VueNumPeriod vnp = new VueNumPeriod(_vp);
+                       Runnable cancel = new Runnable() {
+
+                               @Override
+                               public void run() {
+                                       _vp.setNumPeriod(oldNumPeriod);
+                                       _vp.repaint();
+                               }
+                               
+                       };
+                       showConfirmDialog(vnp.getPanel(), "Set new numbering period", null, cancel, cancel);
+               }
+       }
+
+       public void UIEditBasePair() {
+               if (_vp.isModifiable()) {
+                       ModeleBase mb = _vp.getRNA().get_listeBases().get(_vp.getNearestBase());
+                       if (mb.getElementStructure() != -1) {
+                               final ModeleBP msbp = mb.getStyleBP();
+                               final ModeleBP.Edge bck5 = msbp.getEdgePartner5();
+                               final ModeleBP.Edge bck3 = msbp.getEdgePartner3();
+                               final ModeleBP.Stericity bcks = msbp.getStericity();
+
+                               VueBPType vbpt = new VueBPType(_vp, msbp);
+                               Runnable cancel = new Runnable() {
+
+                                       @Override
+                                       public void run() {
+                                               msbp.setEdge5(bck5);
+                                               msbp.setEdge3(bck3);
+                                               msbp.setStericity(bcks);
+                                               _vp.repaint();
+                                       }
+                                       
+                               };
+                               showConfirmDialog(vbpt.getPanel(), "Set base pair L/W type", null, cancel, cancel);
+                       }
+               }
+       }
+
+       public void UIColorBasePair() {
+               if (_vp.isModifiable()) {
+                       ModeleBase mb = _vp.getRNA().get_listeBases().get(_vp.getNearestBase());
+                       if (mb.getElementStructure() != -1) {
+                               final ModeleBP msbp = mb.getStyleBP();
+                               showColorDialog("Choose custom base pair color",
+                                               msbp.getStyle().getColor(_vp.getConfig()._bondColor), new Runnable() {
+
+                                       @Override
+                                       public void run() {
+                                               if (dialogReturnValue != null) {
+                                                       msbp.getStyle().setCustomColor((Color) dialogReturnValue);
+                                                       _vp.repaint();
+                                               }
+                                       }
+                                       
+                               });
+                       }
+               }
+       }
+
+       public void UIThicknessBasePair() {
+               if (_vp.isModifiable()) {
+                       ModeleBase mb = _vp.getRNA().get_listeBases()
+                                       .get(_vp.getNearestBase());
+                       if (mb.getElementStructure() != -1) {
+                               ModeleBP msbp = mb.getStyleBP();
+                               ArrayList<ModeleBP> bases = new ArrayList<ModeleBP>();
+                               bases.add(msbp);
+                               UIThicknessBasePairs(bases);
+                       }
+               }
+       }
+
+       public void saveToPNG(final String filename) {
+               final VueJPEG jpeg = new VueJPEG(true, false);
+               Runnable ok = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               Double scale = jpeg.getScaleSlider().getValue() / 100.0;
+                               BufferedImage myImage = new BufferedImage((int) Math.round(_vp.getWidth() * scale),
+                                               (int) Math.round(_vp.getHeight() * scale), BufferedImage.TYPE_INT_ARGB);
+                               // BH j2s SwingJS: was BufferedImage.TRANSLUCENT, which is TYPE_INT_ARGB_PRE ?? no transparent background?
+                               Graphics2D g2 = myImage.createGraphics();
+                               AffineTransform AF = new AffineTransform();
+                               AF.setToScale(scale, scale);
+                               g2.setTransform(AF);
+                               _vp.paintComponent(g2, !_vp.getConfig()._drawBackground);
+                               g2.dispose();
+                               try {
+                                       ImageIO.write(myImage, "PNG", new File(filename));
+                               } catch (IOException e) {
+                                       // cannot throw an exception from Runnable.run()
+                                       _vp.errorDialog(new ExceptionExportFailed(e.getMessage(), filename));
+                               }
+                       }
+
+               };
+               showConfirmDialog(jpeg.getPanel(), "Set resolution", ok, null);
+       }
+
+       public void saveToJPEG(final String filename) {
+               final VueJPEG jpeg = new VueJPEG(true, true);
+               Runnable ok = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               Double scale;
+                               if (jpeg.getScaleSlider().getValue() == 0)
+                                       scale = 1. / 100.;
+                               else
+                                       scale = jpeg.getScaleSlider().getValue() / 100.;
+                       BufferedImage myImage = new BufferedImage((int) Math.round(_vp
+                                       .getWidth() * scale), (int) Math.round(_vp.getHeight()
+                                       * scale), BufferedImage.TYPE_INT_RGB);
+                               Graphics2D g2 = myImage.createGraphics();
+                               AffineTransform AF = new AffineTransform();
+                               AF.setToScale(scale, scale);
+                               g2.setTransform(AF);
+                               _vp.paintComponent(g2);
+                               try {
+                               FileImageOutputStream out = new FileImageOutputStream(new File(
+                                               filename));
+                               ImageWriter writer = ImageIO
+                                               .getImageWritersByFormatName("jpeg").next();
+                                       ImageWriteParam params = writer.getDefaultWriteParam();
+                                       params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
+                                       params.setCompressionQuality(jpeg.getQualitySlider().getValue() / 100.0f);
+                                       writer.setOutput(out);
+                                       IIOImage myIIOImage = new IIOImage(myImage, null, null);
+                                       writer.write(null, myIIOImage, params);
+                                       out.close();
+                               } catch (IOException e) {
+                                       // cannot throw an exception from Runnable.run()
+                                       _vp.errorDialog(new ExceptionExportFailed(e.getMessage(), filename));
+                               }
+                       }
+
+               };
+               showConfirmDialog(jpeg.getPanel(), "Set resolution/quality", ok, null);
+       }
+
+       public void UIToggleShowNCBP() {
+               if (_vp.isModifiable()) {
+                       _vp.setShowNonCanonicalBP(!_vp.getShowNonCanonicalBP());
+                       _vp.repaint();
+               }
+       }
+
+       public void UIToggleColorSpecialBases() {
+               _vp.setColorNonStandardBases(!_vp.getColorSpecialBases());
+               _vp.repaint();
+       }
+
+       public void UIToggleColorGapsBases() {
+               _vp.setColorGapsBases(!_vp.getColorGapsBases());
+               _vp.repaint();
+       }
+
+       public void UIToggleShowNonPlanar() {
+               if (_vp.isModifiable()) {
+                       _vp.setShowNonPlanarBP(!_vp.getShowNonPlanarBP());
+                       _vp.repaint();
+               }
+       }
+
+       public void UIToggleShowWarnings() {
+               _vp.setShowWarnings(!_vp.getShowWarnings());
+               _vp.repaint();
+       }
+
+       public void UIPickSpecialBasesColor() {
+               showColorDialog("Choose new special bases color", _vp.getNonStandardBasesColor(), new Runnable() {
+
+                       @Override
+                       public void run() {
+                               if (dialogReturnValue != null) {
+                                       _vp.setNonStandardBasesColor((Color) dialogReturnValue);
+                                       _vp.setColorNonStandardBases(true);
+                                       _vp.repaint();
+                               }
+                       }
+                       
+               });
+       }
+
+       public void UIPickGapsBasesColor() {
+               showColorDialog("Choose new gaps bases color", _vp.getGapsBasesColor(), new Runnable() {
+
+                       @Override
+                       public void run() {
+                               if (dialogReturnValue != null) {
+                                       _vp.setGapsBasesColor((Color) dialogReturnValue);
+                                       _vp.setColorGapsBases(true);
+                                       _vp.repaint();
+                               }
+                       }
+                       
+               });
+       }
+
+       public void UIBaseTypeColor() {
+               if (_vp.isModifiable()) {
+                       new VueBases(_vp, VueBases.KIND_MODE);
+               }
+       }
+
+       public void UIToggleModifiable() {
+               _vp.setModifiable(!_vp.isModifiable());
+       }
+
+       public void UIBasePairTypeColor() {
+               if (_vp.isModifiable()) {
+                       new VueBases(_vp, VueBases.COUPLE_MODE);
+               }
+       }
+
+       public void UIBaseAllColor() {
+               if (_vp.isModifiable()) {
+                       new VueBases(_vp, VueBases.ALL_MODE);
+               }
+       }
+
+       public void UIAbout() {
+               final VueAboutPanel about = new VueAboutPanel();
+               Runnable ok = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               about.gracefulStop();
+                       }
+                       
+               };
+               showMessageDialog(about, "About VARNA " + VARNAConfig.MAJOR_VERSION + "." + VARNAConfig.MINOR_VERSION,
+                               JOptionPane.PLAIN_MESSAGE, ok, ok);
+       }
+
+       public void UIAutoAnnotateHelices() {
+               if (_vp.isModifiable()) {
+                       _vp.getRNA().autoAnnotateHelices();
+                       _vp.repaint();
+               }
+       }
+
+       public void UIAutoAnnotateStrandEnds() {
+               if (_vp.isModifiable()) {
+                       _vp.getRNA().autoAnnotateStrandEnds();
+                       _vp.repaint();
+               }
+       }
+
+       public void UIAutoAnnotateInteriorLoops() {
+               if (_vp.isModifiable()) {
+                       _vp.getRNA().autoAnnotateInteriorLoops();
+                       _vp.repaint();
+               }
+       }
+
+       public void UIAutoAnnotateTerminalLoops() {
+               if (_vp.isModifiable()) {
+                       _vp.getRNA().autoAnnotateTerminalLoops();
+                       _vp.repaint();
+               }
+       }
+
+       public void UIAnnotationRemoveFromAnnotation(TextAnnotation textAnnotation) {
+               if (_vp.isModifiable()) {
+                       _vp.set_selectedAnnotation(null);
+                       _vp.getListeAnnotations().remove(textAnnotation);
+                       _vp.repaint();
+               }
+       }
+
+       public void UIAnnotationEditFromAnnotation(TextAnnotation textAnnotation) {
+               VueAnnotation vue;
+               if (textAnnotation.getType() == TextAnnotation.AnchorType.POSITION)
+                       vue = new VueAnnotation(_vp, textAnnotation, false);
+               else
+                       vue = new VueAnnotation(_vp, textAnnotation, true, false);
+               vue.show();
+       }
+
+       public void UIAnnotationAddFromStructure(TextAnnotation.AnchorType type, ArrayList<Integer> listeIndex)
+                       throws Exception {
+               TextAnnotation textAnnot;
+               ArrayList<ModeleBase> listeBase;
+               VueAnnotation vue;
+               switch (type) {
+               case BASE:
+                       textAnnot = new TextAnnotation("", _vp.getRNA().get_listeBases()
+                                       .get(listeIndex.get(0)));
+                       vue = new VueAnnotation(_vp, textAnnot, true);
+                       vue.show();
+                       break;
+               case LOOP:
+                       listeBase = new ArrayList<ModeleBase>();
+                       for (Integer i : listeIndex) {
+                               listeBase.add(_vp.getRNA().get_listeBases().get(i));
+                       }
+                       textAnnot = new TextAnnotation("", listeBase, type);
+                       vue = new VueAnnotation(_vp, textAnnot, true);
+                       vue.show();
+                       break;
+               case HELIX:
+                       listeBase = new ArrayList<ModeleBase>();
+                       for (Integer i : listeIndex) {
+                               listeBase.add(_vp.getRNA().get_listeBases().get(i));
+                       }
+                       textAnnot = new TextAnnotation("", listeBase, type);
+                       vue = new VueAnnotation(_vp, textAnnot, true);
+                       vue.show();
+                       break;
+               default:
+                       _vp.errorDialog(new Exception("Unknown structure type"));
+                       break;
+               }
+       }
+
+       public void UIAnnotationEditFromStructure(TextAnnotation.AnchorType type,
+                       ArrayList<Integer> listeIndex) {
+               if (_vp.isModifiable()) {
+                       ModeleBase mb = _vp.getRNA().get_listeBases()
+                                       .get(listeIndex.get(0));
+                       TextAnnotation ta = _vp.getRNA().getAnnotation(type, mb);
+                       if (ta != null)
+                               UIAnnotationEditFromAnnotation(ta);
+               }
+       }
+
+       public void UIAnnotationRemoveFromStructure(TextAnnotation.AnchorType type,
+                       ArrayList<Integer> listeIndex) {
+               if (_vp.isModifiable()) {
+                       ModeleBase mb = _vp.getRNA().get_listeBases()
+                                       .get(listeIndex.get(0));
+                       TextAnnotation ta = _vp.getRNA().getAnnotation(type, mb);
+                       if (ta != null)
+                               UIAnnotationRemoveFromAnnotation(ta);
+               }
+       }
+
+       public void UIAnnotationsAddPosition(int x, int y) {
+               if (_vp.isModifiable()) {
+                       Point2D.Double p = _vp.panelToLogicPoint(new Point2D.Double(x, y));
+                       VueAnnotation annotationAdd = new VueAnnotation(_vp, (int) p.x,
+                                       (int) p.y);
+                       annotationAdd.show();
+               }
+       }
+
+       public void UIAnnotationsAddBase(int x, int y) {
+               if (_vp.isModifiable()) {
+                       ModeleBase mb = _vp.getBaseAt(new Point2D.Double(x, y));
+                       if (mb != null) {
+                               _vp.highlightSelectedBase(mb);
+                               TextAnnotation textAnnot = new TextAnnotation("", mb);
+                               VueAnnotation annotationAdd = new VueAnnotation(_vp, textAnnot,
+                                               true);
+                               annotationAdd.show();
+                       }
+               }
+       }
+
+       public void UIAnnotationsAddLoop(int x, int y) {
+               if (_vp.isModifiable()) {
+                       try {
+                               ModeleBase mb = _vp.getBaseAt(new Point2D.Double(x, y));
+                               if (mb != null) {
+                                       Vector<Integer> v = _vp.getRNA()
+                                                       .getLoopBases(mb.getIndex());
+                                       ArrayList<ModeleBase> mbs = _vp.getRNA().getBasesAt(v);
+                                       TextAnnotation textAnnot;
+                                       textAnnot = new TextAnnotation("", mbs,
+                                                       TextAnnotation.AnchorType.LOOP);
+                                       _vp.setSelection(mbs);
+                                       VueAnnotation annotationAdd = new VueAnnotation(_vp,
+                                                       textAnnot, true);
+                                       annotationAdd.show();
+                               }
+                       } catch (Exception e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+               }
+       }
+
+       private ArrayList<ModeleBase> extractMaxContiguousPortion(
+                       ArrayList<ModeleBase> m) {
+               ModeleBase[] tab = new ModeleBase[_vp.getRNA().getSize()];
+               for (int i = 0; i < tab.length; i++) {
+                       tab[i] = null;
+               }
+               for (ModeleBase mb : m) {
+                       tab[mb.getIndex()] = mb;
+               }
+               ArrayList<ModeleBase> best = new ArrayList<ModeleBase>();
+               ArrayList<ModeleBase> current = new ArrayList<ModeleBase>();
+               for (int i = 0; i < tab.length; i++) {
+                       if (tab[i] != null) {
+                               current.add(tab[i]);
+                       } else {
+                               if (current.size() > best.size())
+                                       best = current;
+                               current = new ArrayList<ModeleBase>();
+                       }
+               }
+               if (current.size() > best.size()) {
+                       best = current;
+               }
+               return best;
+       }
+
+       public void UIAnnotationsAddRegion(int x, int y) {
+               if (_vp.isModifiable()) {
+                       ArrayList<ModeleBase> mb = _vp.getSelection().getBases();
+                       if (mb.size() == 0) {
+                               ModeleBase m = _vp.getBaseAt(new Point2D.Double(x, y));
+                               mb.add(m);
+                       }
+                       mb = extractMaxContiguousPortion(extractMaxContiguousPortion(mb));
+                       _vp.setSelection(mb);
+                       HighlightRegionAnnotation regionAnnot = new HighlightRegionAnnotation(
+                                       mb);
+                       _vp.addHighlightRegion(regionAnnot);
+                       VueHighlightRegionEdit annotationAdd = new VueHighlightRegionEdit(
+                                       _vp, regionAnnot);
+                       if (!annotationAdd.show()) {
+                               _vp.removeHighlightRegion(regionAnnot);
+                       }
+                       _vp.clearSelection();
+               }
+       }
+
+       public void UIAnnotationsAddChemProb(int x, int y) {
+               if (_vp.isModifiable() && _vp.getRNA().getSize() > 1) {
+                       Point2D.Double p = _vp.panelToLogicPoint(new Point2D.Double(x, y));
+                       ModeleBase m1 = _vp.getBaseAt(new Point2D.Double(x, y));
+                       ModeleBase best = null;
+                       if (m1.getIndex() - 1 >= 0) {
+                               best = _vp.getRNA().getBaseAt(m1.getIndex() - 1);
+                       }
+                       if (m1.getIndex() + 1 < _vp.getRNA().getSize()) {
+                               ModeleBase m2 = _vp.getRNA().getBaseAt(m1.getIndex() + 1);
+                               if (best == null) {
+                                       best = m2;
+                               } else {
+                                       if (best.getCoords().distance(p) > m2.getCoords().distance(
+                                                       p)) {
+                                               best = m2;
+                                       }
+                               }
+                       }
+                       ArrayList<ModeleBase> tab = new ArrayList<ModeleBase>();
+                       tab.add(m1);
+                       tab.add(best);
+                       _vp.setSelection(tab);
+                       ChemProbAnnotation regionAnnot = new ChemProbAnnotation(m1, best);
+                       _vp.getRNA().addChemProbAnnotation(regionAnnot);
+                       VueChemProbAnnotation annotationAdd = new VueChemProbAnnotation(
+                                       _vp, regionAnnot);
+                       if (!annotationAdd.show()) {
+                               _vp.getRNA().removeChemProbAnnotation(regionAnnot);
+                       }
+                       _vp.clearSelection();
+               }
+       }
+
+       public void UIAnnotationsAddHelix(int x, int y) {
+               if (_vp.isModifiable()) {
+                       try {
+                               ModeleBase mb = _vp.getBaseAt(new Point2D.Double(x, y));
+                               if (mb != null) {
+                                       ArrayList<Integer> v = _vp.getRNA().findHelix(mb.getIndex());
+                                       ArrayList<ModeleBase> mbs = _vp.getRNA().getBasesAt(v);
+                                       TextAnnotation textAnnot;
+                                       textAnnot = new TextAnnotation("", mbs,
+                                                       TextAnnotation.AnchorType.HELIX);
+                                       _vp.setSelection(mbs);
+                                       VueAnnotation annotationAdd = new VueAnnotation(_vp,
+                                                       textAnnot, true);
+                                       annotationAdd.show();
+                               }
+                       } catch (Exception e) {
+                               // TODO Auto-generated catch block
+                               e.printStackTrace();
+                       }
+               }
+       }
+
+       public void UIToggleGaspinMode() {
+               if (_vp.isModifiable()) {
+                       _vp.toggleDrawOutlineBases();
+                       _vp.toggleFillBases();
+                       _vp.repaint();
+               }
+       }
+
+       public void UIAnnotationsAdd() {
+               if (_vp.isModifiable()) {
+                       VueAnnotation annotationAdd = new VueAnnotation(_vp);
+                       annotationAdd.show();
+               }
+       }
+
+       public void UIEditAllBasePairs() {
+               if (_vp.isModifiable()) {
+                       new VueBPList(_vp);
+               }
+       }
+
+       public void UIEditAllBases() {
+               if (_vp.isModifiable()) {
+                       new VueBases(_vp, VueBases.ALL_MODE);
+               }
+       }
+
+       public void UIAnnotationsRemove() {
+               if (_vp.isModifiable()) {
+                       new VueListeAnnotations(_vp, VueListeAnnotations.REMOVE);
+               }
+       }
+
+       public void UIAnnotationsEdit() {
+               if (_vp.isModifiable()) {
+                       new VueListeAnnotations(_vp, VueListeAnnotations.EDIT);
+               }
+       }
+
+       public void UIAddBP(int i, int j, ModeleBP ms) {
+               if (_vp.isModifiable()) {
+                       _vp.getRNA().addBP(i, j, ms);
+                       _undoableEditSupport.postEdit(new VARNAEdits.AddBPEdit(i, j, ms,
+                                       _vp));
+                       _vp.repaint();
+
+                       HashSet<ModeleBP> tmp = new HashSet<ModeleBP>();
+                       tmp.add(ms);
+                       _vp.fireStructureChanged(new HashSet<ModeleBP>(_vp.getRNA()
+                                       .getAllBPs()), tmp, new HashSet<ModeleBP>());
+               }
+       }
+
+       public void UIRemoveBP(ModeleBP ms) {
+               if (_vp.isModifiable()) {
+                       _undoableEditSupport.postEdit(new VARNAEdits.RemoveBPEdit(ms
+                                       .getIndex5(), ms.getIndex3(), ms, _vp));
+                       _vp.getRNA().removeBP(ms);
+                       _vp.repaint();
+
+                       HashSet<ModeleBP> tmp = new HashSet<ModeleBP>();
+                       tmp.add(ms);
+                       _vp.fireStructureChanged(new HashSet<ModeleBP>(_vp.getRNA()
+                                       .getAllBPs()), new HashSet<ModeleBP>(), tmp);
+               }
+       }
+
+       public void UIShiftBaseCoord(ArrayList<Integer> indices, double dx, double dy) {
+               if (_vp.isModifiable()) {
+                       Hashtable<Integer, Point2D.Double> backupPos = new Hashtable<Integer, Point2D.Double>();
+
+                       for (int index : indices) {
+                               ModeleBase mb = _vp.getRNA().getBaseAt(index);
+                               Point2D.Double d = mb.getCoords();
+                               backupPos.put(index, d);
+                               _vp.getRNA().setCoord(index, d.x + dx, d.y + dy);
+                               _vp.getRNA().setCenter(index, mb.getCenter().x + dx, mb.getCenter().y + dy);
+                       }
+                       _undoableEditSupport.postEdit(new VARNAEdits.BasesShiftEdit(
+                                       indices, dx, dy, _vp));
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(backupPos);
+               }
+       }
+
+       public void UIShiftBaseCoord(ArrayList<Integer> indices, Point2D.Double dv) {
+               UIShiftBaseCoord(indices, dv.x, dv.y);
+       }
+
+       public void UIMoveSingleBase(int index, double nx, double ny) {
+               if (_vp.isModifiable()) {
+                       ModeleBase mb = _vp.getRNA().getBaseAt(index);
+                       Point2D.Double d = mb.getCoords();
+                       Hashtable<Integer, Point2D.Double> backupPos = new Hashtable<Integer, Point2D.Double>();
+                       backupPos.put(index, d);
+                       _undoableEditSupport.postEdit(new VARNAEdits.SingleBaseMoveEdit(
+                                       index, nx, ny, _vp));
+                       _vp.getRNA().setCoord(index, nx, ny);
+                       _vp.repaint();
+                       _vp.fireLayoutChanged(backupPos);
+               }
+       }
+
+       public void UIMoveSingleBase(int index, Point2D.Double dv) {
+               UIMoveSingleBase(index, dv.x, dv.y);
+       }
+
+       public void UISetBaseCenter(int index, double x, double y) {
+               UISetBaseCenter(index, new Point2D.Double(x, y));
+       }
+
+       public void UISetBaseCenter(int index, Point2D.Double p) {
+               if (_vp.isModifiable()) {
+                       _vp.getRNA().setCenter(index, p);
+               }
+       }
+
+       public void UIUndo() {
+               _vp.undo();
+       }
+
+       public void UIRedo() {
+               _vp.redo();
+       }
+
+       /**
+        * Move a helix of the rna
+        * 
+        * @param index
+        *            :the index of the selected base
+        * @param newPos
+        *            :the new xy coordinate, within the logical system of
+        *            coordinates
+        */
+       public void UIMoveHelixAtom(int index, Point2D.Double newPos) {
+               if (_vp.isModifiable() && (index >= 0)
+                               && (index < _vp.getRNA().get_listeBases().size())) {
+                       int indexTo = _vp.getRNA().get_listeBases().get(index)
+                                       .getElementStructure();
+                       Point h = _vp.getRNA().getHelixInterval(index);
+                       Point ml = _vp.getRNA().getMultiLoop(h.x);
+                       int i = ml.x;
+                       if (indexTo != -1) {
+                               if (i == 0) {
+                                       if (shouldFlip(index, newPos)) {
+                                               UIFlipHelix(h);
+                                               _undoableEditSupport
+                                                               .postEdit(new VARNAEdits.HelixFlipEdit(h, _vp));
+                                       }
+                               } else {
+                                       UIRotateHelixAtom(index, newPos);
+                               }
+
+                       }
+                       _vp.fireLayoutChanged();
+               }
+       }
+
+       /**
+        * Flip an helix around its supporting base
+        */
+       public void UIFlipHelix(Point h) {
+               int hBeg = h.x;
+               int hEnd = h.y;
+               Point2D.Double A = _vp.getRNA().getCoords(hBeg);
+               Point2D.Double B = _vp.getRNA().getCoords(hEnd);
+               Point2D.Double AB = new Point2D.Double(B.x - A.x, B.y - A.y);
+               double normAB = Math.sqrt(AB.x * AB.x + AB.y * AB.y);
+               // Creating a coordinate system centered on A and having
+               // unit x-vector Ox.
+               Point2D.Double O = A;
+               Point2D.Double Ox = new Point2D.Double(AB.x / normAB, AB.y / normAB);
+               Hashtable<Integer, Point2D.Double> old = new Hashtable<Integer, Point2D.Double>();
+               for (int i = hBeg + 1; i < hEnd; i++) {
+                       Point2D.Double P = _vp.getRNA().getCoords(i);
+                       Point2D.Double nP = RNA.project(O, Ox, P);
+                       old.put(i, nP);
+               }
+               _vp.getRNA().flipHelix(h);
+               _vp.fireLayoutChanged(old);
+       }
+
+       /**
+        * Tests if an helix needs to be flipped.
+        */
+       boolean shouldFlip(int index, Point2D.Double P) {
+               Point h = _vp.getRNA().getHelixInterval(index);
+
+               Point2D.Double A = _vp.getRNA().getCoords(h.x);
+               Point2D.Double B = _vp.getRNA().getCoords(h.y);
+               Point2D.Double C = _vp.getRNA().getCoords(h.x + 1);
+               // Creating a vector that is orthogonal to AB
+               Point2D.Double hAB = new Point2D.Double(B.y - A.y, -(B.x - A.x));
+               Point2D.Double AC = new Point2D.Double(C.x - A.x, C.y - A.y);
+               Point2D.Double AP = new Point2D.Double(P.x - A.x, P.y - A.y);
+               double signC = (hAB.x * AC.x + hAB.y * AC.y);
+               double signP = (hAB.x * AP.x + hAB.y * AP.y);
+               // Now, the product signC*signP is negative iff the mouse and the first
+               // base inside
+               // the helix are on different sides of the end of the helix => Flip the
+               // helix!
+               return (signC * signP < 0.0);
+       }
+
+       public void UIRotateHelixAtom(int index, Point2D.Double newPos) {
+               Point h = _vp.getRNA().getHelixInterval(index);
+               Point ml = _vp.getRNA().getMultiLoop(h.x);
+               int i = ml.x;
+               int prevIndex = h.x;
+               int nextIndex = h.y;
+               while (i <= ml.y) {
+                       int j = _vp.getRNA().get_listeBases().get(i).getElementStructure();
+                       if ((j != -1) && (i < h.x)) {
+                               prevIndex = i;
+                       }
+                       if ((j != -1) && (i > h.y) && (nextIndex == h.y)) {
+                               nextIndex = i;
+                       }
+                       if ((j > i) && (j < ml.y)) {
+                               i = _vp.getRNA().get_listeBases().get(i).getElementStructure();
+                       } else {
+                               i++;
+                       }
+               }
+               Point2D.Double oldPos = _vp.getRNA().getCoords(index);
+               Point2D.Double limitLoopLeft, limitLoopRight, limitLeft, limitRight, helixStart, helixStop;
+               boolean isDirect = _vp.getRNA().testDirectionality(ml.x, ml.y, h.x);
+               if (isDirect) {
+                       limitLoopLeft = _vp.getRNA().getCoords(ml.y);
+                       limitLoopRight = _vp.getRNA().getCoords(ml.x);
+                       limitLeft = _vp.getRNA().getCoords(prevIndex);
+                       limitRight = _vp.getRNA().getCoords(nextIndex);
+                       helixStart = _vp.getRNA().getCoords(h.x);
+                       helixStop = _vp.getRNA().getCoords(h.y);
+               } else {
+                       limitLoopLeft = _vp.getRNA().getCoords(ml.x);
+                       limitLoopRight = _vp.getRNA().getCoords(ml.y);
+                       limitLeft = _vp.getRNA().getCoords(nextIndex);
+                       limitRight = _vp.getRNA().getCoords(prevIndex);
+                       helixStart = _vp.getRNA().getCoords(h.y);
+                       helixStop = _vp.getRNA().getCoords(h.x);
+               }
+
+               Point2D.Double center = _vp.getRNA().get_listeBases().get(h.x)
+                               .getCenter();
+               double base = (RNA.computeAngle(center, limitLoopRight) + RNA
+                               .computeAngle(center, limitLoopLeft)) / 2.0;
+               double pLimR = RNA.computeAngle(center, limitLeft) - base;
+               double pHelR = RNA.computeAngle(center, helixStart) - base;
+               double pNew = RNA.computeAngle(center, newPos) - base;
+               double pOld = RNA.computeAngle(center, oldPos) - base;
+               double pHelL = RNA.computeAngle(center, helixStop) - base;
+               double pLimL = RNA.computeAngle(center, limitRight) - base;
+
+               while (pLimR < 0.0)
+                       pLimR += 2.0 * Math.PI;
+               while (pHelR < pLimR)
+                       pHelR += 2.0 * Math.PI;
+               while ((pNew < pHelR))
+                       pNew += 2.0 * Math.PI;
+               while ((pOld < pHelR))
+                       pOld += 2.0 * Math.PI;
+               while ((pHelL < pOld))
+                       pHelL += 2.0 * Math.PI;
+               while ((pLimL < pHelL))
+                       pLimL += 2.0 * Math.PI;
+
+               double minDelta = normalizeAngle((pLimR - pHelR) + 0.25);
+               double maxDelta = normalizeAngle((pLimL - pHelL) - 0.25);
+               while (maxDelta < minDelta)
+                       maxDelta += 2.0 * Math.PI;
+               double delta = normalizeAngle(pNew - pOld);
+               while (delta < minDelta)
+                       delta += 2.0 * Math.PI;
+
+               if (delta > maxDelta) {
+                       double distanceMax = delta - maxDelta;
+                       double distanceMin = minDelta - (delta - 2.0 * Math.PI);
+                       if (distanceMin < distanceMax) {
+                               delta = minDelta;
+                       } else {
+                               delta = maxDelta;
+                       }
+               }
+               double corrected = RNA
+                               .correctHysteresis((delta + base + (pHelR + pHelL) / 2.));
+               delta = corrected - (base + (pHelR + pHelL) / 2.);
+               _undoableEditSupport.postEdit(new VARNAEdits.HelixRotateEdit(delta,
+                               base, pLimL, pLimR, h, ml, _vp));
+               UIRotateEverything(delta, base, pLimL, pLimR, h, ml);
+       }
+
+       public void UIRotateEverything(double delta, double base, double pLimL,
+                       double pLimR, Point h, Point ml) {
+               Hashtable<Integer, Point2D.Double> backupPos = new Hashtable<Integer, Point2D.Double>();
+               _vp.getRNA().rotateEverything(delta, base, pLimL, pLimR, h, ml,
+                               backupPos);
+               _vp.fireLayoutChanged(backupPos);
+       }
+
+       private double normalizeAngle(double angle) {
+               return normalizeAngle(angle, 0.0);
+       }
+
+       private double normalizeAngle(double angle, double base) {
+               while (angle < base) {
+                       angle += 2.0 * Math.PI;
+               }
+               while (angle >= (2.0 * Math.PI) - base) {
+                       angle -= 2.0 * Math.PI;
+               }
+               return angle;
+       }
+
+       public void UIThicknessBasePairs(ArrayList<ModeleBP> bases) {
+               final VueBPThickness vbpt = new VueBPThickness(_vp, bases);
+               Runnable cancel = new Runnable() {
+
+                       @Override
+                       public void run() {
+                               vbpt.restoreThicknesses();
+                               _vp.repaint();
+                       }
+                       
+               };
+               showConfirmDialog(vbpt.getPanel(), "Set base pair(s) thickness", null, cancel, cancel);
+       }
+       
+       
+
+}
diff --git a/src2/fr/orsay/lri/varna/views/VueZoom.java b/src2/fr/orsay/lri/varna/views/VueZoom.java
new file mode 100644 (file)
index 0000000..08b75f9
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ VARNA is a tool for the automated drawing, visualization and annotation of the secondary structure of RNA, designed as a companion software for web servers and databases.
+ Copyright (C) 2008  Kevin Darty, Alain Denise and Yann Ponty.
+ electronic mail : Yann.Ponty@lri.fr
+ paper mail : LRI, bat 490 Université Paris-Sud 91405 Orsay Cedex France
+
+ This file is part of VARNA version 3.1.
+ VARNA version 3.1 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 3 of the License, or (at your option) any later version.
+
+ VARNA version 3.1 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 VARNA version 3.1.
+ If not, see http://www.gnu.org/licenses.
+ */
+package fr.orsay.lri.varna.views;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
+
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JSlider;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import fr.orsay.lri.varna.VARNAPanel;
+import fr.orsay.lri.varna.controlers.ControleurSliderLabel;
+import fr.orsay.lri.varna.controlers.ControleurZoom;
+import fr.orsay.lri.varna.models.VARNAConfig;
+
+public class VueZoom implements ChangeListener {
+
+       private VARNAPanel _vp;
+       private JSlider zoomSlider, zoomAmountSlider;
+       private JPanel panel;
+
+       public VueZoom(VARNAPanel vp) {
+               _vp = vp;
+
+               JPanel pup = new JPanel();
+               JPanel pdown = new JPanel();
+               panel = new JPanel();
+               panel.setLayout(new GridLayout(2, 1));
+               pup.setLayout(new FlowLayout(FlowLayout.LEFT));
+               pdown.setLayout(new FlowLayout(FlowLayout.LEFT));
+
+               zoomSlider = new JSlider(JSlider.HORIZONTAL,
+                               (int) (VARNAConfig.MIN_ZOOM * 100),
+                               (int) (VARNAConfig.MAX_ZOOM * 100), (int) (_vp.getZoom() * 100));
+               // Turn on labels at major tick marks.
+               zoomSlider.setMajorTickSpacing(2000);
+               zoomSlider.setMinorTickSpacing(500);
+               zoomSlider.setPaintTicks(true);
+               zoomSlider.setPaintLabels(true);
+               zoomSlider.setPreferredSize(new Dimension(250, zoomSlider
+                               .getPreferredSize().height));
+               zoomSlider.addChangeListener(new ControleurZoom(this));
+
+               JLabel zoomValueLabel = new JLabel(String.valueOf(_vp.getZoom()));
+               zoomValueLabel.setPreferredSize(new Dimension(50, zoomValueLabel
+                               .getPreferredSize().height));
+               zoomSlider.addChangeListener(new ControleurSliderLabel(zoomValueLabel,
+                               true));
+
+               zoomAmountSlider = new JSlider(JSlider.HORIZONTAL,
+                               (int) (VARNAConfig.MIN_AMOUNT * 100),
+                               (int) (VARNAConfig.MAX_AMOUNT * 100), (int) (_vp
+                                               .getZoomIncrement() * 100));
+               // Turn on labels at major tick marks.
+               zoomAmountSlider.setMajorTickSpacing(50);
+               zoomAmountSlider.setMinorTickSpacing(10);
+               zoomAmountSlider.setPaintTicks(true);
+               zoomAmountSlider.setPaintLabels(true);
+               zoomAmountSlider.setPreferredSize(new Dimension(200, zoomAmountSlider
+                               .getPreferredSize().height));
+
+               JLabel zoomAmountValueLabel = new JLabel(String.valueOf(_vp
+                               .getZoomIncrement()));
+               zoomAmountValueLabel.setPreferredSize(new Dimension(50,
+                               zoomAmountValueLabel.getPreferredSize().height));
+               zoomAmountSlider.addChangeListener(new ControleurSliderLabel(
+                               zoomAmountValueLabel, true));
+               zoomAmountSlider.addChangeListener(this);
+
+               JLabel labelZ = new JLabel("Zoom:");
+               JLabel labelA = new JLabel("Increment:");
+
+               pup.add(labelZ);
+               pup.add(zoomSlider);
+               pup.add(zoomValueLabel);
+               pdown.add(labelA);
+               pdown.add(zoomAmountSlider);
+               pdown.add(zoomAmountValueLabel);
+               panel.add(pup);
+               panel.add(pdown);
+       }
+
+       public JPanel getPanel() {
+               return panel;
+       }
+
+       public double getZoom() {
+               return zoomSlider.getValue() / 100.0;
+       }
+
+       public double getZoomAmount() {
+               return zoomAmountSlider.getValue() / 100.0;
+       }
+
+       public VARNAPanel get_vp() {
+               return _vp;
+       }
+
+       public void stateChanged(ChangeEvent e) {
+               _vp.setZoomIncrement(getZoomAmount());
+       }
+}
diff --git a/src2/javajs/J2SIgnoreImport.java b/src2/javajs/J2SIgnoreImport.java
new file mode 100644 (file)
index 0000000..b92c82b
--- /dev/null
@@ -0,0 +1,7 @@
+package javajs;
+
+public @interface J2SIgnoreImport {
+
+       Class<?>[] value();
+
+}
diff --git a/src2/javajs/J2SRequireImport.java b/src2/javajs/J2SRequireImport.java
new file mode 100644 (file)
index 0000000..646cebd
--- /dev/null
@@ -0,0 +1,7 @@
+package javajs;
+
+public @interface J2SRequireImport {
+
+       Class<?>[] value();
+
+}
diff --git a/src2/javajs/_README.txt b/src2/javajs/_README.txt
new file mode 100644 (file)
index 0000000..e8c3779
--- /dev/null
@@ -0,0 +1,38 @@
+The javajs directory contains a variety of Java files that you are 
+encouraged to use in your project. It is self-contained, and the 
+classes and methods all work in Java as well as JavaScript. 
+
+These classes perform functions not standard in Java or provide
+classes that are particularly optimized for JavaScript (fewer overloaded 
+methods, especially). 
+
+-- creating (minimal) PDF files
+-- decoding and encoding image files
+-- working with binary, compound document, JSON, and zip data
+-- providing very efficient classes for vectors, matricies, and quaternions
+-- providing a java.lang.Thread subclass (JSThread) that can be used
+   wherever a thread is necessary; note that JSThread cannot sleep(), but
+   it provides a means of managing setTimeout callbacks that is very easy
+   to implement.
+-- providing two very important annotations:
+
+  @J2SIgnoreImport    Indicates that this class will never be used in JavaScript
+                      and thus does not need to be indicated as a dependency. In
+                      some cases, this annotation is necessary just to break a 
+                      cyclical dependency that Java somehow handles, but J2S does not.   
+   
+  @J2SRequireImport   Allows a SwingJS developer to work around J2S transpiler 
+                      issues that for some reason it is not indicating the need for 
+                      a dependent class. Typically this is because a static call
+                      to a static method in a class. 
+                      
+                      In addition, though, @J2SRequireImport can be used to "inject"
+                      JavaScript at a specific point in code loading. For example, 
+                      swingjs.plaf.JSSlider uses the following annotation to load 
+                      jQueryUI, fooling J2S to think that it is a "class" file. 
+                      
+                      @J2SRequireImport(swingjs.jquery.JQueryUI.class)
+                      
+
+All files in the javajs/util directory will be moved to j2s/JU by a build script.
+
diff --git a/src2/javajs/api/BytePoster.java b/src2/javajs/api/BytePoster.java
new file mode 100644 (file)
index 0000000..0b0f29a
--- /dev/null
@@ -0,0 +1,7 @@
+package javajs.api;
+
+public interface BytePoster {
+
+  String postByteArray(String fileName, byte[] bytes);
+
+}
diff --git a/src2/javajs/api/EigenInterface.java b/src2/javajs/api/EigenInterface.java
new file mode 100644 (file)
index 0000000..4a1b592
--- /dev/null
@@ -0,0 +1,15 @@
+package javajs.api;
+
+import javajs.util.V3;
+
+public interface EigenInterface {
+
+  EigenInterface setM(double[][] n);
+
+  double[] getEigenvalues();
+
+  void fillFloatArrays(V3[] eigenVectors, float[] eigenValues);
+
+  float[][] getEigenvectorsFloatTransposed();
+
+}
diff --git a/src2/javajs/api/GenericBinaryDocument.java b/src2/javajs/api/GenericBinaryDocument.java
new file mode 100644 (file)
index 0000000..823bd2a
--- /dev/null
@@ -0,0 +1,40 @@
+package javajs.api;
+
+import java.io.BufferedInputStream;
+import java.io.DataInputStream;
+import java.io.InputStream;
+import java.util.Map;
+
+
+import javajs.util.SB;
+
+public interface GenericBinaryDocument extends GenericBinaryDocumentReader {
+
+  GenericBinaryDocument setStream(BufferedInputStream bis, boolean isBigEndian);
+
+  void setStreamData(DataInputStream dataInputStream, boolean isBigEndian);
+
+  long getPosition();
+
+  SB getAllDataFiles(String binaryFileList, String firstFile);
+
+  void getAllDataMapped(String replace, String string, Map<String, String> fileData);
+
+  int swapBytesI(int nx);
+
+  short swapBytesS(short s);
+
+  void seek(long i);
+
+  void setOutputChannel(GenericOutputChannel out);
+
+  InputStream getInputStream();
+
+  int readIntLE() throws Exception;
+
+  int readByteArray(byte[] b, int off, int len) throws Exception;
+
+
+  void close();
+
+}
diff --git a/src2/javajs/api/GenericBinaryDocumentReader.java b/src2/javajs/api/GenericBinaryDocumentReader.java
new file mode 100644 (file)
index 0000000..aea6f63
--- /dev/null
@@ -0,0 +1,25 @@
+package javajs.api;
+
+public interface GenericBinaryDocumentReader {
+
+  byte readByte() throws Exception;
+
+  byte[] readBytes(int n) throws Exception;
+
+  int readUInt8() throws Exception;
+
+  int readInt() throws Exception;
+
+  short readShort() throws Exception;
+
+  int readUnsignedShort() throws Exception;
+
+  long readLong() throws Exception;
+
+  float readFloat() throws Exception;
+
+  double readDouble() throws Exception;
+
+  String readString(int i) throws Exception;
+
+}
diff --git a/src2/javajs/api/GenericCifDataParser.java b/src2/javajs/api/GenericCifDataParser.java
new file mode 100644 (file)
index 0000000..81a71f7
--- /dev/null
@@ -0,0 +1,45 @@
+package javajs.api;
+
+import java.io.BufferedReader;
+import java.util.Map;
+
+
+public interface GenericCifDataParser {
+
+  static final int NONE = -1;
+
+  String fullTrim(String str);
+
+  Map<String, Object> getAllCifData();
+
+  boolean getData() throws Exception;
+
+  String getColumnName(int i);
+
+  int getColumnCount();
+
+  String getFileHeader();
+
+  Object peekToken() throws Exception;
+
+  Object getTokenPeeked();
+
+  Object getColumnData(int i);
+
+  Object getNextDataToken() throws Exception;
+
+  String getNextToken() throws Exception;
+
+  void parseDataBlockParameters(String[] fields, String key, String data, int[] key2col, int[] col2key) throws Exception;
+
+  String readLine();
+
+  GenericCifDataParser set(GenericLineReader reader, BufferedReader br, boolean debugging);
+
+  String toUnicode(String data);
+
+  String skipLoop(boolean doReport) throws Exception;
+
+  String fixKey(String key);
+
+}
diff --git a/src2/javajs/api/GenericColor.java b/src2/javajs/api/GenericColor.java
new file mode 100644 (file)
index 0000000..57cf169
--- /dev/null
@@ -0,0 +1,19 @@
+package javajs.api;
+
+/**
+ * GenericColor allows both java.awt.Color and javajs.awt.Color to be
+ * handled by methods that need not distinguish between them. It is used
+ * in the javajs package for the background color of a javajs.swing.JComponent
+ * 
+ * @author hansonr
+ *
+ */
+public interface GenericColor {
+
+       int getRGB();
+
+       int getOpacity255();
+
+       void setOpacity255(int a);
+       
+}
diff --git a/src2/javajs/api/GenericImageDialog.java b/src2/javajs/api/GenericImageDialog.java
new file mode 100644 (file)
index 0000000..54d8503
--- /dev/null
@@ -0,0 +1,9 @@
+package javajs.api;
+
+public interface GenericImageDialog {
+
+  void closeMe();
+
+  void setImage(Object image);
+
+}
diff --git a/src2/javajs/api/GenericImageEncoder.java b/src2/javajs/api/GenericImageEncoder.java
new file mode 100644 (file)
index 0000000..9aa7477
--- /dev/null
@@ -0,0 +1,12 @@
+package javajs.api;
+
+import java.util.Map;
+
+import javajs.util.OC;
+
+public interface GenericImageEncoder {
+
+  public boolean createImage(String type, OC out,
+                             Map<String, Object> params) throws Exception;
+
+}
diff --git a/src2/javajs/api/GenericLineReader.java b/src2/javajs/api/GenericLineReader.java
new file mode 100644 (file)
index 0000000..f113a8b
--- /dev/null
@@ -0,0 +1,5 @@
+package javajs.api;
+
+public interface GenericLineReader {
+  public String readNextLine() throws Exception;
+}
diff --git a/src2/javajs/api/GenericOutputChannel.java b/src2/javajs/api/GenericOutputChannel.java
new file mode 100644 (file)
index 0000000..73649d7
--- /dev/null
@@ -0,0 +1,22 @@
+package javajs.api;
+
+public interface GenericOutputChannel {
+
+  boolean isBigEndian();
+
+  void writeByteAsInt(int b);
+
+  void write(byte[] b, int off, int n);
+
+  void writeInt(int i);
+
+  void reset();
+
+  String closeChannel();
+
+  void writeLong(long b);
+
+  void writeShort(short i);
+
+
+}
diff --git a/src2/javajs/api/GenericZipInputStream.java b/src2/javajs/api/GenericZipInputStream.java
new file mode 100644 (file)
index 0000000..e2e8018
--- /dev/null
@@ -0,0 +1,13 @@
+package javajs.api;
+
+
+import java.io.InputStream;
+import java.util.zip.ZipInputStream;
+
+public class GenericZipInputStream extends ZipInputStream implements ZInputStream {
+  
+  public GenericZipInputStream(InputStream in) {
+    super(in);
+  }
+  
+}
\ No newline at end of file
diff --git a/src2/javajs/api/GenericZipTools.java b/src2/javajs/api/GenericZipTools.java
new file mode 100644 (file)
index 0000000..47a2da2
--- /dev/null
@@ -0,0 +1,47 @@
+package javajs.api;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import java.util.Map;
+
+
+public interface GenericZipTools {
+
+  public ZInputStream newZipInputStream(InputStream is);
+  
+  public String getZipDirectoryAsStringAndClose(BufferedInputStream t);
+
+  public InputStream newGZIPInputStream(InputStream bis) throws IOException;
+
+  public InputStream newBZip2InputStream(InputStream bis) throws IOException;
+
+  public Object getZipFileDirectory(BufferedInputStream bis,
+                                          String[] subFileList, int listPtr, boolean asBufferedInputStream);
+
+  public String[] getZipDirectoryAndClose(BufferedInputStream t,
+                                                 String manifestID);
+
+  public void getAllZipData(InputStream bis, String[] subFileList,
+                                String replace, String binaryFileList, String exclude,
+                                Map<String, String> fileData);
+
+  public Object getZipFileContentsAsBytes(BufferedInputStream bis,
+                                                 String[] subFileList, int i);
+
+  public void addZipEntry(Object zos, String fileName) throws IOException;
+
+  public void closeZipEntry(Object zos) throws IOException;
+
+  public Object getZipOutputStream(Object bos);
+
+  public int getCrcValue(byte[] bytes);
+
+  public void readFileAsMap(BufferedInputStream is, Map<String, Object> bdata, String name);
+
+  public String cacheZipContents(BufferedInputStream bis, String shortName,
+                                 Map<String, Object> cache, boolean asByteArray);
+
+  BufferedInputStream getUnGzippedInputStream(byte[] bytes);
+}
diff --git a/src2/javajs/api/Interface.java b/src2/javajs/api/Interface.java
new file mode 100644 (file)
index 0000000..418d528
--- /dev/null
@@ -0,0 +1,54 @@
+/* $RCSfile$
+ * $Author$
+ * $Date$
+ * $Revision$
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2006  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301, USA.
+ */
+
+package javajs.api;
+
+public class Interface {
+
+  public static Object getInterface(String name) {
+    try {
+      Class<?> x = Class.forName(name);
+      return (x == null ? null : x.newInstance());
+    } catch (Exception e) {
+      System.out.println("Interface.getInterface Error creating instance for " + name + ": \n" + e);
+      return null;
+    }
+  }
+  
+       public static Object getInstanceWithParams(String name, Class<?>[] classes, Object... params) {
+               try {
+                       Class<?> cl = Class.forName(name);
+                       return  cl.getConstructor(classes).newInstance(params);
+               } catch (Exception e) {
+      System.out.println("Interface.getInterfaceWithParams Error creating instance for " + name + ": \n" + e);
+                       return null;
+               }
+       }
+
+
+}
diff --git a/src2/javajs/api/JSFunction.java b/src2/javajs/api/JSFunction.java
new file mode 100644 (file)
index 0000000..1c6c108
--- /dev/null
@@ -0,0 +1,12 @@
+package javajs.api;
+
+/**
+ * A flag that this object is really a JavaScript function that, for example,
+ * might be called from setTimeout(). 
+ * 
+ * @author Bob Hanson
+ *
+ */
+public interface JSFunction {
+
+}
diff --git a/src2/javajs/api/JSInterface.java b/src2/javajs/api/JSInterface.java
new file mode 100644 (file)
index 0000000..0f785fa
--- /dev/null
@@ -0,0 +1,30 @@
+package javajs.api;
+
+/** 
+ * called by JSmol JavaScript methods using
+ * 
+ *  this._applet.xxxx()
+ *  
+ */
+public interface JSInterface {
+
+  int cacheFileByName(String fileName, boolean isAdd);
+  void cachePut(String key, Object data);
+  void destroy();
+  String getFullName();
+  void openFileAsyncSpecial(String fileName, int flags);
+  boolean processMouseEvent(int id, int x, int y, int modifiers, long time);
+  void processTwoPointGesture(float[][][] touches);
+  void setDisplay(Object canvas);
+  void setScreenDimension(int width, int height);
+  boolean setStatusDragDropped(int mode, int x, int y, String fileName);
+       void startHoverWatcher(boolean enable);
+       void update();
+
+       // these are not general methods
+//Object getGLmolView();
+//String loadInlineString(String mol, String script, boolean isAppend);
+//String openFile(String fileName);
+
+}
+
diff --git a/src2/javajs/api/JSONEncodable.java b/src2/javajs/api/JSONEncodable.java
new file mode 100644 (file)
index 0000000..b013279
--- /dev/null
@@ -0,0 +1,7 @@
+package javajs.api;
+
+public interface JSONEncodable {
+
+  String toJSON();
+
+}
diff --git a/src2/javajs/api/ResettableStream.java b/src2/javajs/api/ResettableStream.java
new file mode 100644 (file)
index 0000000..5ded55f
--- /dev/null
@@ -0,0 +1,7 @@
+package javajs.api;
+
+public interface ResettableStream {
+
+       void resetStream();
+
+}
diff --git a/src2/javajs/api/ZInputStream.java b/src2/javajs/api/ZInputStream.java
new file mode 100644 (file)
index 0000000..a3310f6
--- /dev/null
@@ -0,0 +1,6 @@
+package javajs.api;
+
+public interface ZInputStream {
+  // placeholder for ZipInputStream not requiring direct access to java.util.zip
+
+}
diff --git a/src2/javajs/api/js/J2SObjectInterface.java b/src2/javajs/api/js/J2SObjectInterface.java
new file mode 100644 (file)
index 0000000..687f642
--- /dev/null
@@ -0,0 +1,12 @@
+package javajs.api.js;
+
+/**
+ * methods in JSmol JavaScript accessed in Jmol 
+ */
+public interface J2SObjectInterface {
+
+  Object _doAjax(Object url, String postOut, Object bytesOrStringOut, boolean isBinary);
+
+  void _apply(Object func, Object data);
+
+}
diff --git a/src2/javajs/api/js/JSInterface.java b/src2/javajs/api/js/JSInterface.java
new file mode 100644 (file)
index 0000000..9b26631
--- /dev/null
@@ -0,0 +1,41 @@
+package javajs.api.js;
+
+/**
+ * called by JSmol JavaScript methods using
+ * 
+ * this._applet.xxxx()
+ * 
+ */
+public interface JSInterface {
+
+       int cacheFileByName(String fileName, boolean isAdd);
+
+       void cachePut(String key, Object data);
+
+       void destroy();
+
+       String getFullName();
+
+       void openFileAsyncSpecial(String fileName, int flags);
+
+       boolean processMouseEvent(int id, int x, int y, int modifiers, long time);
+
+       void processTwoPointGesture(float[][][] touches);
+
+       void setDisplay(Object canvas);
+
+       void setScreenDimension(int width, int height);
+
+       boolean setStatusDragDropped(int mode, int x, int y, String fileName);
+
+       void startHoverWatcher(boolean enable);
+       
+       
+
+       // these are not general methods
+       // Object getGLmolView();
+       // String loadInlineString(String mol, String script, boolean isAppend);
+       // String openFile(String fileName);
+
+}
+
diff --git a/src2/javajs/export/PDFCreator.java b/src2/javajs/export/PDFCreator.java
new file mode 100644 (file)
index 0000000..8306d94
--- /dev/null
@@ -0,0 +1,367 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2009-06-30 18:58:33 -0500 (Tue, 30 Jun 2009) $
+ * $Revision: 11158 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2002-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.export;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javajs.util.Lst;
+import javajs.util.SB;
+
+
+
+public class PDFCreator {
+  private OutputStream os;
+  private Lst<PDFObject> indirectObjects;
+  private PDFObject root;
+  private PDFObject graphics; 
+//  private PDFObject pageResources;
+//  private PDFObject graphicsResources;
+
+  private int pt;
+  private int xrefPt;
+  private int count;
+
+  private int height;
+  private int width;
+  
+  private Map<String, PDFObject>fonts;
+
+  public PDFCreator() {
+   // for Class.forName  
+  }
+
+  public void setOutputStream(OutputStream os) {
+    this.os = os;
+  }
+
+  public void newDocument(int paperWidth, int paperHeight, boolean isLandscape) {
+    width = (isLandscape ? paperHeight : paperWidth);
+    height = (isLandscape ? paperWidth : paperHeight);
+    System.out.println("Creating PDF with width=" + width + " and height=" + height);
+    fonts = new Hashtable<String, PDFObject>();
+    indirectObjects = new Lst<PDFObject>();
+    //graphicsResources = newObject(null);
+    //pageResources = newObject(null); // will set this to compressed stream later
+    root = newObject("Catalog");
+    PDFObject pages = newObject("Pages");
+    PDFObject page = newObject("Page");
+    PDFObject pageContents = newObject(null);
+    graphics = newObject("XObject");
+    
+    root.addDef("Pages", pages.getRef());
+    pages.addDef("Count", "1");
+    pages.addDef("Kids", "[ " + page.getRef() +" ]");
+    page.addDef("Parent", pages.getRef());
+    page.addDef("MediaBox", "[ 0 0 " + paperWidth + " " + paperHeight + " ]");
+    if (isLandscape)
+      page.addDef("Rotate", "90");
+
+    pageContents.addDef("Length", "?");
+    pageContents.append((isLandscape ? "q 0 1 1 0 0 0 " : "q 1 0 0 -1 0 "+(paperHeight))+" cm /" + graphics.getID() + " Do Q");
+    page.addDef("Contents", pageContents.getRef());   
+    addProcSet(page);
+    addProcSet(graphics);
+    // will add fonts as well as they are needed
+    graphics.addDef("Subtype", "/Form");
+    graphics.addDef("FormType", "1");
+    graphics.addDef("BBox", "[0 0 " + width + " " + height + "]");
+    graphics.addDef("Matrix", "[1 0 0 1 0 0]");
+    graphics.addDef("Length", "?");
+    page.addResource("XObject", graphics.getID(), graphics.getRef());   
+    g("q 1 w 1 J 1 j 10 M []0 d q "); // line width 1, line cap circle, line join circle, miter limit 10, solid
+    clip(0, 0, width, height);
+  }   
+
+  private void addProcSet(PDFObject o) {
+    o.addResource(null, "ProcSet", "[/PDF /Text /ImageB /ImageC /ImageI]");
+  }
+
+  private void clip(int x1, int y1, int x2, int y2) {
+    moveto(x1, y1);
+    lineto(x2, y1);
+    lineto(x2, y2);
+    lineto(x1, y2);
+    g("h W n");
+  }
+
+  public void moveto(int x, int y) {
+    g(x + " " + y  + " m");
+  }
+
+  public void lineto(int x, int y) {
+    g(x + " " + y  + " l");
+  }
+
+  private PDFObject newObject(String type) {
+    PDFObject o = new PDFObject(++count);
+    if (type != null)
+      o.addDef("Type", "/" + type);
+    indirectObjects.addLast(o);
+    return o;
+  }
+
+  public void addInfo(Map<String, String> data) {
+    Hashtable<String, Object> info = new Hashtable<String, Object>();
+    for (Entry<String, String> e: data.entrySet()) {
+      String value = "(" + e.getValue().replace(')','_').replace('(','_')+ ")";
+      info.put(e.getKey(), value);      
+    }
+    root.addDef("Info", info);
+  }
+
+  private PDFObject addFontResource(String fname) {
+    PDFObject f = newObject("Font");
+    fonts.put(fname, f);
+    f.addDef("BaseFont", fname);
+    f.addDef("Encoding", "/WinAnsiEncoding");
+    f.addDef("Subtype", "/Type1");
+    graphics.addResource("Font", f.getID(), f.getRef());
+    return f;
+  }
+
+  private Map<Object, PDFObject> images;
+  
+  public void addImageResource(Object newImage, int width, int height, int[] buffer, boolean isRGB) {
+    PDFObject imageObj = newObject("XObject");
+    if (images == null)
+      images = new Hashtable<Object, PDFObject>();
+    images.put(newImage, imageObj);   
+    imageObj.addDef("Subtype", "/Image");
+    imageObj.addDef("Length", "?");
+    imageObj.addDef("ColorSpace", isRGB ? "/DeviceRGB" : "/DeviceGray");
+    imageObj.addDef("BitsPerComponent", "8");
+    imageObj.addDef("Width", "" + width);
+    imageObj.addDef("Height", "" + height);
+    graphics.addResource("XObject", imageObj.getID(), imageObj.getRef());
+    int n = buffer.length;
+    byte[] stream = new byte[n * (isRGB ? 3 : 1)];
+    if (isRGB) {
+      for (int i = 0, pt = 0; i < n; i++) {
+        stream[pt++] = (byte) ((buffer[i] >> 16) & 0xFF);
+        stream[pt++] = (byte) ((buffer[i] >> 8) & 0xFF);
+        stream[pt++] = (byte) (buffer[i] & 0xFF);
+      }
+    } else {
+      for (int i = 0; i < n; i++)
+        stream[i] = (byte) buffer[i];
+    }
+    imageObj.setStream(stream);
+    graphics.addResource("XObject", imageObj.getID(), imageObj.getRef());
+  }
+
+  public void g(String cmd) {
+    graphics.append(cmd).appendC('\n');
+  }
+
+  private void output(String s) throws IOException {
+   byte[] b = s.getBytes();
+   os.write(b, 0, b.length);
+   pt += b.length;
+  }
+
+  public void closeDocument() throws IOException {
+    g("Q Q");
+    outputHeader();
+    writeObjects();
+    writeXRefTable();
+    writeTrailer();
+    os.flush();
+    os.close();
+  }
+
+  private void outputHeader() throws IOException {
+    output("%PDF-1.3\n%");
+    byte[] b = new byte[] {-1, -1, -1, -1};
+    os.write(b, 0, b.length);
+    pt += 4;
+    output("\n");
+  }
+
+  private void writeTrailer() throws IOException {
+    PDFObject trailer = new PDFObject(-2);
+    output("trailer");
+    trailer.addDef("Size", "" + indirectObjects.size());
+    trailer.addDef("Root", root.getRef());
+    trailer.output(os);
+    output("startxref\n");
+    output("" + xrefPt + "\n");
+    output("%%EOF\n");
+  }
+
+  /**
+   * Write Font objects first.
+   * 
+   * @throws IOException
+   */
+  private void writeObjects() throws IOException {
+    int nObj = indirectObjects.size();
+    for (int i = 0; i < nObj; i++) {
+      PDFObject o = indirectObjects.get(i);
+      if (!o.isFont())
+        continue;
+      o.pt = pt;
+      pt += o.output(os);
+    }
+    for (int i = 0; i < nObj; i++) {
+      PDFObject o = indirectObjects.get(i);
+      if (o.isFont())
+        continue;
+      o.pt = pt;
+      pt += o.output(os);
+    }
+  }
+
+  private void writeXRefTable() throws IOException {
+    xrefPt = pt;
+    int nObj = indirectObjects.size();
+    SB sb = new SB();
+    // note trailing space, needed because \n is just one character
+    sb.append("xref\n0 " + (nObj + 1) 
+        + "\n0000000000 65535 f\r\n");
+    for (int i = 0; i < nObj; i++) {
+      PDFObject o = indirectObjects.get(i);
+      String s = "0000000000" + o.pt;
+      sb.append(s.substring(s.length() - 10));
+      sb.append(" 00000 n\r\n");
+    }
+    output(sb.toString());
+  }
+
+  public boolean canDoLineTo() {
+    return true;
+  }
+
+  public void fill() {
+    g("f");   
+  }
+
+  public void stroke() {
+    g("S");   
+  }
+
+  public void doCircle(int x, int y, int r, boolean doFill) {
+    double d = r*4*(Math.sqrt(2)-1)/3;
+    double dx = x;
+    double dy = y;
+    g((dx + r) + " " + dy + " m");
+    g((dx + r) + " " + (dy + d) + " " + (dx + d) + " " + (dy + r) + " " + (dx) + " " + (dy + r) + " "  + " c");
+    g((dx - d) + " " + (dy + r) + " " + (dx - r) + " " + (dy + d) + " " + (dx - r) + " " + (dy) + " c");
+    g((dx - r) + " " + (dy - d) + " " + (dx - d) + " " + (dy - r) + " " + (dx) + " " + (dy - r) + " c");
+    g((dx + d) + " " + (dy - r) + " " + (dx + r) + " " + (dy - d) + " " + (dx + r) + " " + (dy) + " c");
+    g(doFill ? "f" : "s");
+  }
+
+  public void doPolygon(int[] axPoints, int[] ayPoints, int nPoints, boolean doFill) {
+    moveto(axPoints[0], ayPoints[0]);
+    for (int i = 1; i < nPoints; i++)
+      lineto(axPoints[i], ayPoints[i]);
+    g(doFill ? "f" : "s");
+  }
+
+  public void doRect(int x, int y, int width, int height, boolean doFill) {
+    g(x + " " + y + " " + width + " " + height + " re " + (doFill ? "f" : "s"));
+  }
+
+  public void drawImage(Object image, int destX0, int destY0,
+      int destX1, int destY1, int srcX0, int srcY0, int srcX1, int srcY1) {
+    PDFObject imageObj = images.get(image);
+    if (imageObj == null)
+      return;
+    g("q");
+    clip(destX0, destY0, destX1, destY1);
+    double iw = Double.parseDouble((String) imageObj.getDef("Width"));
+    double ih = Double.parseDouble((String) imageObj.getDef("Height"));   
+    double dw = (destX1 - destX0 + 1);
+    double dh  = (destY1 - destY0 + 1);
+    double sw = (srcX1 - srcX0 + 1);
+    double sh = (srcY1 - srcY0 + 1);
+    double scaleX = dw / sw;
+    double scaleY = dh / sh;
+    double transX = destX0 - srcX0 * scaleX;
+    double transY = destY0 + (ih - srcY0) * scaleY;
+    g(scaleX*iw + " 0 0 " + -scaleY*ih + " " + transX + " " + transY + " cm");
+    g("/" + imageObj.getID() + " Do");
+    g("Q");
+  }
+
+  public void drawStringRotated(String s, int x, int y, int angle) {
+    g("q " + getRotation(angle) + " " + x + " " + y
+        + " cm BT(" + s + ")Tj ET Q");
+  }
+
+  public String getRotation(int angle) {    
+    float cos = 0, sin = 0;
+    switch (angle) {
+    case 0:
+      cos = 1;
+      break;
+    case 90:
+      sin = 1;
+      break;
+    case -90:
+      sin = -1;
+      break;
+    case 180:
+      cos = -1;
+      break;
+    default:
+      float a = (float) (angle * (Math.PI / 180));
+      cos = (float) Math.cos(a);
+      sin = (float) Math.sin(a);
+      if (Math.abs(cos) < 0.0001)
+        cos = 0;
+      if (Math.abs(sin) < 0.0001)
+        sin = 0;
+    }
+    return  cos + " " + sin + " " + sin + " " + -cos;
+  }
+
+  public void setColor(float[] rgb, boolean isFill) {
+    g(rgb[0] + " " + rgb[1] + " " + rgb[2] + (isFill ? " rg" : " RG"));
+  }
+
+  public void setFont(String fname, float size) {
+    PDFObject f = fonts.get(fname);
+    if (f == null)
+      f = addFontResource(fname);
+    g("/" + f.getID() + " " + size + " Tf");
+  }
+
+  public void setLineWidth(float width) {
+    g(width + " w");    
+  }
+
+  public void translateScale(float x, float y, float scale) {
+    g(scale + " 0 0 " + scale + " " + x + " " + y + " cm");
+  }
+
+}
diff --git a/src2/javajs/export/PDFObject.java b/src2/javajs/export/PDFObject.java
new file mode 100644 (file)
index 0000000..176dc19
--- /dev/null
@@ -0,0 +1,152 @@
+package javajs.export;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterOutputStream;
+
+import javajs.util.SB;
+
+
+/**
+ * A rudimentary class for working with PDF document creation.
+ * Written from scratch based on PDF Reference 13.
+ * 
+ * @author hansonr  Bob Hanson hansonr@stolaf.edu  10/28/2013
+ * 
+ */
+class PDFObject extends SB {   
+       private Map<String, Object> dictionary;
+       private byte[] stream;
+       private int index;
+       String type;
+       int len;
+       int pt;
+       
+       PDFObject(int index) {
+               this.index = index;
+       }
+
+       String getRef() {
+               return index + " 0 R";
+       }
+       
+       String getID() {
+               return type.substring(0, 1) + index;
+       }
+       
+       boolean isFont() {
+               return "Font".equals(type);
+       }
+
+       void setStream(byte[] stream) {
+               this.stream = stream;
+       }
+
+       Object getDef(String key) {
+               return dictionary.get(key);
+       }
+       
+       void addDef(String key, Object value) {
+               if (dictionary  == null)
+                       dictionary = new Hashtable<String, Object>();
+               dictionary.put(key, value);
+               if (key.equals("Type"))
+                       type = ((String) value).substring(1);
+       }
+       
+       void setAsStream() {
+               stream = toBytes(0, -1);
+               setLength(0);
+       }
+       
+       int output(OutputStream os) throws IOException {
+               if (index > 0) {
+                       String s = index + " 0 obj\n";
+                       write(os, s.getBytes(), 0);
+               }
+               int streamLen = 0;
+               if (dictionary != null) {
+                       if (dictionary.containsKey("Length")) {
+                               if (stream == null)
+                                       setAsStream();
+                               streamLen = stream.length;
+                               boolean doDeflate = (streamLen > 1000);
+        if (doDeflate) {
+          Deflater deflater = new Deflater(9);
+          ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024);
+          DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes,
+              deflater);
+          compBytes.write(stream, 0, streamLen);
+          compBytes.finish();
+          stream = outBytes.toByteArray();
+          dictionary.put("Filter", "/FlateDecode");
+          streamLen = stream.length;
+        }
+                               dictionary.put("Length", "" + streamLen);
+                       }
+                       write(os, getDictionaryText(dictionary, "\n").getBytes(), 0);
+               }
+               if (length() > 0)
+                       write(os, this.toString().getBytes(), 0);
+               if (stream != null) {
+                       write(os, "stream\r\n".getBytes(), 0);
+                       write(os, stream, streamLen);
+                       write(os, "\r\nendstream\r\n".getBytes(), 0);
+               }
+               if (index > 0)
+                       write(os, "endobj\n".getBytes(), 0);
+               return len;
+       }
+
+       private void write(OutputStream os, byte[] bytes, int nBytes) throws IOException {
+               if (nBytes == 0)
+                       nBytes = bytes.length;
+               len += nBytes;
+               os.write(bytes, 0, nBytes);
+       }
+
+       @SuppressWarnings("unchecked")
+       private String getDictionaryText(Map<String, Object> d, String nl) {
+               SB sb = new SB();
+               sb.append("<<");
+               if (d.containsKey("Type"))
+                       sb.append("/Type").appendO(d.get("Type"));
+               for (Entry<String, Object> e : d.entrySet()) {
+                       String s = e.getKey();
+                       if (s.equals("Type") || s.startsWith("!"))
+                               continue;
+                       sb.append("/" + s);
+                       Object o = e.getValue();
+                       if (o instanceof Map<?, ?>) {
+                               sb.append((getDictionaryText((Map<String, Object>) o, "")));
+                               continue;
+                       }
+                       s = (String) e.getValue();
+                       if (!s.startsWith("/"))
+                               sb.append(" ");
+                       sb.appendO(s);
+               }
+               return (sb.length() > 3 ? sb.append(">>").append(nl).toString() : "");
+       }
+
+       @SuppressWarnings("unchecked")
+       private Map<String, Object> createSubdict(Map<String, Object> d0, String dict) {
+               Map<String, Object> d = (Map<String, Object>) d0.get(dict);
+               if (d == null)
+                       d0.put(dict, d = new Hashtable<String, Object>());
+               return d;
+       }
+
+       void addResource(String type, String key, String value) {
+               Map<String, Object> r = createSubdict(dictionary, "Resources");
+               if (type != null)
+                       r = createSubdict(r, type);
+               r.put(key, value);
+       }
+       
+}
diff --git a/src2/javajs/img/BMPDecoder.java b/src2/javajs/img/BMPDecoder.java
new file mode 100644 (file)
index 0000000..4c94c9b
--- /dev/null
@@ -0,0 +1,211 @@
+/* $RCSfile$
+ * $Author: nicove $
+ * $Date: 2007-03-30 12:26:16 -0500 (Fri, 30 Mar 2007) $
+ * $Revision: 7275 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2002-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.img;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+
+import javajs.util.Rdr;
+
+/**
+ * src: http://www.javaworld.com/article/2077542/learn-java/java-tip-43--how-to-
+ * read-8--and-24-bit-microsoft-windows-bitmaps-in-java-applications.html
+ *
+ * see also: http://en.wikipedia.org/wiki/BMP_file_format
+ * 
+ * Modified by Bob Hanson hansonr@stolaf.edu
+ * 
+ * @author Bob Hanson (hansonr@stolaf.edu)
+ * 
+ */
+public class BMPDecoder {
+
+  public BMPDecoder() {
+    // for reflection
+  }
+  
+  private BufferedInputStream bis;
+
+  /**
+   * original comment:
+   * 
+   * loadbitmap() method converted from Windows C code. Reads only uncompressed
+   * 24- and 8-bit images. Tested with images saved using Microsoft Paint in
+   * Windows 95. If the image is not a 24- or 8-bit image, the program refuses
+   * to even try. I guess one could include 4-bit images by masking the byte by
+   * first 1100 and then 0011. I am not really interested in such images. If a
+   * compressed image is attempted, the routine will probably fail by generating
+   * an IOException. Look for variable ncompression to be different from 0 to
+   * indicate compression is present.
+   * 
+   * @param bytes
+   * @return [image byte array, width, height]
+   */
+  public Object[] decodeWindowsBMP(byte[] bytes) {
+    try {
+      bis = Rdr.getBIS(bytes);
+      temp = new byte[4];
+      // read BITMAPFILEHEADER
+      if (readByte() != 'B' || readByte() != 'M')
+        return null;
+      readInt(); // file size; ignored
+      readShort(); // reserved
+      readShort(); // reserved
+      readInt(); // ptr to pixel array; ignored
+      int imageWidth, imageHeight, bitsPerPixel, nColors = 0, imageSize = 0;
+      // read BITMAP header
+      int headerSize = readInt();
+      switch (headerSize) {
+      case 12:
+        // BITMAPCOREHEADER
+        imageWidth = readShort();
+        imageHeight = readShort();
+        readShort(); // planes
+        bitsPerPixel = readShort();
+        break;
+      case 40:
+        // BITMAPINFOHEADER
+        imageWidth = readInt();
+        imageHeight = readInt();
+        readShort(); // planes
+        bitsPerPixel = readShort();
+        int ncompression = readInt();
+        if (ncompression != 0) {
+          System.out.println("BMP Compression is :" + ncompression
+              + " -- aborting");
+          return null;
+        }
+        imageSize = readInt();
+        readInt(); // hres
+        readInt(); // vres
+        nColors = readInt();
+        readInt(); // colors used
+        break;
+      default:
+        System.out.println("BMP Header unrecognized, length=" + headerSize
+            + " -- aborting");
+        return null;
+      }
+      boolean isYReversed = (imageHeight < 0);
+      if (isYReversed)
+        imageHeight = -imageHeight;
+      int nPixels = imageHeight * imageWidth;
+      int bytesPerPixel = bitsPerPixel / 8;
+      nColors = (nColors > 0 ? nColors : 1 << bitsPerPixel);
+      int npad = (bytesPerPixel == 4 ? 0
+          : imageSize == 0 ? 4 - (imageWidth % 4) : (imageSize / imageHeight)
+              - imageWidth * bytesPerPixel) % 4;
+      int[] palette;
+      int[] buf = new int[nPixels];
+      int dpt = (isYReversed ? imageWidth : -imageWidth);
+      int pt0 = (isYReversed ? 0 : nPixels + dpt);
+      int pt1 = (isYReversed ? nPixels : dpt);
+      switch (bitsPerPixel) {
+      case 32:
+      case 24:
+        for (int pt = pt0; pt != pt1; pt += dpt, pad(npad))
+          for (int i = 0; i < imageWidth; i++)
+            buf[pt + i] = readColor(bytesPerPixel);
+        break;
+      case 8:
+        palette = new int[nColors];
+        for (int i = 0; i < nColors; i++)
+          palette[i] = readColor(4);
+        for (int pt = pt0; pt != pt1; pt += dpt, pad(npad))
+          for (int i = 0; i < imageWidth; i++)
+            buf[pt + i] = palette[readByte()];
+        break;
+      case 4:
+        npad = (4 - (((imageWidth + 1) / 2) % 4)) % 4;
+        palette = new int[nColors];
+        for (int i = 0; i < nColors; i++)
+          palette[i] = readColor(4);
+        int b4 = 0;
+        for (int pt = pt0; pt != pt1; pt += dpt, pad(npad))
+          for (int i = 0, shift = 4; i < imageWidth; i++, shift = 4 - shift)
+            buf[pt + i] = palette[((shift == 4 ? (b4 = readByte()) : b4) >> shift) & 0xF];
+        break;
+      case 1:
+        int color1 = readColor(3);
+        int color2 = readColor(3);
+        npad = (4 - (((imageWidth + 7) / 8) % 4)) % 4;
+        int b = 0;
+        for (int pt = pt0; pt != pt1; pt += dpt, pad(npad))
+          for (int i = 0, bpt = -1; i < imageWidth; i++, bpt--) {
+            if (bpt < 0) {
+              b = readByte();
+              bpt = 7;
+            }
+            buf[pt + i] = ((b & (1 << bpt)) == 0 ? color1 : color2);
+          }
+        break;
+      case 64:
+      case 2:
+      default:
+        System.out
+            .println("Not a 32-, 24-, 8-, 4-, or 1-bit Windows Bitmap, aborting...");
+        return null;
+      }
+      return new Object[] { buf, Integer.valueOf(imageWidth),
+          Integer.valueOf(imageHeight) };
+    } catch (Exception e) {
+      System.out.println("Caught exception in loadbitmap!");
+    }
+    return null;
+  }
+
+  private boolean pad(int npad) throws IOException {
+    for (int i = 0; i < npad; i++)
+      readByte();
+    return true;
+  }
+
+  private byte[] temp;
+  
+  private int readColor(int n) throws IOException {
+    bis.read(temp, 0, n);
+    return 0xff << 24 | ((temp[2] & 0xff) << 16)
+        | ((temp[1] & 0xff) << 8) | temp[0] & 0xff;
+  }
+
+  private int readInt() throws IOException {
+    bis.read(temp, 0, 4);
+    return ((temp[3] & 0xff) << 24) | ((temp[2] & 0xff) << 16)
+        | ((temp[1] & 0xff) << 8) | temp[0] & 0xff;
+  }
+
+  private int readShort() throws IOException {
+    bis.read(temp, 0, 2);
+    return ((temp[1] & 0xff) << 8) | temp[0] & 0xff;
+  }
+
+  private int readByte() throws IOException {
+    bis.read(temp, 0, 1);
+    return temp[0] & 0xff;
+  }
+
+}
diff --git a/src2/javajs/img/CRCEncoder.java b/src2/javajs/img/CRCEncoder.java
new file mode 100644 (file)
index 0000000..77ed11e
--- /dev/null
@@ -0,0 +1,110 @@
+package javajs.img;
+
+import java.util.zip.CRC32;
+
+
+import javajs.util.AU;
+
+abstract class CRCEncoder extends ImageEncoder {
+
+  protected int startPos, bytePos;
+  
+  private CRC32 crc;  
+  protected byte[] pngBytes;  
+  protected int dataLen;
+  private byte[] int2 = new byte[2];
+  private byte[] int4 = new byte[4];
+
+  CRCEncoder() {
+    pngBytes = new byte[250];
+    crc = new CRC32();
+  }
+
+  protected void setData(byte[] b, int pt) {
+    pngBytes = b;
+    dataLen = b.length;
+    startPos = bytePos = pt;
+  }
+
+  protected byte[] getBytes() {
+    return (dataLen == pngBytes.length ? pngBytes : AU.arrayCopyByte(
+        pngBytes, dataLen));
+  }
+
+  protected void writeCRC() {
+    crc.reset();
+    crc.update(pngBytes, startPos, bytePos - startPos);
+    writeInt4((int) crc.getValue());
+  }
+
+  /**
+   * Write a two-byte integer into the pngBytes array at a given position.
+   *
+   * @param n The integer to be written into pngBytes.
+   */
+  protected void writeInt2(int n) {
+    int2[0] = (byte) ((n >> 8) & 0xff);
+    int2[1] = (byte) (n & 0xff);
+    writeBytes(int2);
+  }
+
+  /**
+   * Write a four-byte integer into the pngBytes array at a given position.
+   *
+   * @param n The integer to be written into pngBytes.
+   */
+  protected void writeInt4(int n) {
+    getInt4(n, int4);
+    writeBytes(int4);
+  }
+
+  protected static void getInt4(int n, byte[] int4) {
+    int4[0] = (byte) ((n >> 24) & 0xff);
+    int4[1] = (byte) ((n >> 16) & 0xff);
+    int4[2] = (byte) ((n >> 8) & 0xff);
+    int4[3] = (byte) (n & 0xff);
+  }
+
+  /**
+   * Write a single byte into the pngBytes array at a given position.
+   *
+   * @param b The byte to be written into pngBytes.
+   */
+  protected void writeByte(int b) {
+    byte[] temp = {
+      (byte) b
+    };
+    writeBytes(temp);
+  }
+
+  /**
+   * Write a string into the pngBytes array at a given position.
+   * This uses the getBytes method, so the encoding used will
+   * be its default.
+   *
+   * @param s The string to be written into pngBytes.
+   * @see java.lang.String#getBytes()
+   */
+  protected void writeString(String s) {
+    writeBytes(s.getBytes());
+  }
+
+  /**
+   * Write an array of bytes into the pngBytes array. 
+   * Both dataLen and bytePos are updated. If we don't have 
+   * enough room, this is certainly in image data writing,
+   * so we add just enough for CRC END CRC
+   * 
+   * @param data
+   *        The data to be written into pngBytes.
+   */
+  protected void writeBytes(byte[] data) {
+    int newPos = bytePos + data.length;
+    dataLen = Math.max(dataLen, newPos);
+    if (newPos > pngBytes.length)
+      pngBytes = AU.arrayCopyByte(pngBytes, newPos + 16);
+    System.arraycopy(data, 0, pngBytes, bytePos, data.length);
+    bytePos = newPos;
+  }
+
+}
diff --git a/src2/javajs/img/GifEncoder.java b/src2/javajs/img/GifEncoder.java
new file mode 100644 (file)
index 0000000..287f9c3
--- /dev/null
@@ -0,0 +1,1142 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2007-06-02 12:14:13 -0500 (Sat, 02 Jun 2007) $
+ * $Revision: 7831 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2000-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+//  Final encoding code from http://acme.com/resources/classes/Acme/JPM/Encoders/GifEncoder.java
+//
+//  GifEncoder - write out an image as a GIF
+// 
+// 
+//  Transparency handling and variable bit size courtesy of Jack Palevich.
+//  
+//  Copyright (C)1996,1998 by Jef Poskanzer <jef@mail.acme.com>. All rights reserved.
+//  
+//  Redistribution and use in source and binary forms, with or without
+//  modification, are permitted provided that the following conditions
+//  are met:
+//  1. Redistributions of source code must retain the above copyright
+//     notice, this list of conditions and the following disclaimer.
+//  2. 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.
+// 
+//  THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+// 
+//  Visit the ACME Labs Java page for up-to-date versions of this and other
+//  fine Java utilities: http://www.acme.com/java/
+// 
+/// Write out an image as a GIF.
+// <P>
+// <A HREF="/resources/classes/Acme/JPM/Encoders/GifEncoder.java">Fetch the software.</A><BR>
+// <A HREF="/resources/classes/Acme.tar.gz">Fetch the entire Acme package.</A>
+// <P>
+// @see ToGif
+
+package javajs.img;
+
+import javajs.util.CU;
+import javajs.util.Lst;
+import javajs.util.M3;
+import javajs.util.P3;
+
+import java.util.Hashtable;
+import java.util.Map;
+import java.io.IOException;
+
+/**
+ * 
+ * GifEncoder extensively adapted for Jmol by Bob Hanson
+ * 
+ * Color quantization roughly follows the GIMP method
+ * "dither Floyd-Steinberg (normal)" but with some twists. (For example, we
+ * exclude the background color.)
+ * 
+ * Note that although GIMP code annotation refers to "median-cut", it is really
+ * using MEAN-cut. That is what I use here as well.
+ * 
+ * -- commented code allows visualization of the color space using Jmol. Very
+ * enlightening!
+ * 
+ * -- much simplified interface with ImageEncoder
+ * 
+ * -- uses simple Hashtable with Integer() to catalog colors
+ * 
+ * -- allows progressive production of animated GIF via Jmol CAPTURE command
+ * 
+ * -- uses general purpose javajs.util.OutputChannel for byte-handling options
+ * such as posting to a server, writing to disk, and retrieving bytes.
+ * 
+ * -- allows JavaScript port
+ * 
+ * -- Bob Hanson, first try: 24 Sep 2013; final coding: 9 Nov 2014
+ * 
+ * 
+ * @author Bob Hanson hansonr@stolaf.edu
+ */
+
+public class GifEncoder extends ImageEncoder {
+
+  private Map<String, Object> params;
+  private P3[] palette;
+  private int backgroundColor;
+
+  private boolean interlaced;
+  private boolean addHeader = true;
+  private boolean addImage = true;
+  private boolean addTrailer = true;
+  private boolean isTransparent;
+  private boolean floydSteinberg = true;
+  private boolean capturing;
+  private boolean looping;
+
+  private int delayTime100ths = -1;
+  private int bitsPerPixel = 1;
+
+  private int byteCount;
+
+  /**
+   * we allow for animated GIF by being able to re-enter the code with different
+   * parameters held in params
+   * 
+   * 
+   */
+  @Override
+  protected void setParams(Map<String, Object> params) {
+    this.params = params;
+    Integer ic = (Integer) params.get("transparentColor");
+    if (ic == null) {
+      ic = (Integer) params.get("backgroundColor");
+      if (ic != null)
+        backgroundColor = ic.intValue();
+    } else {
+      backgroundColor = ic.intValue();
+      isTransparent = true;
+    }
+
+    interlaced = (Boolean.TRUE == params.get("interlaced"));
+    if (params.containsKey("captureRootExt") // file0000.gif 
+        || !params.containsKey("captureMode")) // animated gif
+      return;
+    interlaced = false;
+    capturing = true;
+    try {
+      byteCount = ((Integer) params.get("captureByteCount")).intValue();
+    } catch (Exception e) {
+      // ignore
+    }
+    switch ("maec"
+        .indexOf(((String) params.get("captureMode")).substring(0, 1))) {
+    case 0: //"movie"
+      params.put("captureMode", "add");
+      addImage = false;
+      addTrailer = false;
+      break;
+    case 1: // add 
+      addHeader = false;
+      addTrailer = false;
+      int fps = Math.abs(((Integer) params.get("captureFps")).intValue());
+      delayTime100ths = (fps == 0 ? 0 : 100 / fps);
+      looping = (Boolean.FALSE != params.get("captureLooping"));
+      break;
+    case 2: // end
+      addHeader = false;
+      addImage = false;
+      break;
+    case 3: // cancel
+      addHeader = false;
+      addImage = false;
+      out.cancel();
+      break;
+    }
+  }
+
+  @Override
+  protected void generate() throws IOException {
+    if (addHeader)
+      writeHeader();
+    addHeader = false; // only one header
+    if (addImage) {
+      createPalette();
+      writeGraphicControlExtension();
+      if (delayTime100ths >= 0 && looping)
+        writeNetscapeLoopExtension();
+      writeImage();
+    }
+  }
+
+  @Override
+  protected void close() {
+    if (addTrailer) {
+      writeTrailer();
+    } else {
+      doClose = false;
+    }
+    if (capturing)
+      params.put("captureByteCount", Integer.valueOf(byteCount));
+  }
+
+  //////////////  256-color quantization  //////////////
+
+  /**
+   * a color point in normalized L*a*b space with a flag indicating whether it
+   * is the background color
+   */
+  private class ColorItem extends P3 {
+    /**
+        * 
+        */
+       protected boolean isBackground;
+
+    ColorItem(int rgb, boolean isBackground) {
+      this.isBackground = isBackground;
+      setT(toLABnorm(rgb));
+    }
+  }
+
+  /**
+   * A list of normalized L*a*b points with an index and a center and volume
+   * 
+   */
+  private class ColorCell extends Lst<P3> {
+
+    /**
+        * 
+        */
+       private static final long serialVersionUID = 1L;
+       protected int index;
+    protected P3 center;
+
+    private float volume;
+
+    ColorCell(int index) {
+      this.index = index;
+    }
+
+    /**
+     * @param doVisualize
+     *        debugging only
+     * @return volume in normalized L*a*b space
+     */
+    public float getVolume(boolean doVisualize) {
+      if (volume != 0)
+        return volume;
+      if (size() < 2)
+        return -1;
+      //if (true)
+      //return lst.size();
+      //float d;
+      float maxx = -Integer.MAX_VALUE;
+      float minx = Integer.MAX_VALUE;
+      float maxy = -Integer.MAX_VALUE;
+      float miny = Integer.MAX_VALUE;
+      float maxz = -Integer.MAX_VALUE;
+      float minz = Integer.MAX_VALUE;
+      int n = size();
+      for (int i = n; --i >= 0;) {
+        P3 xyz = get(i);
+        if (xyz.x < minx)
+          minx = xyz.x;
+        if (xyz.y < miny)
+          miny = xyz.y;
+        if (xyz.z < minz)
+          minz = xyz.z;
+        if (xyz.x > maxx)
+          maxx = xyz.x;
+        if (xyz.y > maxy)
+          maxy = xyz.y;
+        if (xyz.z > maxz)
+          maxz = xyz.z;
+      }
+      float dx = (maxx - minx);
+      float dy = (maxy - miny);
+      float dz = (maxz - minz);
+      // Jmol visualization only
+      //      if (doVisualize) {
+      //        P3 ptRGB = toRGB(center);
+      //        drawPt(index, -size(), ptRGB);
+      //        //for (int i = n; --i >= 0;)
+      //        //drawPt(index, i, toRGB(get(i)));
+      //        P3 pt0 = toRGB(P3.new3(Math.max(minx, 0), Math.max(miny, 0),
+      //            Math.max(minz, 0)));
+      //        P3 pt1 = toRGB(P3.new3(Math.min(maxx, 100), Math.min(maxy, 100),
+      //            Math.min(maxz, 100)));
+      //        rgbToXyz(pt0, pt0);
+      //        xyzToLab(pt0, pt0);
+      //        rgbToXyz(pt1, pt1);
+      //        xyzToLab(pt1, pt1);
+      //        System.out.println("boundbox corners " + pt0 + " " + pt1);
+      //        System.out.println("draw d" + index + " boundbox color " + ptRGB
+      //            + " mesh nofill");
+      //      }
+      return volume = dx * dx + dy * dy + dz * dz;
+    }
+
+    //    // Jmol visualization only
+    //      private void drawPt(int index, int i, P3 rgb) {
+    //        boolean isMain = (i < 0);
+    //      P3 lab = rgbToXyz(rgb, null);
+    //      xyzToLab(lab, lab);
+    //      System.out.println("draw d" + index + (isMain ? "_" : "_" + i) + " width "
+    //          + (isMain ? 1.0 : 0.2) + " " + lab
+    //          + " color " + rgb + (isMain ? " '" + -i + "'" : ""));
+    //      }
+
+    /**
+     * Set the average normalized L*a*b value for this cell and return its RGB point
+     * 
+     * @return RGB point
+     * 
+     */
+    protected P3 setColor() {
+      int count = size();
+      center = new P3();
+      for (int i = count; --i >= 0;)
+        center.add(get(i));
+      center.scale(1f / count);
+      // Jmol visualization only
+      //volume = 0;
+      //getVolume(true); 
+      return toRGB(center);
+    }
+
+    /**
+     * use median_cut algorithm to split the cell, creating a doubly linked
+     * list.
+     * 
+     * Paul Heckbert, MIT thesis COLOR IMAGE QUANTIZATION FOR FRAME BUFFER
+     * DISPLAY https://www.cs.cmu.edu/~ph/ciq_thesis
+     * 
+     * except, as in GIMP, we use center (not median) here.
+     * 
+     * @param cells
+     * @return true if split
+     */
+    protected boolean splitCell(Lst<ColorCell> cells) {
+      int n = size();
+      if (n < 2)
+        return false;
+      int newIndex = cells.size();
+      ColorCell newCell = new ColorCell(newIndex);
+      cells.addLast(newCell);
+      float[][] ranges = new float[3][3];
+      for (int ic = 0; ic < 3; ic++) {
+        float low = Float.MAX_VALUE;
+        float high = -Float.MAX_VALUE;
+        for (int i = n; --i >= 0;) {
+          P3 lab = get(i);
+          float v = (ic == 0 ? lab.x : ic == 1 ? lab.y : lab.z);
+          if (low > v)
+            low = v;
+          if (high < v)
+            high = v;
+        }
+        ranges[0][ic] = low;
+        ranges[1][ic] = high;
+        ranges[2][ic] = high - low;
+      }
+      float[] r = ranges[2];
+      int mode = (r[0] >= r[1] ? (r[0] >= r[2] ? 0 : 2) : r[1] >= r[2] ? 1 : 2);
+      float val = ranges[0][mode] + ranges[2][mode] / 2;
+      volume = 0; // recalculate volume if needed
+      switch (mode) {
+      case 0:
+        for (int i = n; --i >= 0;)
+          if (get(i).x >= val)
+            newCell.addLast(removeItemAt(i));
+        break;
+      case 1:
+        for (int i = n; --i >= 0;)
+          if (get(i).y >= val)
+            newCell.addLast(removeItemAt(i));
+        break;
+      case 2:
+        for (int i = size(); --i >= 0;)
+          if (get(i).z >= val)
+            newCell.addLast(removeItemAt(i));
+        break;
+      }
+      return true;
+    }
+  }
+
+  /**
+   * Quantize all colors and create the final palette;
+   * replace pixels[] with an array of color indices.
+   * 
+   */
+  private void createPalette() {
+
+    // catalog all pixel colors
+
+    Lst<ColorItem> tempColors = new Lst<ColorItem>();
+    Map<Integer, ColorItem> ciHash = new Hashtable<Integer, ColorItem>();
+    for (int i = 0, n = pixels.length; i < n; i++) {
+      int rgb = pixels[i];
+      Integer key = Integer.valueOf(rgb);
+      ColorItem item = ciHash.get(key);
+      if (item == null) {
+        item = new ColorItem(rgb, rgb == backgroundColor);
+        ciHash.put(key, item);
+        tempColors.addLast(item);
+      }
+    }
+    int nColors = tempColors.size();
+    System.out.println("GIF total image colors: " + nColors);
+    ciHash = null;
+
+    // create a set of <= 256 color cells
+
+    Lst<ColorCell> cells = quantizeColors(tempColors);
+    nColors = cells.size();
+    System.out.println("GIF final color count: " + nColors);
+
+    // generate the palette and map each cell's rgb color to itself
+
+    Map<Integer, ColorCell> colorMap = new Hashtable<Integer, ColorCell>();
+    bitsPerPixel = (nColors <= 2 ? 1 : nColors <= 4 ? 2 : nColors <= 16 ? 4 : 8);
+    palette = new P3[1 << bitsPerPixel];
+    for (int i = 0; i < nColors; i++) {
+      ColorCell c = cells.get(i);
+      colorMap.put(
+          Integer.valueOf(CU.colorPtToFFRGB(palette[i] = c.setColor())), c);
+    }
+
+    // index all pixels to a pallete color
+
+    pixels = indexPixels(cells, colorMap);
+  }
+
+  /**
+   * Quantize colors by generating a set of cells in normalized L*a*b space
+   * containing all colors. Start with just two cells -- fixed background color
+   * and all others. Keep splitting cells while there are fewer than 256 and
+   * some with multiple colors in them.
+   * 
+   * It is possible that we will end up with fewer than 256 colors.
+   * 
+   * @param tempColors
+   * @return final list of colors
+   */
+  private Lst<ColorCell> quantizeColors(Lst<ColorItem> tempColors) {
+    int n = tempColors.size();
+    Lst<ColorCell> cells = new Lst<ColorCell>();
+    ColorCell cc = new ColorCell(0);
+    cc.addLast(new ColorItem(backgroundColor, true));
+    cells.addLast(cc);
+    cc = new ColorCell(1);
+    if (n > 256)
+      cells.addLast(cc);
+    for (int i = 0; i < n; i++) {
+      ColorItem c = tempColors.get(i);
+      if (c.isBackground)
+        continue;
+      cc.addLast(c);
+      if (n <= 256) {
+        cells.addLast(cc);
+        cc = new ColorCell(cells.size());
+      }
+    }
+    tempColors.clear();
+    if (n > 256)
+      while ((n = cells.size()) < 256) {
+        float maxVol = 0;
+        ColorCell maxCell = null;
+        for (int i = n; --i >= 1;) {
+          ColorCell c = cells.get(i);
+          float v = c.getVolume(false);
+          if (v > maxVol) {
+            maxVol = v;
+            maxCell = c;
+          }
+        }
+        if (maxCell == null || !maxCell.splitCell(cells))
+          break;
+      }
+    return cells;
+  }
+
+  /**
+   * 
+   * Assign all colors to their closest approximation and return an array of
+   * color indexes.
+   * 
+   * Uses Floyd-Steinberg dithering, finding the closest known color and then
+   * spreading out the error over four leading pixels. Limits error to +/- 75
+   * percent in normalized L*a*b space.
+   * 
+   * @param cells
+   *        quantized color cells
+   * @param colorMap
+   *        map of quantized rgb to its cell
+   * @return array of color indexes, one for each pixel
+   * 
+   */
+  private int[] indexPixels(Lst<ColorCell> cells,
+                            Map<Integer, ColorCell> colorMap) {
+    // We need a strip only width+2 wide to process all the errors.
+    // Errors are added to the next pixel and the next row's pixels 
+    // only through p + width + 1:
+    //         p  +1
+    //   +w-1 +w  +w+1
+    // so including p as well, we need a total of width + 2 errors.
+    //
+    // as p moves through the pixels, we just use mod to cycle through
+    // this strip.
+    //
+    int w2 = width + 2;
+    P3[] errors = new P3[w2];
+    // We should replace, not overwrite, pixels 
+    // as this may be the raw canvas.buf32.
+    int[] newPixels = new int[pixels.length];
+    P3 err = new P3();
+    P3 lab;
+    int rgb;
+    Map<Integer, ColorCell> nearestCell = new Hashtable<Integer, ColorCell>();
+    for (int i = 0, p = 0; i < height; ++i) {
+      boolean notLastRow = (i != height - 1);
+      for (int j = 0; j < width; ++j, p++) {
+        if (pixels[p] == backgroundColor) {
+          // leave as 0
+          continue;
+        }
+        P3 pe = errors[p % w2];
+        if (pe == null || pe.x == Float.MAX_VALUE) {
+          lab = null;
+          rgb = pixels[p];
+        } else {
+          lab = toLABnorm(pixels[p]);
+          err = pe;
+          // important not to round the clamp here -- full floating precision
+          err.x = clamp(err.x, -75, 75);
+          err.y = clamp(err.y, -75, 75);
+          err.z = clamp(err.z, -75, 75);
+          lab.add(err);
+          rgb = CU.colorPtToFFRGB(toRGB(lab));
+        }
+        Integer key = Integer.valueOf(rgb);
+        ColorCell cell = colorMap.get(key);
+        if (cell == null) {
+          // critical to generate normalized L*a*b from RGB here for nearestCell mapping.
+          // otherwise future RGB keys may match the wrong cell
+          lab = toLABnorm(rgb);
+          cell = nearestCell.get(key);
+          if (cell == null) {
+            // find nearest cell
+            float maxerr = Float.MAX_VALUE;
+            // skip 0 0 0
+            for (int ib = cells.size(); --ib >= 1;) {
+              ColorCell c = cells.get(ib);
+              err.sub2(lab, c.center);
+              float d = err.lengthSquared();
+              if (d < maxerr) {
+                maxerr = d;
+                cell = c;
+              }
+            }
+            nearestCell.put(key, cell);
+          }
+          if (floydSteinberg) {
+            // dither
+            err.sub2(lab, cell.center);
+            boolean notLastCol = (j < width - 1);
+            if (notLastCol)
+              addError(err, 7, errors, p + 1, w2);
+            if (notLastRow) {
+              if (j > 0)
+                addError(err, 3, errors, p + width - 1, w2);
+              addError(err, 5, errors, p + width, w2);
+              if (notLastCol)
+                addError(err, 1, errors, p + width + 1, w2);
+            }
+          }
+          err.x = Float.MAX_VALUE; // used; flag for resetting to 0
+        }
+        newPixels[p] = cell.index;
+      }
+    }
+    return newPixels;
+  }
+
+  private void addError(P3 err, int f, P3[] errors, int p, int w2) {
+    // GIMP will allow changing the background color.
+    if (pixels[p] == backgroundColor)
+      return;
+    p %= w2;
+    P3 errp = errors[p];
+    if (errp == null)
+      errp = errors[p] = new P3();
+    else if (errp.x == Float.MAX_VALUE) // reuse
+      errp.set(0, 0, 0);
+    errp.scaleAdd2(f / 16f, err, errp);
+  }
+
+  ///////////////////////// CIE L*a*b / XYZ / sRGB conversion methods /////////
+
+  // these could be static, but that just makes for more JavaScript code
+
+  protected P3 toLABnorm(int rgb) {
+    P3 lab = CU.colorPtFromInt(rgb, null);
+    rgbToXyz(lab, lab);
+    xyzToLab(lab, lab);
+    // normalize to 0-100
+    lab.y = (lab.y + 86.185f) / (98.254f + 86.185f) * 100f;
+    lab.z = (lab.z + 107.863f) / (94.482f + 107.863f) * 100f;
+    return lab;
+  }
+
+  protected P3 toRGB(P3 lab) {
+    P3 xyz = P3.newP(lab);
+    // normalized to 0-100
+    xyz.y = xyz.y / 100f * (98.254f + 86.185f) - 86.185f;
+    xyz.z = xyz.z / 100f * (94.482f + 107.863f) - 107.863f;
+    labToXyz(xyz, xyz);
+    return xyzToRgb(xyz, xyz);
+  }
+
+  private static M3 xyz2rgb;
+  private static M3 rgb2xyz;
+
+  static {
+    rgb2xyz = M3.newA9(new float[] { 0.4124f, 0.3576f, 0.1805f, 0.2126f,
+        0.7152f, 0.0722f, 0.0193f, 0.1192f, 0.9505f });
+
+    xyz2rgb = M3.newA9(new float[] { 3.2406f, -1.5372f, -0.4986f, -0.9689f,
+        1.8758f, 0.0415f, 0.0557f, -0.2040f, 1.0570f });
+  }
+
+  public P3 rgbToXyz(P3 rgb, P3 xyz) {
+    // http://en.wikipedia.org/wiki/CIE_1931_color_space
+    // http://rsb.info.nih.gov/ij/plugins/download/Color_Space_Converter.java
+    if (xyz == null)
+      xyz = new P3();
+    xyz.x = sxyz(rgb.x);
+    xyz.y = sxyz(rgb.y);
+    xyz.z = sxyz(rgb.z);
+    rgb2xyz.rotate(xyz);
+    return xyz;
+  }
+
+  private float sxyz(float x) {
+    x /= 255;
+    return (float) (x <= 0.04045 ? x / 12.92 : Math.pow(((x + 0.055) / 1.055),
+        2.4)) * 100;
+  }
+
+  public P3 xyzToRgb(P3 xyz, P3 rgb) {
+    // http://en.wikipedia.org/wiki/CIE_1931_color_space
+    // http://rsb.info.nih.gov/ij/plugins/download/Color_Space_Converter.java
+    if (rgb == null)
+      rgb = new P3();
+    rgb.setT(xyz);
+    rgb.scale(0.01f);
+    xyz2rgb.rotate(rgb);
+    rgb.x = clamp(srgb(rgb.x), 0, 255);
+    rgb.y = clamp(srgb(rgb.y), 0, 255);
+    rgb.z = clamp(srgb(rgb.z), 0, 255);
+    return rgb;
+  }
+
+  private float srgb(float x) {
+    return (float) (x > 0.0031308f ? (1.055 * Math.pow(x, 1.0 / 2.4)) - 0.055
+        : x * 12.92) * 255;
+  }
+
+  public P3 xyzToLab(P3 xyz, P3 lab) {
+    // http://en.wikipedia.org/wiki/Lab_color_space
+    // http://rsb.info.nih.gov/ij/plugins/download/Color_Space_Converter.java
+    // Lab([0..100], [-86.185..98.254], [-107.863..94.482])
+    // XYZn = D65 = {95.0429, 100.0, 108.8900};
+    if (lab == null)
+      lab = new P3();
+    float x = flab(xyz.x / 95.0429f);
+    float y = flab(xyz.y / 100);
+    float z = flab(xyz.z / 108.89f);
+    lab.x = (116 * y) - 16;
+    lab.y = 500 * (x - y);
+    lab.z = 200 * (y - z);
+    return lab;
+  }
+
+  private float flab(float t) {
+    return (float) (t > 8.85645168E-3 /* (24/116)^3 */? Math.pow(t,
+        0.333333333) : 7.78703704 /* 1/3*116/24*116/24 */* t + 0.137931034 /* 16/116 */
+    );
+  }
+
+  public P3 labToXyz(P3 lab, P3 xyz) {
+    // http://en.wikipedia.org/wiki/Lab_color_space
+    // http://rsb.info.nih.gov/ij/plugins/download/Color_Space_Converter.java
+    // XYZn = D65 = {95.0429, 100.0, 108.8900};
+    if (xyz == null)
+      xyz = new P3();
+
+    xyz.setT(lab);
+    float y = (xyz.x + 16) / 116;
+    float x = xyz.y / 500 + y;
+    float z = y - xyz.z / 200;
+    xyz.x = fxyz(x) * 95.0429f;
+    xyz.y = fxyz(y) * 100;
+    xyz.z = fxyz(z) * 108.89f;
+
+    return xyz;
+  }
+
+  private float fxyz(float t) {
+    return (float) (t > 0.206896552 /* (24/116) */? t * t * t
+        : 0.128418549 /* 3*24/116*24/116 */* (t - 0.137931034 /* 16/116 */));
+  }
+
+  private float clamp(float c, float min, float max) {
+    c = (c < min ? min : c > max ? max : c);
+    return (min == 0 ? Math.round(c) : c);
+  }
+
+  ///////////////////////// GifEncoder writing methods ////////////////////////
+
+  /**
+   * includes logical screen descriptor
+   * 
+   * @throws IOException
+   */
+  private void writeHeader() throws IOException {
+    putString("GIF89a");
+    putWord(width);
+    putWord(height);
+    putByte(0); // no global color table -- using local instead
+    putByte(0); // no background
+    putByte(0); // no pixel aspect ratio given
+  }
+
+  private void writeGraphicControlExtension() {
+    if (isTransparent || delayTime100ths >= 0) {
+      putByte(0x21); // graphic control extension
+      putByte(0xf9); // graphic control label
+      putByte(4); // block size
+      putByte((isTransparent ? 9 : 0) | (delayTime100ths > 0 ? 2 : 0)); // packed bytes 
+      putWord(delayTime100ths > 0 ? delayTime100ths : 0);
+      putByte(0); // transparent index
+      putByte(0); // end-of-block
+    }
+  }
+
+  // see  http://www.vurdalakov.net/misc/gif/netscape-looping-application-extension
+  //      +---------------+
+  //   0  |     0x21      |  Extension Label
+  //      +---------------+
+  //   1  |     0xFF      |  Application Extension Label
+  //      +---------------+
+  //   2  |     0x0B      |  Block Size
+  //      +---------------+
+  //   3  |               | 
+  //      +-             -+
+  //   4  |               | 
+  //      +-             -+
+  //   5  |               | 
+  //      +-             -+
+  //   6  |               | 
+  //      +-  NETSCAPE   -+  Application Identifier (8 bytes)
+  //   7  |               | 
+  //      +-             -+
+  //   8  |               | 
+  //      +-             -+
+  //   9  |               | 
+  //      +-             -+
+  //  10  |               | 
+  //      +---------------+
+  //  11  |               | 
+  //      +-             -+
+  //  12  |      2.0      |  Application Authentication Code (3 bytes)
+  //      +-             -+
+  //  13  |               | 
+  //      +===============+                      --+
+  //  14  |     0x03      |  Sub-block Data Size   |
+  //      +---------------+                        |
+  //  15  |     0x01      |  Sub-block ID          |
+  //      +---------------+                        | Application Data Sub-block
+  //  16  |               |                        |
+  //      +-             -+  Loop Count (2 bytes)  |
+  //  17  |               |                        |
+  //      +===============+                      --+
+  //  18  |     0x00      |  Block Terminator
+  //      +---------------+
+
+  private void writeNetscapeLoopExtension() {
+    putByte(0x21); // graphic control extension
+    putByte(0xff); // netscape loop extension
+    putByte(0x0B); // block size
+    putString("NETSCAPE2.0");
+    putByte(3);
+    putByte(1);
+    putWord(0); // loop indefinitely
+    putByte(0); // end-of-block
+
+  }
+
+  private int initCodeSize;
+  private int curpt;
+
+  private void writeImage() {
+    putByte(0x2C);
+    putWord(0); //left
+    putWord(0); //top
+    putWord(width);
+    putWord(height);
+
+    //    <Packed Fields>  =      LISx xZZZ
+
+    //    L Local Color Table Flag
+    //    I Interlace Flag
+    //    S Sort Flag
+    //    x Reserved
+    //    ZZZ Size of Local Color Table
+
+    int packedFields = 0x80 | (interlaced ? 0x40 : 0) | (bitsPerPixel - 1);
+    putByte(packedFields);
+    int colorMapSize = 1 << bitsPerPixel;
+    P3 p = new P3();
+    for (int i = 0; i < colorMapSize; i++) {
+      if (palette[i] != null)
+        p = palette[i];
+      putByte((int) p.x);
+      putByte((int) p.y);
+      putByte((int) p.z);
+    }
+    putByte(initCodeSize = (bitsPerPixel <= 1 ? 2 : bitsPerPixel));
+    compress();
+    putByte(0);
+  }
+
+  private void writeTrailer() {
+    // Write the GIF file terminator
+    putByte(0x3B);
+  }
+
+  ///// compression routines /////
+
+  private static final int EOF = -1;
+
+  // Return the next pixel from the image
+  private int nextPixel() {
+    if (countDown-- == 0)
+      return EOF;
+    int colorIndex = pixels[curpt];
+    // Bump the current X position
+    ++curx;
+    if (curx == width) {
+      // If we are at the end of a scan line, set curx back to the beginning
+      // If we are interlaced, bump the cury to the appropriate spot,
+      // otherwise, just increment it.
+      curx = 0;
+      if (interlaced)
+        updateY(INTERLACE_PARAMS[pass], INTERLACE_PARAMS[pass + 4]);
+      else
+        ++cury;
+    }
+    curpt = cury * width + curx;
+    return colorIndex & 0xff;
+  }
+
+  private static final int[] INTERLACE_PARAMS = { 8, 8, 4, 2, 4, 2, 1, 0 };
+
+  /**
+   * 
+   * Group 1 : Every 8th. row, starting with row 0. (Pass 1)
+   * 
+   * Group 2 : Every 8th. row, starting with row 4. (Pass 2)
+   * 
+   * Group 3 : Every 4th. row, starting with row 2. (Pass 3)
+   * 
+   * Group 4 : Every 2nd. row, starting with row 1. (Pass 4)
+   * 
+   * @param yNext
+   * @param yNew
+   */
+  private void updateY(int yNext, int yNew) {
+    cury += yNext;
+    if (yNew >= 0 && cury >= height) {
+      cury = yNew;
+      ++pass;
+    }
+  }
+
+  // Write out a word to the GIF file
+  private void putWord(int w) {
+    putByte(w);
+    putByte(w >> 8);
+  }
+
+  // GIFCOMPR.C       - GIF Image compression routines
+  //
+  // Lempel-Ziv compression based on 'compress'.  GIF modifications by
+  // David Rowley (mgardi@watdcsu.waterloo.edu)
+
+  // General DEFINEs
+
+  private static final int BITS = 12;
+
+  private static final int HSIZE = 5003; // 80% occupancy
+
+  // GIF Image compression - modified 'compress'
+  //
+  // Based on: compress.c - File compression ala IEEE Computer, June 1984.
+  //
+  // By Authors:  Spencer W. Thomas      (decvax!harpo!utah-cs!utah-gr!thomas)
+  //              Jim McKie              (decvax!mcvax!jim)
+  //              Steve Davies           (decvax!vax135!petsd!peora!srd)
+  //              Ken Turkowski          (decvax!decwrl!turtlevax!ken)
+  //              James A. Woods         (decvax!ihnp4!ames!jaw)
+  //              Joe Orost              (decvax!vax135!petsd!joe)
+
+  private int nBits; // number of bits/code
+  private int maxbits = BITS; // user settable max # bits/code
+  private int maxcode; // maximum code, given n_bits
+  private int maxmaxcode = 1 << BITS; // should NEVER generate this code
+
+  private final static int MAXCODE(int nBits) {
+    return (1 << nBits) - 1;
+  }
+
+  private int[] htab = new int[HSIZE];
+  private int[] codetab = new int[HSIZE];
+
+  private int hsize = HSIZE; // for dynamic table sizing
+
+  private int freeEnt = 0; // first unused entry
+
+  // block compression parameters -- after all codes are used up,
+  // and compression rate changes, start over.
+  private boolean clearFlag = false;
+
+  // Algorithm:  use open addressing double hashing (no chaining) on the
+  // prefix code / next character combination.  We do a variant of Knuth's
+  // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
+  // secondary probe.  Here, the modular division first probe is gives way
+  // to a faster exclusive-or manipulation.  Also do block compression with
+  // an adaptive reset, whereby the code table is cleared when the compression
+  // ratio decreases, but after the table fills.  The variable-length output
+  // codes are re-sized at this point, and a special CLEAR code is generated
+  // for the decompressor.  Late addition:  construct the table according to
+  // file size for noticeable speed improvement on small files.  Please direct
+  // questions about this implementation to ames!jaw.
+
+  private int clearCode;
+  private int EOFCode;
+
+  private int countDown;
+  private int pass = 0;
+  private int curx, cury;
+
+  private void compress() {
+
+    // Calculate number of bits we are expecting
+    countDown = width * height;
+
+    // Indicate which pass we are on (if interlace)
+    pass = 0;
+    // Set up the current x and y position
+    curx = 0;
+    cury = 0;
+
+    // Set up the necessary values
+    clearFlag = false;
+    nBits = initCodeSize + 1;
+    maxcode = MAXCODE(nBits);
+
+    clearCode = 1 << initCodeSize;
+    EOFCode = clearCode + 1;
+    freeEnt = clearCode + 2;
+
+    // Set up the 'byte output' routine
+    bufPt = 0;
+
+    int ent = nextPixel();
+
+    int hshift = 0;
+    int fcode;
+    for (fcode = hsize; fcode < 65536; fcode *= 2)
+      ++hshift;
+    hshift = 8 - hshift; // set hash code range bound
+
+    int hsizeReg = hsize;
+    clearHash(hsizeReg); // clear hash table
+
+    output(clearCode);
+
+    int c;
+    outer_loop: while ((c = nextPixel()) != EOF) {
+      fcode = (c << maxbits) + ent;
+      int i = (c << hshift) ^ ent; // xor hashing
+
+      if (htab[i] == fcode) {
+        ent = codetab[i];
+        continue;
+      } else if (htab[i] >= 0) // non-empty slot
+      {
+        int disp = hsizeReg - i; // secondary hash (after G. Knott)
+        if (i == 0)
+          disp = 1;
+        do {
+          if ((i -= disp) < 0)
+            i += hsizeReg;
+
+          if (htab[i] == fcode) {
+            ent = codetab[i];
+            continue outer_loop;
+          }
+        } while (htab[i] >= 0);
+      }
+      output(ent);
+      ent = c;
+      if (freeEnt < maxmaxcode) {
+        codetab[i] = freeEnt++; // code -> hashtable
+        htab[i] = fcode;
+      } else {
+        clearBlock();
+      }
+    }
+    // Put out the final code.
+    output(ent);
+    output(EOFCode);
+  }
+
+  // output
+  //
+  // Output the given code.
+  // Inputs:
+  //      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
+  //              that n_bits =< wordsize - 1.
+  // Outputs:
+  //      Outputs code to the file.
+  // Assumptions:
+  //      Chars are 8 bits long.
+  // Algorithm:
+  //      Maintain a BITS character long buffer (so that 8 codes will
+  // fit in it exactly).  Use the VAX insv instruction to insert each
+  // code in turn.  When the buffer fills up empty it and start over.
+
+  private int curAccum = 0;
+  private int curBits = 0;
+
+  private int masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F,
+      0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF,
+      0x7FFF, 0xFFFF };
+
+  private void output(int code) {
+    curAccum &= masks[curBits];
+
+    if (curBits > 0)
+      curAccum |= (code << curBits);
+    else
+      curAccum = code;
+
+    curBits += nBits;
+
+    while (curBits >= 8) {
+      byteOut((byte) (curAccum & 0xff));
+      curAccum >>= 8;
+      curBits -= 8;
+    }
+
+    // If the next entry is going to be too big for the code size,
+    // then increase it, if possible.
+    if (freeEnt > maxcode || clearFlag) {
+      if (clearFlag) {
+        maxcode = MAXCODE(nBits = initCodeSize + 1);
+        clearFlag = false;
+      } else {
+        ++nBits;
+        if (nBits == maxbits)
+          maxcode = maxmaxcode;
+        else
+          maxcode = MAXCODE(nBits);
+      }
+    }
+
+    if (code == EOFCode) {
+      // At EOF, write the rest of the buffer.
+      while (curBits > 0) {
+        byteOut((byte) (curAccum & 0xff));
+        curAccum >>= 8;
+        curBits -= 8;
+      }
+      flushBytes();
+    }
+  }
+
+  // Clear out the hash table
+
+  // table clear for block compress
+  private void clearBlock() {
+    clearHash(hsize);
+    freeEnt = clearCode + 2;
+    clearFlag = true;
+
+    output(clearCode);
+  }
+
+  // reset code table
+  private void clearHash(int hsize) {
+    for (int i = 0; i < hsize; ++i)
+      htab[i] = -1;
+  }
+
+  // GIF-specific routines (byte array buffer)
+
+  // Number of bytes so far in this 'packet'
+  private int bufPt;
+
+  // Define the storage for the packet accumulator
+  final private byte[] buf = new byte[256];
+
+  // Add a byte to the end of the current packet, and if it is 254
+  // byte, flush the packet to disk.
+  private void byteOut(byte c) {
+    buf[bufPt++] = c;
+    if (bufPt >= 254)
+      flushBytes();
+  }
+
+  // Flush the packet to disk, and reset the accumulator
+  protected void flushBytes() {
+    if (bufPt > 0) {
+      putByte(bufPt);
+      out.write(buf, 0, bufPt);
+      byteCount += bufPt;
+      bufPt = 0;
+    }
+  }
+
+}
diff --git a/src2/javajs/img/ImageEncoder.java b/src2/javajs/img/ImageEncoder.java
new file mode 100644 (file)
index 0000000..7781202
--- /dev/null
@@ -0,0 +1,127 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2007-06-02 12:14:13 -0500 (Sat, 02 Jun 2007) $
+ * $Revision: 7831 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2000-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+// ImageEncoder - abstract class for writing out an image
+//
+// Copyright (C) 1996 by Jef Poskanzer <jef@mail.acme.com>.  All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. 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.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+//
+// Visit the ACME Labs Java page for up-to-date versions of this and other
+// fine Java utilities: http://www.acme.com/java/
+
+package javajs.img;
+
+import java.util.Map;
+
+import javajs.api.GenericImageEncoder;
+import javajs.util.OC;
+
+
+
+/**
+ * Generic abstract image creator:
+ * 
+ *   (1) set parameters
+ *   
+ *   (2) encode the image bytes, if necessary
+ *   
+ *   (3) generate the image 
+ * @author Bob Hanson hansonr@stolaf.edu
+ */
+
+public abstract class ImageEncoder implements GenericImageEncoder {
+
+  protected OC out;
+
+  protected int width = -1;
+  protected int height = -1;
+  protected int quality = -1;
+  protected String date;
+  protected boolean logging;
+  protected boolean doClose = true;
+
+  /**
+   * @param type
+   * @param out
+   * @param params
+   */
+  @Override
+  public boolean createImage(String type, OC out, Map<String, Object> params)
+      throws Exception {
+    this.out = out;
+    logging = (Boolean.TRUE == params.get("logging"));
+    width = ((Integer) params.get("imageWidth")).intValue();
+    height = ((Integer) params.get("imageHeight")).intValue();
+    pixels = (int[]) params.get("imagePixels");
+    date = (String) params.get("date");
+    Integer q = (Integer) params.get("quality");
+    quality = (q == null ? -1 : q.intValue());
+    setParams(params);
+    generate();
+    close(); // GIF will override this and not close
+    return doClose;
+  }
+
+  abstract protected void setParams(Map<String, Object> params);
+  abstract protected void generate() throws Exception;
+
+  protected int[] pixels;
+
+  protected void putString(String s) {
+    byte[] b = s.getBytes();
+    out.write(b, 0, b.length);
+  }
+
+  protected void putByte(int b) {
+    out.writeByteAsInt(b);
+  }
+  
+  protected void close() {
+    // your responsibility to close the output channel
+  }
+
+}
diff --git a/src2/javajs/img/Jpg64Encoder.java b/src2/javajs/img/Jpg64Encoder.java
new file mode 100644 (file)
index 0000000..796972f
--- /dev/null
@@ -0,0 +1,64 @@
+// Version 1.0a
+// Copyright (C) 1998, James R. Weeks and BioElectroMech.
+// Visit BioElectroMech at www.obrador.com.  Email James@obrador.com.
+
+// See license.txt for details about the allowed used of this software.
+// This software is based in part on the work of the Independent JPEG Group.
+// See IJGreadme.txt for details about the Independent JPEG Group's license.
+
+// This encoder is inspired by the Java Jpeg encoder by Florian Raemy,
+// studwww.eurecom.fr/~raemy.
+// It borrows a great deal of code and structure from the Independent
+// Jpeg Group's Jpeg 6a library, Copyright Thomas G. Lane.
+// See license.txt for details 
+
+/*
+ * JpegEncoder and its associated classes are Copyright (c) 1998, James R. Weeks and BioElectroMech
+ * see(Jmol/src/com/obrador/license.txt)
+ * 
+ * javajs.img.JpegEncoder.java was adapted by Bob Hanson
+ * for Jmol in the following ways:
+ * 
+ * 1) minor coding efficiencies were made in some for() loops.
+ * 2) methods not used by Jmol were commented out
+ * 3) method and variable signatures were modified to provide 
+ *    more appropriate method privacy.
+ * 4) additions for Java2Script compatibility 
+ * 
+ * Original files are maintained in the Jmol.src.com.obrador package, but
+ * these original files are not distributed with Jmol.
+ *   
+*/
+
+package javajs.img;
+
+import java.io.IOException;
+import java.util.Map;
+
+import javajs.util.Base64;
+import javajs.util.OC;
+
+
+public class Jpg64Encoder extends JpgEncoder {
+
+  private OC outTemp;
+
+  @Override
+  protected void setParams(Map<String, Object> params) {
+    defaultQuality = 75;
+    outTemp = (OC) params.remove("outputChannelTemp");
+    super.setParams(params);
+  }
+
+  @Override
+  protected void generate() throws IOException {
+    OC out0 = out;
+    out = outTemp;
+    super.generate();
+    byte[] bytes = Base64.getBytes64(out.toByteArray());
+    outTemp = null;
+    out = out0;
+    out.write(bytes, 0, bytes.length);
+  }
+
+}
diff --git a/src2/javajs/img/JpgEncoder.java b/src2/javajs/img/JpgEncoder.java
new file mode 100644 (file)
index 0000000..4e49718
--- /dev/null
@@ -0,0 +1,1208 @@
+// Version 1.0a
+// Copyright (C) 1998, James R. Weeks and BioElectroMech.
+// Visit BioElectroMech at www.obrador.com.  Email James@obrador.com.
+
+// See license.txt for details about the allowed used of this software.
+// This software is based in part on the work of the Independent JPEG Group.
+// See IJGreadme.txt for details about the Independent JPEG Group's license.
+
+// This encoder is inspired by the Java Jpeg encoder by Florian Raemy,
+// studwww.eurecom.fr/~raemy.
+// It borrows a great deal of code and structure from the Independent
+// Jpeg Group's Jpeg 6a library, Copyright Thomas G. Lane.
+// See license.txt for details 
+
+/*
+ * JpegEncoder and its associated classes are Copyright (c) 1998, James R. Weeks and BioElectroMech
+ * see(Jmol/src/com/obrador/license.txt)
+ * 
+ * javjs.img.JpegEncoder.java was adapted by Bob Hanson
+ * 
+ * for Jmol in the following ways:
+ * 
+ * 1) minor coding efficiencies were made in some for() loops.
+ * 2) methods not used by Jmol were commented out
+ * 3) method and variable signatures were modified to provide 
+ *    more appropriate method privacy.
+ * 4) additions for Java2Script compatibility 
+ * 
+ * Original files are maintained in the Jmol.src.com.obrador package, but
+ * these original files are not distributed with Jmol.
+ *   
+*/
+
+package javajs.img;
+
+import java.io.IOException;
+import java.util.Map;
+
+import javajs.img.ImageEncoder;
+import javajs.util.AU;
+import javajs.util.OC;
+
+/**
+ * JpegEncoder - The JPEG main program which performs a jpeg compression of an
+ * image.
+ * 
+ *  A system to allow the full Jmol state -- regardless of length -- 
+ *  to be encoded in a set of APP1 (FFE1) tags.
+ *  But we have to be careful about line ends for backward compatibility. 
+ *  This solution is not 100% effective, because some data lines may in principle be 
+ *  Very large and may not contain new lines for more than 65500 characters, 
+ *  But that would be very unusual. Perhaps a huge data set loaded from a 
+ *  string. Introduced in Jmol 12.1.36. Bob Hanson
+ *  
+ * See org.com.obrador.license.txt
+ * 
+ */
+
+public class JpgEncoder extends ImageEncoder {
+
+  // this string will GENERALLY appear at the end of lines and be escaped 
+  private static final int CONTINUE_MAX = 65500; // some room to spare here. 
+  private static final int CONTINUE_MAX_BUFFER = CONTINUE_MAX + 10; // never break up last 10 bytes
+
+  private JpegObj jpegObj;
+  private Huffman huf;
+  private DCT dct;
+  protected int defaultQuality = 100;
+  private String applicationTag;
+
+  public JpgEncoder() {
+
+  }
+
+  @Override
+  protected void setParams(Map<String, Object> params) {
+    if (quality <= 0)
+      quality = (params.containsKey("qualityJPG") ? ((Integer) params.get("qualityJPG")).intValue() : defaultQuality);
+    jpegObj = new JpegObj();
+    jpegObj.comment = (String) params.get("comment");
+    applicationTag = (String) params.get("jpgAppTag");
+  }
+
+  @Override
+  protected void generate() throws IOException {
+    jpegObj.imageWidth = width;
+    jpegObj.imageHeight = height;
+    dct = new DCT(quality);
+    huf = new Huffman(width, height);
+    if (jpegObj == null)
+      return;
+    jpegObj.getYCCArray(pixels);
+    String longState = writeHeaders(jpegObj, dct);
+    writeCompressedData(jpegObj, dct, huf);
+    writeMarker(eoi);
+    if (longState != null) {
+      byte[] b = longState.getBytes();
+      out.write(b, 0, b.length);
+    }
+  }
+
+  private void writeCompressedData(JpegObj jpegObj, DCT dct, Huffman huf) {
+    int i, j, r, c, a, b;
+    int comp, xpos, ypos, xblockoffset, yblockoffset;
+    float inputArray[][];
+    float dctArray1[][] = new float[8][8];
+    double dctArray2[][] = new double[8][8];
+    int dctArray3[] = new int[8 * 8];
+
+    /*
+     * This method controls the compression of the image.
+     * Starting at the upper left of the image, it compresses 8x8 blocks
+     * of data until the entire image has been compressed.
+     */
+
+    int lastDCvalue[] = new int[jpegObj.numberOfComponents];
+    //int zeroArray[] = new int[64]; // initialized to hold all zeros
+    //int Width = 0, Height = 0;
+    //int nothing = 0, not;
+    int minBlockWidth, minBlockHeight;
+    // This initial setting of MinBlockWidth and MinBlockHeight is done to
+    // ensure they start with values larger than will actually be the case.
+    minBlockWidth = ((huf.imageWidth % 8 != 0) ? (int) (Math
+        .floor(huf.imageWidth / 8.0) + 1) * 8 : huf.imageWidth);
+    minBlockHeight = ((huf.imageHeight % 8 != 0) ? (int) (Math
+        .floor(huf.imageHeight / 8.0) + 1) * 8 : huf.imageHeight);
+    for (comp = 0; comp < jpegObj.numberOfComponents; comp++) {
+      minBlockWidth = Math.min(minBlockWidth, jpegObj.blockWidth[comp]);
+      minBlockHeight = Math.min(minBlockHeight, jpegObj.blockHeight[comp]);
+    }
+    xpos = 0;
+    for (r = 0; r < minBlockHeight; r++) {
+      for (c = 0; c < minBlockWidth; c++) {
+        xpos = c * 8;
+        ypos = r * 8;
+        for (comp = 0; comp < jpegObj.numberOfComponents; comp++) {
+          //Width = JpegObj.BlockWidth[comp];
+          //Height = JpegObj.BlockHeight[comp];
+          inputArray = jpegObj.components[comp];
+          int vsampF = jpegObj.vsampFactor[comp];
+          int hsampF = jpegObj.hsampFactor[comp];
+          int qNumber = jpegObj.qtableNumber[comp];
+          int dcNumber = jpegObj.dctableNumber[comp];
+          int acNumber = jpegObj.actableNumber[comp];
+
+          for (i = 0; i < vsampF; i++) {
+            for (j = 0; j < hsampF; j++) {
+              xblockoffset = j * 8;
+              yblockoffset = i * 8;
+              for (a = 0; a < 8; a++) {
+                for (b = 0; b < 8; b++) {
+
+                  // I believe this is where the dirty line at the bottom of
+                  // the image is coming from.
+                  // I need to do a check here to make sure I'm not reading past
+                  // image data.
+                  // This seems to not be a big issue right now. (04/04/98)
+
+                  dctArray1[a][b] = inputArray[ypos + yblockoffset + a][xpos
+                      + xblockoffset + b];
+                }
+              }
+              // The following code commented out because on some images this technique
+              // results in poor right and bottom borders.
+              // if ((!JpegObj.lastColumnIsDummy[comp] || c < Width - 1) &&
+              //       (!JpegObj.lastRowIsDummy[comp] || r < Height - 1)) {
+              dctArray2 = DCT.forwardDCT(dctArray1);
+              dctArray3 = DCT.quantizeBlock(dctArray2, dct.divisors[qNumber]);
+              // }
+              // else {
+              //   zeroArray[0] = dctArray3[0];
+              //   zeroArray[0] = lastDCvalue[comp];
+              //   dctArray3 = zeroArray;
+              // }
+              huf.HuffmanBlockEncoder(out, dctArray3, lastDCvalue[comp],
+                  dcNumber, acNumber);
+              lastDCvalue[comp] = dctArray3[0];
+            }
+          }
+        }
+      }
+    }
+    huf.flushBuffer(out);
+  }
+
+  private static byte[] eoi = { (byte) 0xFF, (byte) 0xD9 };
+
+  private static byte[] jfif = new byte[] {
+  /* JFIF[0] =*/(byte) 0xff,
+  /* JFIF[1] =*/(byte) 0xe0,
+  /* JFIF[2] =*/0,
+  /* JFIF[3] =*/16,
+  /* JFIF[4] =*/(byte) 0x4a, //'J'
+      /* JFIF[5] =*/(byte) 0x46, //'F'
+      /* JFIF[6] =*/(byte) 0x49, //'I'
+      /* JFIF[7] =*/(byte) 0x46, //'F'
+      /* JFIF[8] =*/0,
+      /* JFIF[9] =*/1,
+      /* JFIF[10] =*/0,
+      /* JFIF[11] =*/0,
+      /* JFIF[12] =*/0,
+      /* JFIF[13] =*/1,
+      /* JFIF[14] =*/0,
+      /* JFIF[15] =*/1,
+      /* JFIF[16] =*/0,
+      /* JFIF[17] =*/0 };
+
+  private static byte[] soi = { (byte) 0xFF, (byte) 0xD8 };
+
+  private String writeHeaders(JpegObj jpegObj, DCT dct) {
+    int i, j, index, offset;
+    int tempArray[];
+
+    // the SOI marker
+    writeMarker(soi);
+
+    // The order of the following headers is quite inconsequential.
+    // the JFIF header
+    writeArray(jfif);
+
+    // Comment Header
+    String comment = null;
+    if (jpegObj.comment != null && jpegObj.comment.length() > 0)
+      writeString(jpegObj.comment, (byte) 0xE1); // App data 1
+    writeString(
+        "JPEG Encoder Copyright 1998, James R. Weeks and BioElectroMech.\n\n",
+        (byte) 0xFE);
+
+    // The DQT header
+    // 0 is the luminance index and 1 is the chrominance index
+    byte dqt[] = new byte[134];
+    dqt[0] = (byte) 0xFF;
+    dqt[1] = (byte) 0xDB;
+    dqt[2] = 0;
+    dqt[3] = (byte) 132;
+    offset = 4;
+    for (i = 0; i < 2; i++) {
+      dqt[offset++] = (byte) ((0 << 4) + i);
+      tempArray = dct.quantum[i];
+      for (j = 0; j < 64; j++) {
+        dqt[offset++] = (byte) tempArray[Huffman.jpegNaturalOrder[j]];
+      }
+    }
+    writeArray(dqt);
+
+    // Start of Frame Header
+    byte sof[] = new byte[19];
+    sof[0] = (byte) 0xFF;
+    sof[1] = (byte) 0xC0;
+    sof[2] = 0;
+    sof[3] = 17;
+    sof[4] = (byte) jpegObj.precision;
+    sof[5] = (byte) ((jpegObj.imageHeight >> 8) & 0xFF);
+    sof[6] = (byte) ((jpegObj.imageHeight) & 0xFF);
+    sof[7] = (byte) ((jpegObj.imageWidth >> 8) & 0xFF);
+    sof[8] = (byte) ((jpegObj.imageWidth) & 0xFF);
+    sof[9] = (byte) jpegObj.numberOfComponents;
+    index = 10;
+    for (i = 0; i < sof[9]; i++) {
+      sof[index++] = (byte) jpegObj.compID[i];
+      sof[index++] = (byte) ((jpegObj.hsampFactor[i] << 4) + jpegObj.vsampFactor[i]);
+      sof[index++] = (byte) jpegObj.qtableNumber[i];
+    }
+    writeArray(sof);
+
+    WriteDHTHeader(Huffman.bitsDCluminance, Huffman.valDCluminance);
+    WriteDHTHeader(Huffman.bitsACluminance, Huffman.valACluminance);
+    WriteDHTHeader(Huffman.bitsDCchrominance, Huffman.valDCchrominance);
+    WriteDHTHeader(Huffman.bitsACchrominance, Huffman.valACchrominance);
+
+    // Start of Scan Header
+    byte sos[] = new byte[14];
+    sos[0] = (byte) 0xFF;
+    sos[1] = (byte) 0xDA;
+    sos[2] = 0;
+    sos[3] = 12;
+    sos[4] = (byte) jpegObj.numberOfComponents;
+    index = 5;
+    for (i = 0; i < sos[4]; i++) {
+      sos[index++] = (byte) jpegObj.compID[i];
+      sos[index++] = (byte) ((jpegObj.dctableNumber[i] << 4) + jpegObj.actableNumber[i]);
+    }
+    sos[index++] = (byte) jpegObj.ss;
+    sos[index++] = (byte) jpegObj.se;
+    sos[index++] = (byte) ((jpegObj.ah << 4) + jpegObj.al);
+    writeArray(sos);
+    return comment;
+  }
+
+  private void writeString(String s, byte id) {
+    int len = s.length();
+    int i0 = 0;
+    String suffix = applicationTag;
+    while (i0 < len) {
+      int nBytes = len - i0;
+      if (nBytes > CONTINUE_MAX_BUFFER) {
+        nBytes = CONTINUE_MAX;
+        // but break only at line breaks
+        int pt = s.lastIndexOf('\n', i0 + nBytes);
+        if (pt > i0 + 1)
+          nBytes = pt - i0;
+      }
+      if (i0 + nBytes == len)
+        suffix = "";
+      writeTag(nBytes + suffix.length(), id);
+      writeArray(s.substring(i0, i0 + nBytes).getBytes());
+      if (suffix.length() > 0)
+        writeArray(suffix.getBytes());
+      i0 += nBytes;
+    }
+  }
+
+  private void writeTag(int length, byte id) {
+    length += 2;
+    byte com[] = new byte[4];
+    com[0] = (byte) 0xFF;
+    com[1] = id;
+    com[2] = (byte) ((length >> 8) & 0xFF);
+    com[3] = (byte) (length & 0xFF);
+    writeArray(com);
+  }
+
+  void WriteDHTHeader(int[] bits, int[] val) {
+    // hansonr@stolaf.edu: simplified code.
+    byte[] dht;
+    int bytes = 0;
+    for (int j = 1; j < 17; j++)
+      bytes += bits[j];
+    dht = new byte[21 + bytes];
+    dht[0] = (byte) 0xFF;
+    dht[1] = (byte) 0xC4;
+    int index = 4;
+    for (int j = 0; j < 17; j++)
+      dht[index++] = (byte) bits[j];
+    for (int j = 0; j < bytes; j++)
+      dht[index++] = (byte) val[j];
+    dht[2] = (byte) (((index - 2) >> 8) & 0xFF);
+    dht[3] = (byte) ((index - 2) & 0xFF);
+    writeArray(dht);
+  }
+
+  void writeMarker(byte[] data) {
+    out.write(data, 0, 2);
+  }
+
+  void writeArray(byte[] data) {
+    out.write(data, 0, data.length);
+  }
+
+}
+
+// This class incorporates quality scaling as implemented in the JPEG-6a
+// library.
+
+/*
+ * DCT - A Java implementation of the Discreet Cosine Transform
+ */
+
+class DCT {
+
+  /**
+   * DCT Block Size - default 8
+   */
+  private final static int N = 8;
+  private final static int NN = N * N;
+
+  /**
+   * Image Quality (0-100) - default 80 (good image / good compression)
+   */
+  //public int QUALITY = 80;
+
+  int[][] quantum = AU.newInt2(2);
+  double[][] divisors = AU.newDouble2(2);
+
+  /**
+   * Quantitization Matrix for luminace.
+   */
+  private int quantum_luminance[] = new int[NN];
+  private double DivisorsLuminance[] = new double[NN];
+
+  /**
+   * Quantitization Matrix for chrominance.
+   */
+  private int quantum_chrominance[] = new int[NN];
+  private double DivisorsChrominance[] = new double[NN];
+
+  /**
+   * Constructs a new DCT object. Initializes the cosine transform matrix these
+   * are used when computing the DCT and it's inverse. This also initializes the
+   * run length counters and the ZigZag sequence. Note that the image quality
+   * can be worse than 25 however the image will be extemely pixelated, usually
+   * to a block size of N.
+   * 
+   * @param quality
+   *        The quality of the image (0 worst - 100 best)
+   * 
+   */
+  DCT(int quality) {
+    initMatrix(quality);
+  }
+
+  /*
+   * This method sets up the quantization matrix for luminance and
+   * chrominance using the Quality parameter.
+   */
+  private void initMatrix(int quality) {
+    // converting quality setting to that specified in the jpeg_quality_scaling
+    // method in the IJG Jpeg-6a C libraries
+
+    quality = (quality < 1 ? 1 : quality > 100 ? 100 : quality);
+    quality = (quality < 50 ? 5000 / quality : 200 - quality * 2);
+
+    // Creating the luminance matrix
+
+    quantum_luminance[0] = 16;
+    quantum_luminance[1] = 11;
+    quantum_luminance[2] = 10;
+    quantum_luminance[3] = 16;
+    quantum_luminance[4] = 24;
+    quantum_luminance[5] = 40;
+    quantum_luminance[6] = 51;
+    quantum_luminance[7] = 61;
+    quantum_luminance[8] = 12;
+    quantum_luminance[9] = 12;
+    quantum_luminance[10] = 14;
+    quantum_luminance[11] = 19;
+    quantum_luminance[12] = 26;
+    quantum_luminance[13] = 58;
+    quantum_luminance[14] = 60;
+    quantum_luminance[15] = 55;
+    quantum_luminance[16] = 14;
+    quantum_luminance[17] = 13;
+    quantum_luminance[18] = 16;
+    quantum_luminance[19] = 24;
+    quantum_luminance[20] = 40;
+    quantum_luminance[21] = 57;
+    quantum_luminance[22] = 69;
+    quantum_luminance[23] = 56;
+    quantum_luminance[24] = 14;
+    quantum_luminance[25] = 17;
+    quantum_luminance[26] = 22;
+    quantum_luminance[27] = 29;
+    quantum_luminance[28] = 51;
+    quantum_luminance[29] = 87;
+    quantum_luminance[30] = 80;
+    quantum_luminance[31] = 62;
+    quantum_luminance[32] = 18;
+    quantum_luminance[33] = 22;
+    quantum_luminance[34] = 37;
+    quantum_luminance[35] = 56;
+    quantum_luminance[36] = 68;
+    quantum_luminance[37] = 109;
+    quantum_luminance[38] = 103;
+    quantum_luminance[39] = 77;
+    quantum_luminance[40] = 24;
+    quantum_luminance[41] = 35;
+    quantum_luminance[42] = 55;
+    quantum_luminance[43] = 64;
+    quantum_luminance[44] = 81;
+    quantum_luminance[45] = 104;
+    quantum_luminance[46] = 113;
+    quantum_luminance[47] = 92;
+    quantum_luminance[48] = 49;
+    quantum_luminance[49] = 64;
+    quantum_luminance[50] = 78;
+    quantum_luminance[51] = 87;
+    quantum_luminance[52] = 103;
+    quantum_luminance[53] = 121;
+    quantum_luminance[54] = 120;
+    quantum_luminance[55] = 101;
+    quantum_luminance[56] = 72;
+    quantum_luminance[57] = 92;
+    quantum_luminance[58] = 95;
+    quantum_luminance[59] = 98;
+    quantum_luminance[60] = 112;
+    quantum_luminance[61] = 100;
+    quantum_luminance[62] = 103;
+    quantum_luminance[63] = 99;
+
+    AANscale(DivisorsLuminance, quantum_luminance, quality);
+
+    // Creating the chrominance matrix
+
+    for (int i = 4; i < 64; i++)
+      quantum_chrominance[i] = 99;
+
+    quantum_chrominance[0] = 17;
+    quantum_chrominance[1] = 18;
+    quantum_chrominance[2] = 24;
+    quantum_chrominance[3] = 47;
+
+    quantum_chrominance[8] = 18;
+    quantum_chrominance[9] = 21;
+    quantum_chrominance[10] = 26;
+    quantum_chrominance[11] = 66;
+
+    quantum_chrominance[16] = 24;
+    quantum_chrominance[17] = 26;
+    quantum_chrominance[18] = 56;
+
+    quantum_chrominance[24] = 47;
+    quantum_chrominance[25] = 66;
+
+    AANscale(DivisorsChrominance, quantum_chrominance, quality);
+
+    // quantum and Divisors are objects used to hold the appropriate matices
+
+    quantum[0] = quantum_luminance;
+    quantum[1] = quantum_chrominance;
+
+    divisors[0] = DivisorsLuminance;
+    divisors[1] = DivisorsChrominance;
+
+  }
+
+  private final static double[] AANscaleFactor = { 1.0, 1.387039845,
+      1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 };
+
+  static private void AANscale(double[] divisors, int[] values, int quality) {
+
+    for (int j = 0; j < 64; j++) {
+      int temp = (values[j] * quality + 50) / 100;
+      values[j] = (temp < 1 ? 1 : temp > 255 ? 255 : temp);
+    }
+
+    for (int i = 0, index = 0; i < 8; i++)
+      for (int j = 0; j < 8; j++, index++)
+        // The divisors for the LL&M method (the slow integer method used in
+        // jpeg 6a library).  This method is currently (04/04/98) incompletely
+        // implemented.
+        // DivisorsLuminance[index] = ((double) quantum_luminance[index]) << 3;
+        // The divisors for the AAN method (the float method used in jpeg 6a library.
+        divisors[index] = (0.125 / (values[index] * AANscaleFactor[i] * AANscaleFactor[j]));
+  }
+
+  /*
+   * This method preforms forward DCT on a block of image data using
+   * the literal method specified for a 2-D Discrete Cosine Transform.
+   * It is included as a curiosity and can give you an idea of the
+   * difference in the compression result (the resulting image quality)
+   * by comparing its output to the output of the AAN method below.
+   * It is ridiculously inefficient.
+   */
+
+  // For now the final output is unusable.  The associated quantization step
+  // needs some tweaking.  If you get this part working, please let me know.
+  /*
+    public double[][] forwardDCTExtreme(float input[][])
+    {
+      double output[][] = new double[N][N];
+      int v, u, x, y;
+      for (v = 0; v < 8; v++) {
+        for (u = 0; u < 8; u++) {
+          for (x = 0; x < 8; x++) {
+            for (y = 0; y < 8; y++) {
+              output[v][u] += input[x][y] * 
+                  Math.cos(((double)(2*x + 1)*(double)u*Math.PI)/16)*
+                  Math.cos(((double)(2*y + 1)*(double)v*Math.PI)/16);
+            }
+          }
+          output[v][u] *= (0.25)*((u == 0) ? (1.0/Math.sqrt(2)) : (double) 1.0)*((v == 0) ? (1.0/Math.sqrt(2)) : (double) 1.0);
+        }
+      }
+      return output;
+    }
+    
+  */
+  /*
+   * This method preforms a DCT on a block of image data using the AAN
+   * method as implemented in the IJG Jpeg-6a library.
+   */
+  static double[][] forwardDCT(float input[][]) {
+    double output[][] = new double[N][N];
+    double tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+    double tmp10, tmp11, tmp12, tmp13;
+    double z1, z2, z3, z4, z5, z11, z13;
+    // Subtracts 128 from the input values
+    for (int i = 0; i < 8; i++)
+      for (int j = 0; j < 8; j++)
+        output[i][j] = (input[i][j] - 128.0);
+    // input[i][j] -= 128;
+
+    for (int i = 0; i < 8; i++) {
+      tmp0 = output[i][0] + output[i][7];
+      tmp7 = output[i][0] - output[i][7];
+      tmp1 = output[i][1] + output[i][6];
+      tmp6 = output[i][1] - output[i][6];
+      tmp2 = output[i][2] + output[i][5];
+      tmp5 = output[i][2] - output[i][5];
+      tmp3 = output[i][3] + output[i][4];
+      tmp4 = output[i][3] - output[i][4];
+
+      tmp10 = tmp0 + tmp3;
+      tmp13 = tmp0 - tmp3;
+      tmp11 = tmp1 + tmp2;
+      tmp12 = tmp1 - tmp2;
+
+      output[i][0] = tmp10 + tmp11;
+      output[i][4] = tmp10 - tmp11;
+
+      z1 = (tmp12 + tmp13) * 0.707106781;
+      output[i][2] = tmp13 + z1;
+      output[i][6] = tmp13 - z1;
+
+      tmp10 = tmp4 + tmp5;
+      tmp11 = tmp5 + tmp6;
+      tmp12 = tmp6 + tmp7;
+
+      z5 = (tmp10 - tmp12) * 0.382683433;
+      z2 = 0.541196100 * tmp10 + z5;
+      z4 = 1.306562965 * tmp12 + z5;
+      z3 = tmp11 * 0.707106781;
+
+      z11 = tmp7 + z3;
+      z13 = tmp7 - z3;
+
+      output[i][5] = z13 + z2;
+      output[i][3] = z13 - z2;
+      output[i][1] = z11 + z4;
+      output[i][7] = z11 - z4;
+    }
+
+    for (int i = 0; i < 8; i++) {
+      tmp0 = output[0][i] + output[7][i];
+      tmp7 = output[0][i] - output[7][i];
+      tmp1 = output[1][i] + output[6][i];
+      tmp6 = output[1][i] - output[6][i];
+      tmp2 = output[2][i] + output[5][i];
+      tmp5 = output[2][i] - output[5][i];
+      tmp3 = output[3][i] + output[4][i];
+      tmp4 = output[3][i] - output[4][i];
+
+      tmp10 = tmp0 + tmp3;
+      tmp13 = tmp0 - tmp3;
+      tmp11 = tmp1 + tmp2;
+      tmp12 = tmp1 - tmp2;
+
+      output[0][i] = tmp10 + tmp11;
+      output[4][i] = tmp10 - tmp11;
+
+      z1 = (tmp12 + tmp13) * 0.707106781;
+      output[2][i] = tmp13 + z1;
+      output[6][i] = tmp13 - z1;
+
+      tmp10 = tmp4 + tmp5;
+      tmp11 = tmp5 + tmp6;
+      tmp12 = tmp6 + tmp7;
+
+      z5 = (tmp10 - tmp12) * 0.382683433;
+      z2 = 0.541196100 * tmp10 + z5;
+      z4 = 1.306562965 * tmp12 + z5;
+      z3 = tmp11 * 0.707106781;
+
+      z11 = tmp7 + z3;
+      z13 = tmp7 - z3;
+
+      output[5][i] = z13 + z2;
+      output[3][i] = z13 - z2;
+      output[1][i] = z11 + z4;
+      output[7][i] = z11 - z4;
+    }
+
+    return output;
+  }
+
+  /*
+   * This method quantitizes data and rounds it to the nearest integer.
+   */
+  static int[] quantizeBlock(double inputData[][], double[] divisorsCode) {
+    int outputData[] = new int[NN];
+    for (int i = 0, index = 0; i < 8; i++)
+      for (int j = 0; j < 8; j++, index++)
+        // The second line results in significantly better compression.
+        outputData[index] = (int) (Math.round(inputData[i][j]
+            * divisorsCode[index]));
+    //                        outputData[index] = (int)(((inputData[i][j] * (((double[]) (Divisors[code]))[index])) + 16384.5) -16384);
+    return outputData;
+  }
+
+  /*
+   * This is the method for quantizing a block DCT'ed with forwardDCTExtreme
+   * This method quantitizes data and rounds it to the nearest integer.
+   */
+
+  /*
+
+    public double[][] forwardDCTExtreme(float input[][])
+    {
+      double output[][] = new double[N][N];
+      int v, u, x, y;
+      for (v = 0; v < 8; v++) {
+        for (u = 0; u < 8; u++) {
+          for (x = 0; x < 8; x++) {
+            for (y = 0; y < 8; y++) {
+              output[v][u] += input[x][y] * 
+                  Math.cos(((double)(2*x + 1)*(double)u*Math.PI)/16)*
+                  Math.cos(((double)(2*y + 1)*(double)v*Math.PI)/16);
+            }
+          }
+          output[v][u] *= (0.25)*((u == 0) ? (1.0/Math.sqrt(2)) : (double) 1.0)*((v == 0) ? (1.0/Math.sqrt(2)) : (double) 1.0);
+        }
+      }
+      return output;
+    }
+
+   */
+  /*
+    public int[] quantizeBlockExtreme(double inputData[][], int code)
+    {
+      int outputData[] = new int[NN];
+      int i, j;
+      int index;
+      index = 0;
+      for (i = 0; i < 8; i++) {
+        for (j = 0; j < 8; j++) {
+          outputData[index] = (int)(Math.round(inputData[i][j] / (((int[]) (quantum[code]))[index])));
+          index++;
+        }
+      }
+      
+      return outputData;
+    }
+  */
+}
+
+// This class was modified by James R. Weeks on 3/27/98.
+// It now incorporates Huffman table derivation as in the C jpeg library
+// from the IJG, Jpeg-6a.
+
+class Huffman {
+  private int bufferPutBits, bufferPutBuffer;
+  int imageHeight;
+  int imageWidth;
+  private int dc_matrix0[][];
+  private int ac_matrix0[][];
+  private int dc_matrix1[][];
+  private int ac_matrix1[][];
+  private int[][][] dc_matrix;
+  private int[][][] ac_matrix;
+  //private int code;
+  int numOfDCTables;
+  int numOfACTables;
+  final static int[] bitsDCluminance = { 0x00, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0,
+      0, 0, 0, 0, 0 };
+  final static int[] valDCluminance = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
+  final static int[] bitsDCchrominance = { 0x01, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1,
+      1, 0, 0, 0, 0, 0 };
+  final static int[] valDCchrominance = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
+  final static int[] bitsACluminance = { 0x10, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4,
+      4, 0, 0, 1, 0x7d };
+  final static int[] valACluminance = { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11,
+      0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71,
+      0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52,
+      0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18,
+      0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37,
+      0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53,
+      0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67,
+      0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83,
+      0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
+      0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9,
+      0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
+      0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
+      0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8,
+      0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa };
+  final static int[] bitsACchrominance = { 0x11, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5,
+      4, 4, 0, 1, 2, 0x77 };
+  final static int[] valACchrominance = { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04,
+      0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22,
+      0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33,
+      0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25,
+      0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36,
+      0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a,
+      0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66,
+      0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
+      0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94,
+      0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
+      0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba,
+      0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
+      0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
+      0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa };
+
+  /*
+   * jpegNaturalOrder[i] is the natural-order position of the i'th element
+   * of zigzag order.
+   */
+  final static int[] jpegNaturalOrder = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32,
+      25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14,
+      21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
+      58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, };
+
+  Huffman(int width, int height) {
+    initHuf();
+    imageWidth = width;
+    imageHeight = height;
+
+  }
+
+  /**
+   * HuffmanBlockEncoder run length encodes and Huffman encodes the quantized
+   * data.
+   * 
+   * @param out
+   * @param zigzag
+   * @param prec
+   * @param dcCode
+   * @param acCode
+   **/
+
+  void HuffmanBlockEncoder(OC out, int zigzag[], int prec,
+                           int dcCode, int acCode) {
+    int temp, temp2, nbits, k, r, i;
+
+    numOfDCTables = 2;
+    numOfACTables = 2;
+
+    int[][] matrixDC = dc_matrix[dcCode];
+    int[][] matrixAC = ac_matrix[acCode];
+
+    // The DC portion
+
+    temp = temp2 = zigzag[0] - prec;
+    if (temp < 0) {
+      temp = -temp;
+      temp2--;
+    }
+    nbits = 0;
+    while (temp != 0) {
+      nbits++;
+      temp >>= 1;
+    }
+    //        if (nbits > 11) nbits = 11;
+    bufferIt(out, matrixDC[nbits][0], matrixDC[nbits][1]);
+    // The arguments in bufferIt are code and size.
+    if (nbits != 0) {
+      bufferIt(out, temp2, nbits);
+    }
+
+    // The AC portion
+
+    r = 0;
+
+    for (k = 1; k < 64; k++) {
+      if ((temp = zigzag[jpegNaturalOrder[k]]) == 0) {
+        r++;
+      } else {
+        while (r > 15) {
+          bufferIt(out, matrixAC[0xF0][0], matrixAC[0xF0][1]);
+          r -= 16;
+        }
+        temp2 = temp;
+        if (temp < 0) {
+          temp = -temp;
+          temp2--;
+        }
+        nbits = 1;
+        while ((temp >>= 1) != 0) {
+          nbits++;
+        }
+        i = (r << 4) + nbits;
+        bufferIt(out, matrixAC[i][0], matrixAC[i][1]);
+        bufferIt(out, temp2, nbits);
+
+        r = 0;
+      }
+    }
+
+    if (r > 0) {
+      bufferIt(out, matrixAC[0][0], matrixAC[0][1]);
+    }
+
+  }
+
+  // Uses an integer long (32 bits) buffer to store the Huffman encoded bits
+  // and sends them to out by the byte.
+
+  void bufferIt(OC out, int code, int size) {
+    int putBuffer = code;
+    int putBits = bufferPutBits;
+
+    putBuffer &= (1 << size) - 1;
+    putBits += size;
+    putBuffer <<= 24 - putBits;
+    putBuffer |= bufferPutBuffer;
+
+    while (putBits >= 8) {
+      int c = ((putBuffer >> 16) & 0xFF);
+      out.writeByteAsInt(c);
+      if (c == 0xFF) {
+        out.writeByteAsInt(0);
+      }
+      putBuffer <<= 8;
+      putBits -= 8;
+    }
+    bufferPutBuffer = putBuffer;
+    bufferPutBits = putBits;
+
+  }
+
+  void flushBuffer(OC out) {
+    int putBuffer = bufferPutBuffer;
+    int putBits = bufferPutBits;
+    while (putBits >= 8) {
+      int c = ((putBuffer >> 16) & 0xFF);
+      out.writeByteAsInt(c);
+      if (c == 0xFF) {
+        out.writeByteAsInt(0);
+      }
+      putBuffer <<= 8;
+      putBits -= 8;
+    }
+    if (putBits > 0) {
+      int c = ((putBuffer >> 16) & 0xFF);
+      out.writeByteAsInt(c);
+    }
+  }
+
+  /*
+   * Initialisation of the Huffman codes for Luminance and Chrominance.
+   * This code results in the same tables created in the IJG Jpeg-6a
+   * library.
+   */
+
+  private void initHuf() {
+    dc_matrix0 = new int[12][2];
+    dc_matrix1 = new int[12][2];
+    ac_matrix0 = new int[255][2];
+    ac_matrix1 = new int[255][2];
+    dc_matrix = AU.newInt3(2, -1);
+    ac_matrix = AU.newInt3(2, -1);
+    int p, l, i, lastp, si, code;
+    int[] huffsize = new int[257];
+    int[] huffcode = new int[257];
+
+    /*
+     * init of the DC values for the chrominance
+     * [][0] is the code   [][1] is the number of bit
+     */
+
+    p = 0;
+    for (l = 1; l <= 16; l++) {
+      //      for (i = 1; i <= bitsDCchrominance[l]; i++)
+      for (i = bitsDCchrominance[l]; --i >= 0;) {
+        huffsize[p++] = l; //that's an "el", not a "one"
+      }
+    }
+    huffsize[p] = 0;
+    lastp = p;
+
+    code = 0;
+    si = huffsize[0];
+    p = 0;
+    while (huffsize[p] != 0) {
+      while (huffsize[p] == si) {
+        huffcode[p++] = code;
+        code++;
+      }
+      code <<= 1;
+      si++;
+    }
+
+    for (p = 0; p < lastp; p++) {
+      dc_matrix1[valDCchrominance[p]][0] = huffcode[p];
+      dc_matrix1[valDCchrominance[p]][1] = huffsize[p];
+    }
+
+    /*
+     * Init of the AC huffman code for the chrominance
+     * matrix [][][0] is the code & matrix[][][1] is the number of bit needed
+     */
+
+    p = 0;
+    for (l = 1; l <= 16; l++) {
+      for (i = bitsACchrominance[l]; --i >= 0;)
+      //      for (i = 1; i <= bitsACchrominance[l]; i++)
+      {
+        huffsize[p++] = l;
+      }
+    }
+    huffsize[p] = 0;
+    lastp = p;
+
+    code = 0;
+    si = huffsize[0];
+    p = 0;
+    while (huffsize[p] != 0) {
+      while (huffsize[p] == si) {
+        huffcode[p++] = code;
+        code++;
+      }
+      code <<= 1;
+      si++;
+    }
+
+    for (p = 0; p < lastp; p++) {
+      ac_matrix1[valACchrominance[p]][0] = huffcode[p];
+      ac_matrix1[valACchrominance[p]][1] = huffsize[p];
+    }
+
+    /*
+     * init of the DC values for the luminance
+     * [][0] is the code   [][1] is the number of bit
+     */
+    p = 0;
+    for (l = 1; l <= 16; l++) {
+      //      for (i = 1; i <= bitsDCluminance[l]; i++)
+      for (i = bitsDCluminance[l]; --i >= 0;) {
+        huffsize[p++] = l;
+      }
+    }
+    huffsize[p] = 0;
+    lastp = p;
+
+    code = 0;
+    si = huffsize[0];
+    p = 0;
+    while (huffsize[p] != 0) {
+      while (huffsize[p] == si) {
+        huffcode[p++] = code;
+        code++;
+      }
+      code <<= 1;
+      si++;
+    }
+
+    for (p = 0; p < lastp; p++) {
+      dc_matrix0[valDCluminance[p]][0] = huffcode[p];
+      dc_matrix0[valDCluminance[p]][1] = huffsize[p];
+    }
+
+    /*
+     * Init of the AC huffman code for luminance
+     * matrix [][][0] is the code & matrix[][][1] is the number of bit
+     */
+
+    p = 0;
+    for (l = 1; l <= 16; l++) {
+      //      for (i = 1; i <= bitsACluminance[l]; i++)
+      for (i = bitsACluminance[l]; --i >= 0;) {
+        huffsize[p++] = l;
+      }
+    }
+    huffsize[p] = 0;
+    lastp = p;
+
+    code = 0;
+    si = huffsize[0];
+    p = 0;
+    while (huffsize[p] != 0) {
+      while (huffsize[p] == si) {
+        huffcode[p++] = code;
+        code++;
+      }
+      code <<= 1;
+      si++;
+    }
+    for (int q = 0; q < lastp; q++) {
+      ac_matrix0[valACluminance[q]][0] = huffcode[q];
+      ac_matrix0[valACluminance[q]][1] = huffsize[q];
+    }
+
+    dc_matrix[0] = dc_matrix0;
+    dc_matrix[1] = dc_matrix1;
+    ac_matrix[0] = ac_matrix0;
+    ac_matrix[1] = ac_matrix1;
+  }
+
+}
+
+/*
+ * JpegInfo - Given an image, sets default information about it and divides
+ * it into its constituant components, downsizing those that need to be.
+ */
+
+class JpegObj {
+  String comment;
+  int imageHeight;
+  int imageWidth;
+  int blockWidth[];
+  int blockHeight[];
+
+  int precision = 8;
+  int numberOfComponents = 3;
+  float[][][] components;
+  int[] compID = { 1, 2, 3 };
+  int[] hsampFactor = { 1, 1, 1 };
+  int[] vsampFactor = { 1, 1, 1 };
+  int[] qtableNumber = { 0, 1, 1 };
+  int[] dctableNumber = { 0, 1, 1 };
+  int[] actableNumber = { 0, 1, 1 };
+  private boolean[] lastColumnIsDummy = { false, false, false };
+  private boolean[] lastRowIsDummy = { false, false, false };
+  int ss = 0;
+  int se = 63;
+  int ah = 0;
+  int al = 0;
+  private int compWidth[];
+  private int compHeight[];
+  private int maxHsampFactor;
+  private int maxVsampFactor;
+
+  public JpegObj() {
+    components = AU.newFloat3(numberOfComponents, -1);
+    compWidth = new int[numberOfComponents];
+    compHeight = new int[numberOfComponents];
+    blockWidth = new int[numberOfComponents];
+    blockHeight = new int[numberOfComponents];
+  }
+
+  /*
+   * This method creates and fills three arrays, Y, Cb, and Cr using the
+   * input image.
+   */
+
+  void getYCCArray(int[] pixels) {
+    // In order to minimize the chance that grabPixels will throw an exception
+    // it may be necessary to grab some pixels every few scanlines and process
+    // those before going for more.  The time expense may be prohibitive.
+    // However, for a situation where memory overhead is a concern, this may be
+    // the only choice.
+    maxHsampFactor = 1;
+    maxVsampFactor = 1;
+    for (int y = 0; y < numberOfComponents; y++) {
+      maxHsampFactor = Math.max(maxHsampFactor, hsampFactor[y]);
+      maxVsampFactor = Math.max(maxVsampFactor, vsampFactor[y]);
+    }
+    for (int y = 0; y < numberOfComponents; y++) {
+      compWidth[y] = (((imageWidth % 8 != 0) ? ((int) Math
+          .ceil(imageWidth / 8.0)) * 8 : imageWidth) / maxHsampFactor)
+          * hsampFactor[y];
+      if (compWidth[y] != ((imageWidth / maxHsampFactor) * hsampFactor[y])) {
+        lastColumnIsDummy[y] = true;
+      }
+      // results in a multiple of 8 for compWidth
+      // this will make the rest of the program fail for the unlikely
+      // event that someone tries to compress an 16 x 16 pixel image
+      // which would of course be worse than pointless
+      blockWidth[y] = (int) Math.ceil(compWidth[y] / 8.0);
+      compHeight[y] = (((imageHeight % 8 != 0) ? ((int) Math
+          .ceil(imageHeight / 8.0)) * 8 : imageHeight) / maxVsampFactor)
+          * vsampFactor[y];
+      if (compHeight[y] != ((imageHeight / maxVsampFactor) * vsampFactor[y])) {
+        lastRowIsDummy[y] = true;
+      }
+      blockHeight[y] = (int) Math.ceil(compHeight[y] / 8.0);
+    }
+    float Y[][] = new float[compHeight[0]][compWidth[0]];
+    float Cr1[][] = new float[compHeight[0]][compWidth[0]];
+    float Cb1[][] = new float[compHeight[0]][compWidth[0]];
+    //float Cb2[][] = new float[compHeight[1]][compWidth[1]];
+    //float Cr2[][] = new float[compHeight[2]][compWidth[2]];
+    for (int pt = 0, y = 0; y < imageHeight; ++y) {
+      for (int x = 0; x < imageWidth; ++x, pt++) {
+        int p = pixels[pt];
+        int r = ((p >> 16) & 0xff);
+        int g = ((p >> 8) & 0xff);
+        int b = (p & 0xff);
+        // The following three lines are a more correct color conversion but
+        // the current conversion technique is sufficient and results in a higher
+        // compression rate.
+        // Y[y][x] = 16 + (float)(0.8588*(0.299 * (float)r + 0.587 * (float)g + 0.114 * (float)b ));
+        // Cb1[y][x] = 128 + (float)(0.8784*(-0.16874 * (float)r - 0.33126 * (float)g + 0.5 * (float)b));
+        // Cr1[y][x] = 128 + (float)(0.8784*(0.5 * (float)r - 0.41869 * (float)g - 0.08131 * (float)b));
+        Y[y][x] = (float) ((0.299 * r + 0.587 * g + 0.114 * b));
+        Cb1[y][x] = 128 + (float) ((-0.16874 * r - 0.33126 * g + 0.5 * b));
+        Cr1[y][x] = 128 + (float) ((0.5 * r - 0.41869 * g - 0.08131 * b));
+      }
+    }
+
+    // Need a way to set the H and V sample factors before allowing downsampling.
+    // For now (04/04/98) downsampling must be hard coded.
+    // Until a better downsampler is implemented, this will not be done.
+    // Downsampling is currently supported.  The downsampling method here
+    // is a simple box filter.
+
+    components[0] = Y;
+    //        Cb2 = DownSample(Cb1, 1);
+    components[1] = Cb1;
+    //        Cr2 = DownSample(Cr1, 2);
+    components[2] = Cr1;
+  }
+  /*  
+    float[][] DownSample(float[][] C, int comp)
+    {
+      int inrow, incol;
+      int outrow, outcol;
+      float output[][];
+      int bias;
+      inrow = 0;
+      incol = 0;
+      int cHeight = compHeight[comp];
+      int cWidth = compWidth[comp];
+      output = new float[cHeight][cWidth];
+      
+      for (outrow = 0; outrow < cHeight; outrow++) {
+        bias = 1;
+        for (outcol = 0; outcol < cWidth; outcol++) {
+          output[outrow][outcol] = (C[inrow][incol++] + C[inrow++][incol--] 
+                   + C[inrow][incol++] + C[inrow--][incol++] + bias)/(float)4.0;
+          bias ^= 3;
+        }
+        inrow += 2;
+        incol = 0;
+      }
+      return output;
+    }
+  */
+
+}
diff --git a/src2/javajs/img/PdfEncoder.java b/src2/javajs/img/PdfEncoder.java
new file mode 100644 (file)
index 0000000..7dfd4b8
--- /dev/null
@@ -0,0 +1,108 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2009-06-30 18:58:33 -0500 (Tue, 30 Jun 2009) $
+ * $Revision: 11158 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2002-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.img;
+
+import java.util.Hashtable;
+import java.util.Map;
+
+import javajs.export.PDFCreator;
+
+/**
+ * A relatively primitive PDF generator that just makes a document with an image
+ * in it.
+ * 
+ */
+public class PdfEncoder extends ImageEncoder {
+
+  private boolean isLandscape;
+  private PDFCreator pdf;
+  private String comment;
+
+  public PdfEncoder() {
+    // for Class.forName  
+  }
+
+  @Override
+  protected void setParams(Map<String, Object> params) {
+       isLandscape = (quality > 1);
+    comment = "Jmol " + (String) params.get("comment");
+  }
+
+  @Override
+  protected void generate() throws Exception {
+    pdf = new PDFCreator();
+    int pageWidth = 8 * 72;
+    int pageHeight = 11 * 72;
+    pdf.setOutputStream(out);
+    pdf.newDocument(pageWidth, pageHeight, isLandscape); // A4 or Letter
+    addMyImage(pageWidth, pageHeight);
+    Map<String, String> ht = new Hashtable<String, String>();
+    if (comment != null)
+      ht.put("Producer", comment);
+    ht.put("Author", "JMol");
+    ht.put("CreationDate", date);
+    pdf.addInfo(ht);
+    pdf.closeDocument();
+  }
+
+  
+  /**
+   * centered on the page
+   * 
+   * @param pageWidth
+   * @param pageHeight
+   */
+  private void addMyImage(int pageWidth, int pageHeight) {
+    pdf.addImageResource("img1", width, height, pixels, true);
+    int w = (isLandscape ? pageHeight : pageWidth);
+    int h = (isLandscape ? pageWidth : pageHeight);
+    int iw = width;
+    int ih = height;
+    if (iw > 0.9 * w) {
+      ih = (int) (ih * 0.9 * w / iw);
+      iw = (int) (w * 0.9);
+    }
+    if (ih > 0.9 * h) {
+      iw = (int) (iw * 0.9 * h / ih);
+      ih = (int) (h * 0.9);
+    }
+    int x = 0;
+    int y = 0;
+    int x1 = iw;
+    int y1 = ih;
+    if (w > iw) {
+      x = (w - iw) / 2;
+      x1 = iw + x;
+    }
+    if (h > ih) {
+      y = (h - ih) / 2;
+      y1 = ih + y;
+    }
+    pdf.drawImage("img1", x, y, x1, y1, 0, 0, width, height);
+  }
+
+}
diff --git a/src2/javajs/img/PngEncoder.java b/src2/javajs/img/PngEncoder.java
new file mode 100644 (file)
index 0000000..2dc8485
--- /dev/null
@@ -0,0 +1,480 @@
+/* $RCSfile$
+ * $Author: nicove $
+ * $Date: 2007-03-30 12:26:16 -0500 (Fri, 30 Mar 2007) $
+ * $Revision: 7275 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2002-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.img;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterOutputStream;
+
+
+
+/**
+ * 
+ * Modified by Bob Hanson hansonr@stolaf.edu to be a subclass of ImageEncoder
+ * and to use javajs.util.OutputChannel instead of just returning bytes. Also includes: 
+ *  
+ * -- JavaScript-compatible image processing
+ *  
+ * -- transparent background option
+ *  
+ * -- more efficient calculation of needs for pngBytes 
+ * 
+ * -- option to use pre-created PNGJ image data (3/19/14; Jmol 14.1.12)
+ * 
+ * -- PNGJ format:
+ * 
+ * // IHDR chunk 
+ * 
+ * // tEXt chunk "Jmol type - <PNG0|PNGJ|PNGT><0000000pt>+<000000len>" 
+ * 
+ * // tEXt chunk "Software - Jmol <version>"
+ * 
+ * // tEXt chunk "Creation Time - <date>"
+ * 
+ * // tRNS chunk transparent color, if desired
+ *
+ * // IDAT chunk (image data)
+ * 
+ * // IEND chunk 
+ * 
+ * // [JMOL ZIP FILE APPENDIX]
+ * 
+ * Original Comment:
+ * 
+ * PngEncoder takes a Java Image object and creates a byte string which can be
+ * saved as a PNG file. The Image is presumed to use the DirectColorModel.
+ * 
+ * Thanks to Jay Denny at KeyPoint Software http://www.keypoint.com/ who let me
+ * develop this code on company time.
+ * 
+ * You may contact me with (probably very-much-needed) improvements, comments,
+ * and bug fixes at:
+ * 
+ * david@catcode.com
+ * 
+ * @author J. David Eisenberg
+ * @author http://catcode.com/pngencoder/
+ * @author Christian Ribeaud (christian.ribeaud@genedata.com)
+ * @author Bob Hanson (hansonr@stolaf.edu)
+ * 
+ * @version 1.4, 31 March 2000
+ */
+public class PngEncoder extends CRCEncoder {
+
+  /** Constants for filters */
+  public static final int FILTER_NONE = 0;
+  public static final int FILTER_SUB = 1;
+  public static final int FILTER_UP = 2;
+  public static final int FILTER_LAST = 2;
+  
+  private static final int PT_FIRST_TAG = 37;
+
+  private boolean encodeAlpha;
+  private int filter = FILTER_NONE;
+  private int bytesPerPixel;
+  private int compressionLevel;
+  private String type;
+  private Integer transparentColor;
+
+  private byte[] appData;
+  private String appPrefix;
+  private String comment;
+  private byte[] bytes;
+
+  
+  public PngEncoder() {
+    super();
+  }
+
+  @Override
+  protected void setParams(Map<String, Object> params) {
+    if (quality < 0)
+      quality = (params.containsKey("qualityPNG") ? ((Integer) params
+          .get("qualityPNG")).intValue() : 2);
+    if (quality > 9)
+      quality = 9;
+    encodeAlpha = false;
+    filter = FILTER_NONE;
+    compressionLevel = quality;
+    transparentColor = (Integer) params.get("transparentColor");
+    comment = (String) params.get("comment");
+    type = (params.get("type") + "0000").substring(0, 4);
+    bytes = (byte[]) params.get("pngImgData");
+    appData = (byte[]) params.get("pngAppData");
+    appPrefix = (String) params.get("pngAppPrefix");
+  }
+
+  
+
+  @Override
+  protected void generate() throws IOException {
+    if (bytes == null) {
+      if (!pngEncode()) {
+        out.cancel();
+        return;
+      }
+      bytes = getBytes();
+    } else {
+      dataLen = bytes.length;
+    }
+    int len = dataLen;
+    if (appData != null) {
+      setJmolTypeText(appPrefix, bytes, len, appData.length,
+          type);
+      out.write(bytes, 0, len);
+      len = (bytes = appData).length;
+    }
+    out.write(bytes, 0, len);
+  }
+
+
+  /**
+   * Creates an array of bytes that is the PNG equivalent of the current image,
+   * specifying whether to encode alpha or not.
+   * 
+   * @return        true if successful
+   * 
+   */
+  private boolean pngEncode() {
+
+    byte[] pngIdBytes = { -119, 80, 78, 71, 13, 10, 26, 10 };
+
+    writeBytes(pngIdBytes);
+    //hdrPos = bytePos;
+    writeHeader();
+    writeText(getApplicationText(appPrefix, type, 0, 0));
+
+    writeText("Software\0" + comment);
+    writeText("Creation Time\0" + date);
+
+    if (!encodeAlpha && transparentColor != null)
+      writeTransparentColor(transparentColor.intValue());
+    //dataPos = bytePos;
+    return writeImageData();
+  }
+
+  /**
+   * Fill in the Jmol type text area with number of bytes of PNG data and number
+   * of bytes of Jmol state data and fix checksum.
+   * 
+   * If we do not do this, then the checksum will be wrong, and Jmol and some
+   * other programs may not be able to read the PNG image.
+   * 
+   * This was corrected for Jmol 12.3.30. Between 12.3.7 and 12.3.29, PNG files
+   * created by Jmol have incorrect checksums.
+   * 
+   * @param prefix 
+   * 
+   * @param b
+   * @param nPNG
+   * @param nState
+   * @param type
+   */
+  private static void setJmolTypeText(String prefix, byte[] b, int nPNG, int nState, String type) {
+    String s = "tEXt" + getApplicationText(prefix, type, nPNG, nState);
+    CRCEncoder encoder = new PngEncoder();
+    byte[] test = s.substring(0, 4 + prefix.length()).getBytes();
+    for (int i = test.length; -- i >= 0;) 
+      if (b[i + PT_FIRST_TAG] != test[i]) {
+        System.out.println("image is not of the right form; appending data, but not adding tEXt tag.");
+        return;
+      }
+    encoder.setData(b, PT_FIRST_TAG);
+    encoder.writeString(s);
+    encoder.writeCRC();
+  }
+
+  /**
+   * Generate the PNGJ directory identifier:
+   * 
+   *    xxxxxxxxx\0ttttiiiiiiiii+ddddddddd
+   *    
+   * where 
+   * 
+   * xxxxxxxxx is a unique 9-character software identifier
+   * tttt is a four-byte software-specific type indicator (PNG0, PNGJ, PNGT, etc.)
+   * iiiiiiiii is the file pointer to the start of app data
+   * ddddddddd is the length of the app data
+   * 
+   * @param prefix up to 9 characters to allow software to recognize itself 
+   * @param type PNGx, where x is J or T for Jmol; original type "PNG" is now "PNG0" 
+   * @param nPNG
+   * @param nData
+   * @return
+   */
+       private static String getApplicationText(String prefix, String type,
+                       int nPNG, int nData) {
+               String sPNG = "000000000" + nPNG;
+               sPNG = sPNG.substring(sPNG.length() - 9);
+               String sData = "000000000" + nData;
+               sData = sData.substring(sData.length() - 9);
+               if (prefix == null)
+                       prefix = "#SwingJS.";                   
+               if (prefix.length() < 9)
+                       prefix = (prefix + ".........");
+               if (prefix.length() > 9)
+                       prefix = prefix.substring(0, 9);
+               return prefix + "\0" + type + sPNG + "+" + sData;
+       }
+
+  //  /**
+  //   * Set the filter to use
+  //   *
+  //   * @param whichFilter from constant list
+  //   */
+  //  public void setFilter(int whichFilter) {
+  //    this.filter = (whichFilter <= FILTER_LAST ? whichFilter : FILTER_NONE);
+  //  }
+
+  //  /**
+  //   * Retrieve filtering scheme
+  //   *
+  //   * @return int (see constant list)
+  //   */
+  //  public int getFilter() {
+  //    return filter;
+  //  }
+
+  //  /**
+  //   * Set the compression level to use
+  //   *
+  //   * @param level 0 through 9
+  //   */
+  //  public void setCompressionLevel(int level) {
+  //    if ((level >= 0) && (level <= 9)) {
+  //      this.compressionLevel = level;
+  //    }
+  //  }
+
+  //  /**
+  //   * Retrieve compression level
+  //   *
+  //   * @return int in range 0-9
+  //   */
+  //  public int getCompressionLevel() {
+  //    return compressionLevel;
+  //  }
+
+  /**
+   * Write a PNG "IHDR" chunk into the pngBytes array.
+   */
+  private void writeHeader() {
+
+    writeInt4(13);
+    startPos = bytePos;
+    writeString("IHDR");
+    writeInt4(width);
+    writeInt4(height);
+    writeByte(8); // bit depth
+    writeByte(encodeAlpha ? 6 : 2); // color type or direct model
+    writeByte(0); // compression method
+    writeByte(0); // filter method
+    writeByte(0); // no interlace
+    writeCRC();
+  }
+
+  private void writeText(String msg) {
+    writeInt4(msg.length());
+    startPos = bytePos;
+    writeString("tEXt" + msg);
+    writeCRC();
+  }
+
+  /**
+   * Write a PNG "tRNS" chunk into the pngBytes array.
+   * 
+   * @param icolor
+   */
+  private void writeTransparentColor(int icolor) {
+
+    writeInt4(6);
+    startPos = bytePos;
+    writeString("tRNS");
+    writeInt2((icolor >> 16) & 0xFF);
+    writeInt2((icolor >> 8) & 0xFF);
+    writeInt2(icolor & 0xFF);
+    writeCRC();
+  }
+
+  private byte[] scanLines; // the scan lines to be compressed
+  private int byteWidth; // width * bytesPerPixel
+
+  //private int hdrPos, dataPos, endPos;
+  //private byte[] priorRow;
+  //private byte[] leftBytes;
+
+
+  /**
+   * Write the image data into the pngBytes array. This will write one or more
+   * PNG "IDAT" chunks. In order to conserve memory, this method grabs as many
+   * rows as will fit into 32K bytes, or the whole image; whichever is less.
+   * 
+   * 
+   * @return true if no errors; false if error grabbing pixels
+   */
+  private boolean writeImageData() {
+
+    bytesPerPixel = (encodeAlpha ? 4 : 3);
+    byteWidth = width * bytesPerPixel;
+
+    int scanWidth = byteWidth + 1; // the added 1 is for the filter byte
+
+    //boolean doFilter = (filter != FILTER_NONE);
+
+    int rowsLeft = height; // number of rows remaining to write
+    //int startRow = 0; // starting row to process this time through
+    int nRows; // how many rows to grab at a time
+
+    int scanPos; // where we are in the scan lines
+
+    Deflater deflater = new Deflater(compressionLevel);
+    ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024);
+
+    DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes,
+        deflater);
+
+    int pt = 0; // overall image byte pointer
+    
+    // Jmol note: The entire image has been stored in pixels[] already
+    
+    try {
+      while (rowsLeft > 0) {
+        nRows = Math.max(1, Math.min(32767 / scanWidth, rowsLeft));
+        scanLines = new byte[scanWidth * nRows];
+        //        if (doFilter)
+        //          switch (filter) {
+        //          case FILTER_SUB:
+        //            leftBytes = new byte[16];
+        //            break;
+        //          case FILTER_UP:
+        //            priorRow = new byte[scanWidth - 1];
+        //            break;
+        //          }
+        int nPixels = width * nRows;
+        scanPos = 0;
+        //startPos = 1;
+        for (int i = 0; i < nPixels; i++, pt++) {
+          if (i % width == 0) {
+            scanLines[scanPos++] = (byte) filter;
+            //startPos = scanPos;
+          }
+          scanLines[scanPos++] = (byte) ((pixels[pt] >> 16) & 0xff);
+          scanLines[scanPos++] = (byte) ((pixels[pt] >> 8) & 0xff);
+          scanLines[scanPos++] = (byte) ((pixels[pt]) & 0xff);
+          if (encodeAlpha) {
+            scanLines[scanPos++] = (byte) ((pixels[pt] >> 24) & 0xff);
+          }
+          //          if (doFilter && i % width == width - 1) {
+          //            switch (filter) {
+          //            case FILTER_SUB:
+          //              filterSub();
+          //              break;
+          //            case FILTER_UP:
+          //              filterUp();
+          //              break;
+          //            }
+          //          }
+        }
+
+        /*
+         * Write these lines to the output area
+         */
+        compBytes.write(scanLines, 0, scanPos);
+
+        //startRow += nRows;
+        rowsLeft -= nRows;
+      }
+      compBytes.close();
+
+      /*
+       * Write the compressed bytes
+       */
+      byte[] compressedLines = outBytes.toByteArray();
+      writeInt4(compressedLines.length);
+      startPos = bytePos;
+      writeString("IDAT");
+      writeBytes(compressedLines);
+      writeCRC();
+      writeEnd();
+      deflater.finish();
+      return true;
+    } catch (IOException e) {
+      System.err.println(e.toString());
+      return false;
+    }
+  }
+
+  /**
+   * Write a PNG "IEND" chunk into the pngBytes array.
+   */
+  private void writeEnd() {
+    writeInt4(0);
+    startPos = bytePos;
+    writeString("IEND");
+    writeCRC();
+  }
+
+  ///**
+  //* Perform "sub" filtering on the given row.
+  //* Uses temporary array leftBytes to store the original values
+  //* of the previous pixels.  The array is 16 bytes long, which
+  //* will easily hold two-byte samples plus two-byte alpha.
+  //*
+  //*/
+  //private void filterSub() {
+  // int offset = bytesPerPixel;
+  // int actualStart = startPos + offset;
+  // int leftInsert = offset;
+  // int leftExtract = 0;
+  // //byte current_byte;
+  //
+  // for (int i = actualStart; i < startPos + byteWidth; i++) {
+  //   leftBytes[leftInsert] = scanLines[i];
+  //   scanLines[i] = (byte) ((scanLines[i] - leftBytes[leftExtract]) % 256);
+  //   leftInsert = (leftInsert + 1) % 0x0f;
+  //   leftExtract = (leftExtract + 1) % 0x0f;
+  // }
+  //}
+  //
+  ///**
+  //* Perform "up" filtering on the given row. Side effect: refills the prior row
+  //* with current row
+  //* 
+  //*/
+  //private void filterUp() {
+  // int nBytes = width * bytesPerPixel;
+  // for (int i = 0; i < nBytes; i++) {
+  //   int pt = startPos + i;
+  //   byte b = scanLines[pt];
+  //   scanLines[pt] = (byte) ((scanLines[pt] - priorRow[i]) % 256);
+  //   priorRow[i] = b;
+  // }
+  //}
+
+}
diff --git a/src2/javajs/img/PpmEncoder.java b/src2/javajs/img/PpmEncoder.java
new file mode 100644 (file)
index 0000000..4bdc980
--- /dev/null
@@ -0,0 +1,60 @@
+// PpmEncoder - write out an image as a PPM
+//
+// Copyright (C)1996,1998 by Jef Poskanzer <jef@mail.acme.com>. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+// 1. Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+// 2. 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.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
+//
+// Visit the ACME Labs Java page for up-to-date versions of this and other
+// fine Java utilities: http://www.acme.com/java/
+
+package javajs.img;
+
+import java.util.Map;
+
+
+/**
+ * see http://netpbm.sourceforge.net/doc/ppm.html
+ */
+public class PpmEncoder extends ImageEncoder {
+
+  @Override
+  protected void setParams(Map<String, Object> params) {
+    // no params
+  }
+
+  @Override
+  protected void generate() {
+    putString("P6\n");
+    putString(width + " " + height + "\n");
+    putString("255\n");
+    byte[] ppmPixels = new byte[width * 3];
+    for (int pt = 0, row = 0; row < height; ++row) {
+      for (int col = 0, j = 0; col < width; ++col, pt++) {
+        int p = pixels[pt];
+        ppmPixels[j++] = (byte) ((p >> 16) & 0xff);
+        ppmPixels[j++] = (byte) ((p >> 8) & 0xff);
+        ppmPixels[j++] = (byte) (p & 0xff);
+      }
+      out.write(ppmPixels, 0, ppmPixels.length);
+    }
+  }
+}
diff --git a/src2/javajs/util/A4.java b/src2/javajs/util/A4.java
new file mode 100644 (file)
index 0000000..d20b6c2
--- /dev/null
@@ -0,0 +1,252 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+import java.io.Serializable;
+
+import javajs.api.JSONEncodable;
+import javajs.util.T3;
+
+
+
+/**
+ * A 4 element axis angle represented by single precision floating point
+ * x,y,z,angle components. An axis angle is a rotation of angle (radians) about
+ * the vector (x,y,z).
+ * 
+ * @version specification 1.1, implementation $Revision: 1.9 $, $Date:
+ *          2006/07/28 17:01:32 $
+ * @author Kenji hiranabe
+ * 
+ * additions by Bob Hanson hansonr@stolaf.edu 9/30/2012
+ * for unique constructor and method names
+ * for the optimization of compiled JavaScript using Java2Script
+ */
+public class A4 implements JSONEncodable, Serializable {
+
+  /*
+   * I assumed that the length of the axis vector is not significant.
+   */
+
+  /**
+   * The x coordinate.
+   */
+  public float x;
+
+  /**
+   * The y coordinate.
+   */
+  public float y;
+
+  /**
+   * The z coordinate.
+   */
+  public float z;
+
+  /**
+   * The angle.
+   */
+  public float angle;
+
+  /**
+   * Constructs and initializes a AxisAngle4f to (0,0,1,0).
+   */
+  public A4() {
+    z = 1.0f;
+  }
+
+  /**
+   * Constructs and initializes an AxisAngle4f from the specified x, y, z, and
+   * angle.
+   * 
+   * @param x
+   *        the x coordinate
+   * @param y
+   *        the y coordinate
+   * @param z
+   *        the z coordinate
+   * @param angle
+   *        the angle.
+   * @return a
+   */
+  public static A4 new4(float x, float y, float z, float angle) {
+    A4 a = new A4();
+    a.set4(x, y, z, angle);
+    return a;
+  }
+
+  /**
+   * Constructs and initializes a AxisAngle4f from the specified AxisAngle4f.
+   * 
+   * @param a1
+   *        the AxisAngle4f containing the initialization x y z angle data
+   * @return a
+   */
+  public static A4 newAA(A4 a1) {
+    A4 a = new A4();
+    a.set4(a1.x, a1.y, a1.z, a1.angle);
+    return a;
+  }
+
+  /**
+   * Constructs and initializes an AxisAngle4f from the specified axis and
+   * angle.
+   * 
+   * @param axis
+   *        the axis
+   * @param angle
+   *        the angle
+   * @return a
+   */
+  public static A4 newVA(V3 axis, float angle) {
+    A4 a = new A4();
+    a.setVA(axis, angle);
+    return a;
+  }
+
+  /**
+   * Sets the value of this AxisAngle4f to the specified axis and angle.
+   * 
+   * @param axis
+   *        the axis
+   * @param angle
+   *        the angle
+   * @since Java 3D 1.2
+   */
+  public final void setVA(V3 axis, float angle) {
+    x = axis.x;
+    y = axis.y;
+    z = axis.z;
+    this.angle = angle;
+  }
+
+  /**
+   * Sets the value of this axis angle to the specified x,y,z,angle.
+   * 
+   * @param x
+   *        the x coordinate
+   * @param y
+   *        the y coordinate
+   * @param z
+   *        the z coordinate
+   * @param angle
+   *        the angle
+   */
+  public final void set4(float x, float y, float z, float angle) {
+    this.x = x;
+    this.y = y;
+    this.z = z;
+    this.angle = angle;
+  }
+
+  /**
+   * Sets the value of this axis angle to the value of axis angle t1.
+   * 
+   * @param a
+   *        the axis angle to be copied
+   */
+  public final void setAA(A4 a) {
+    x = a.x;
+    y = a.y;
+    z = a.z;
+    angle = a.angle;
+  }
+
+
+  /**
+   * Sets the value of this axis-angle to the rotational component of the passed
+   * matrix.
+   * 
+   * @param m1
+   *        the matrix3f
+   */
+  public final void setM(M3 m1) {
+    setFromMat(m1.m00, m1.m01, m1.m02, m1.m10, m1.m11, m1.m12, m1.m20, m1.m21,
+        m1.m22);
+  }
+
+  // helper method
+  private void setFromMat(double m00, double m01, double m02, double m10,
+                          double m11, double m12, double m20, double m21,
+                          double m22) {
+    // assuming M is normalized.
+
+    double cos = (m00 + m11 + m22 - 1.0) * 0.5;
+    x = (float) (m21 - m12);
+    y = (float) (m02 - m20);
+    z = (float) (m10 - m01);
+    double sin = 0.5 * Math.sqrt(x * x + y * y + z * z);
+    if (sin == 0 && cos == 1) {
+      x = y = 0;
+      z = 1;
+      angle = 0;
+    } else {
+      angle = (float) Math.atan2(sin, cos);
+    }
+
+    // no need to normalize
+    // x /= n;
+    // y /= n;
+    // z /= n;
+  }
+
+  /**
+   * Returns a hash number based on the data values in this object. Two
+   * different AxisAngle4f objects with identical data values (ie, returns true
+   * for equals(AxisAngle4f) ) will return the same hash number. Two vectors
+   * with different data members may return the same hash value, although this
+   * is not likely.
+   */
+  @Override
+  public int hashCode() {
+    return T3.floatToIntBits(x) ^ T3.floatToIntBits(y)
+        ^ T3.floatToIntBits(z) ^ T3.floatToIntBits(angle);
+  }
+
+  /**
+   * Returns true if the Object o is of type AxisAngle4f and all of the data
+   * members of o1 are equal to the corresponding data members in this
+   * AxisAngle4f.
+   * 
+   * @param o
+   *        the object with which the comparison is made.
+   * @return T/F
+   */
+  @Override
+  public boolean equals(Object o) {
+    if (!(o instanceof A4))
+      return false;
+    A4 a1 = (A4) o;
+    return x == a1.x && y == a1.y && z == a1.z && angle == a1.angle;
+  }
+
+  /**
+   * Returns a string that contains the values of this AxisAngle4f. The form is
+   * (x,y,z,angle).
+   * 
+   * @return the String representation
+   */
+  @Override
+  public String toString() {
+    return "(" + x + ", " + y + ", " + z + ", " + angle + ")";
+  }
+
+  @Override
+  public String toJSON() {
+    return "[" + x + "," + y + "," + z + "," + (float) (angle * 180.0 / Math.PI) + "]";
+  }
+}
diff --git a/src2/javajs/util/AU.java b/src2/javajs/util/AU.java
new file mode 100644 (file)
index 0000000..f873116
--- /dev/null
@@ -0,0 +1,551 @@
+/* $RCSfile$
+ * $Author: egonw $
+ * $Date: 2005-11-10 09:52:44 -0600 (Thu, 10 Nov 2005) $
+ * $Revision: 4255 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2003-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.util;
+
+// 4/23/15 BH getComponentType fix
+
+import java.lang.reflect.Array;
+
+import java.util.Arrays;
+import java.util.Hashtable;
+import java.util.Map;
+
+
+final public class AU {
+
+  /**
+   * Very important that this not be used with Int32Array or Float32Array,
+   * because it is not initialize to all zeros in MSIE 9. 
+   * 
+   * @param array
+   * @param minimumLength
+   * @return array
+   */
+  public static Object ensureLength(Object array, int minimumLength) {
+    return (array != null && getLength(array) >= minimumLength ? array 
+        : arrayCopyObject(array, minimumLength));
+  }
+
+  public static String[] ensureLengthS(String[] array, int minimumLength) {
+    return (array != null && array.length >= minimumLength ? array
+        : arrayCopyS(array, minimumLength));
+  }
+
+  public static float[] ensureLengthA(float[] array, int minimumLength) {
+   return (array != null && array.length >= minimumLength ? array: arrayCopyF(array, minimumLength));
+  }
+
+  public static int[] ensureLengthI(int[] array, int minimumLength) {
+    return (array != null && array.length >= minimumLength ? array : arrayCopyI(array, minimumLength));
+  }
+
+  public static short[] ensureLengthShort(short[] array, int minimumLength) {
+    return (array != null && array.length >= minimumLength ? array : arrayCopyShort(array, minimumLength));
+  }
+
+  public static byte[] ensureLengthByte(byte[] array, int minimumLength) {
+    return (array != null && array.length >= minimumLength ? array : arrayCopyByte(array, minimumLength));
+  }
+
+  /**
+   * Very important that this not be used with Int32Array or Float32Array,
+   * because it is not initialized to all zeros in MSIE 9.
+   * 
+   * @param array
+   * @return array
+   */
+  public static Object doubleLength(Object array) {
+    return arrayCopyObject(array, (array == null ? 16 : 2 * getLength(array)));
+  }
+
+  public static String[] doubleLengthS(String[] array) {
+    return arrayCopyS(array, (array == null ? 16 : 2 * array.length));
+  }
+
+  public static float[] doubleLengthF(float[] array) {
+    return arrayCopyF(array, (array == null ? 16 : 2 * array.length));
+  }
+
+  public static int[] doubleLengthI(int[] array) {
+    return arrayCopyI(array, (array == null ? 16 : 2 * array.length));
+  }
+
+  public static short[] doubleLengthShort(short[] array) {
+    return arrayCopyShort(array, (array == null ? 16 : 2 * array.length));
+  }
+
+  public static byte[] doubleLengthByte(byte[] array) {
+    return arrayCopyByte(array, (array == null ? 16 : 2 * array.length));
+  }
+
+  public static boolean[] doubleLengthBool(boolean[] array) {
+    return arrayCopyBool(array, (array == null ? 16 : 2 * array.length));
+  }
+
+  public static Object deleteElements(Object array, int firstElement,
+                                     int nElements) {
+    if (nElements == 0 || array == null)
+      return array;
+    int oldLength = getLength(array);
+    if (firstElement >= oldLength)
+      return array;
+    int n = oldLength - (firstElement + nElements);
+    if (n < 0)
+      n = 0;
+    Object t = newInstanceO(array, firstElement + n);
+    if (firstElement > 0)
+      System.arraycopy(array, 0, t, 0, firstElement);
+    if (n > 0)
+      System.arraycopy(array, firstElement + nElements, t, firstElement, n);
+    return t;
+  }
+
+  /**
+   * note -- cannot copy if array is null! does not copy if length is unchanged
+   * 
+   * @param array
+   * @param newLength
+   * @return array
+   */
+  public static Object arrayCopyObject(Object array, int newLength) {  
+    int oldLength = (array == null ? -1 : getLength(array));
+    if (newLength < 0) newLength = oldLength;
+    if (newLength == oldLength)
+     return array;
+    /**
+     * @j2sNative
+     * 
+     *     if (newLength < oldLength) return Clazz.array(-1, array, 0, newLength);
+     */
+    {}
+    Object t = newInstanceO(array, newLength);
+    if (oldLength > 0)
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+        : newLength);
+    return t;
+
+  }
+
+  /**
+   * Very important that this not be used with Int32Array or Float32Array,
+   * because those need to be initialized to all zeros in MSIE 9, and
+   * MSIE 9 cannot distinguish Int32Array or Float32Array from Array.
+   * 
+   * @param array
+   * @param n
+   * @return array
+   */
+  private static Object newInstanceO(Object array, int n) {
+    return Array.newInstance(array.getClass().getComponentType(), n);
+  }
+
+  public static int getLength(Object array) {
+    /**
+     * @j2sNative
+     * 
+     *  return array.length
+     *   
+     */
+    {
+      return Array.getLength(array);
+    }
+  }
+
+  public static String[] arrayCopyS(String[] array, int newLength) {
+    int oldLength = (array == null ? -1 : array.length);
+    if (newLength < 0) newLength = oldLength;
+    /**
+     * @j2sNative
+     * 
+     *     if (newLength < oldLength) return Clazz.array(-1, array, 0, newLength);
+     */
+    {}
+    String[] t = new String[newLength];
+    if (array != null) {
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+          : newLength);
+    }
+    return t;
+  }
+
+  public static int[][] arrayCopyII(int[][] array, int newLength) {
+    int[][] t = newInt2(newLength);
+    if (array != null) {
+      int oldLength = array.length;
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+          : newLength);
+    }
+    return t;
+  }
+
+  public static T3[] arrayCopyPt(T3[] array, int newLength) {
+    if (newLength < 0)
+      newLength = array.length;
+    T3[] t = new T3[newLength];
+    if (array != null) {
+      int oldLength = array.length;
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+          : newLength);
+    }
+    return t;
+  }
+
+  public static float[] arrayCopyF(float[] array, int newLength) {
+    int oldLength = (array == null ? -1 : array.length);
+    if (newLength < 0) newLength = oldLength;
+    /**
+     * @j2sNative
+     * 
+     *     if (newLength < oldLength) return Clazz.array(-1, array, 0, newLength);
+     */
+    {}
+    float[] t = new float[newLength];
+    if (array != null) {
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+          : newLength);
+    }
+    return t;
+  }
+
+  public static int[] arrayCopyI(int[] array, int newLength) {
+    int oldLength = (array == null ? -1 : array.length);
+    if (newLength < 0) newLength = oldLength;
+    /**
+     * @j2sNative
+     * 
+     *     if (newLength < oldLength) return Clazz.array(-1, array, 0, newLength);
+     */
+    {}
+    int[] t = new int[newLength];
+    if (array != null) {
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+          : newLength);
+    }
+    return t;
+  }
+
+  /**
+   * a specialized method that allows copying from a starting point either
+   * to the end or to the middle (color schemes, especially)
+   * @param array
+   * @param i0
+   * @param n
+   * @return array or null
+   */
+  public static int[] arrayCopyRangeI(int[] array, int i0, int n) {
+    if (array == null)
+      return null;
+    int oldLength = array.length;
+    if (n == -1) n = oldLength;
+    if (n == -2) n = oldLength / 2;
+    /**
+     * @j2sNative
+     * 
+     * return Clazz.array(-1, array, i0, n);
+     * 
+     */
+    {
+    }
+    n -= i0;
+    int[] t = new int[n];
+    System.arraycopy(array, i0, t, 0, n);
+    return t;
+  }
+
+  public static int[] arrayCopyRangeRevI(int[] array, int i0, int n) {
+    if (array == null)
+      return null;
+    /**
+     * @j2sNative
+     * 
+     * return Clazz.array(-1, array, i0, n).reverse();
+     */
+    {
+    }
+    int[] t = arrayCopyRangeI(array, i0, n);
+    if (n < 0)
+      n = array.length;
+    for (int i = n / 2; --i >= 0;)
+      swapInt(t, i, n - 1 - i);
+    return t;
+  }
+
+  public static short[] arrayCopyShort(short[] array, int newLength) {
+    int oldLength = (array == null ? -1 : array.length);
+    if (newLength < 0) newLength = oldLength;
+    /**
+     * @j2sNative
+     * 
+     *     if (newLength < oldLength) return Clazz.array(-1, array, 0, newLength);
+     */
+    {}
+    short[] t = new short[newLength];
+    if (array != null) {
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+          : newLength);
+    }
+    return t;
+  }
+
+  public static byte[] arrayCopyByte(byte[] array, int newLength) {
+    int oldLength = (array == null ? -1 : array.length);
+    if (newLength < 0) newLength = oldLength;
+    /**
+     * @j2sNative
+     * 
+     *     if (newLength < oldLength) return Clazz.array(-1, array, 0, newLength);
+     */
+    {}
+    byte[] t = new byte[newLength];
+    if (array != null) {
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+          : newLength);
+    }
+    return t;
+  }
+
+  public static boolean[] arrayCopyBool(boolean[] array, int newLength) {
+    int oldLength = (array == null ? -1 : array.length);
+    if (newLength < 0) newLength = oldLength;
+    /**
+     * @j2sNative
+     * 
+     *     if (newLength < oldLength) return Clazz.array(-1, array, 0, newLength);
+     */
+    {}
+    boolean[] t = new boolean[newLength];
+    if (array != null) {
+      System.arraycopy(array, 0, t, 0, oldLength < newLength ? oldLength
+          : newLength);
+    }
+    return t;
+  }
+
+  public static void swapInt(int[] array, int indexA, int indexB) {
+    int t = array[indexA];
+    array[indexA] = array[indexB];
+    array[indexB] = t;
+  }
+
+  /*
+  public static void swap(short[] array, int indexA, int indexB) {
+    short t = array[indexA];
+    array[indexA] = array[indexB];
+    array[indexB] = t;
+  }
+
+  public static void swap(float[] array, int indexA, int indexB) {
+    float t = array[indexA];
+    array[indexA] = array[indexB];
+    array[indexB] = t;
+  }
+  */
+  
+  public static String dumpArray(String msg, float[][] A, int x1, int x2, int y1, int y2) {
+    String s = "dumpArray: " + msg + "\n";
+    for (int x = x1; x <= x2; x++)
+      s += "\t*" + x + "*";
+    for (int y = y2; y >= y1; y--) {
+      s += "\n*" + y + "*";
+      for (int x = x1; x <= x2; x++)
+        s += "\t" + (x < A.length && y < A[x].length ? A[x][y] : Float.NaN);
+    }
+    return s;
+  }
+
+  public static String dumpIntArray(int[] A, int n) {
+    String str = "";
+    for (int i = 0; i < n; i++)
+      str += " " + A[i];
+    return str;
+  }
+
+  public static String sortedItem(Lst<String> v, int n) {
+    if (v.size() == 0)
+      return null;
+    if (v.size() == 1)
+      return v.get(0);
+    String[] keys = v.toArray(new String[v.size()]);
+    Arrays.sort(keys);
+    return keys[n % keys.length];
+  }
+
+  /**
+   * Helper method for creating a List<Tx>[] without warnings.
+   * 
+   * @param <type> Type of objects in the list.
+   * @param size Array size.
+   * @return Array of List<type>
+   */
+  @SuppressWarnings("unchecked")
+  public static <type> Lst<type>[] createArrayOfArrayList(int size) {
+    return new Lst[size];
+  }
+
+  /**
+   * Helper method for creating a Map<K, V>[] without warnings.
+   * 
+   * @param <K> Type of object for the keys in the map.
+   * @param <V> Type of object for the values in the map.
+   * @param size Array size.
+   * @return Array of Map<K, V>
+   */
+  @SuppressWarnings("unchecked")
+  public static <K, V> Map<K, V>[] createArrayOfHashtable(int size) {
+    return new Hashtable[size];
+  }
+
+  public static void swap(Object[] o, int i, int j) {
+    Object oi = o[i];
+    o[i] = o[j];
+    o[j] = oi;
+  }
+
+  public static float[][] newFloat2(int n) {
+    return new float[n][];
+  }
+
+       public static boolean[][] newBool2(int n) {
+       return new boolean[n][];
+       }
+
+  public static int[][] newInt2(int n) {
+    return new int[n][];
+  }
+
+  public static int[][][] newInt3(int nx, int ny) {
+    return (ny < 0 ? new int[nx][][] : new int[nx][ny][]);
+  }
+
+  public static float[][][] newFloat3(int nx, int ny) {
+    return (ny < 0 ? new float[nx][][] : new float[nx][ny][]);
+  }
+
+  public static int[][][][] newInt4(int n) {
+    return new int[n][][][];
+  }
+
+  public static short[][] newShort2(int n) {
+    return new short[n][];
+  }
+
+  public static byte[][] newByte2(int n) {
+    return new byte[n][];
+  }
+
+  public static double[][] newDouble2(int n) {
+    return new double[n][];
+  }
+
+  /**
+   * remove all keys from a map that start with given root
+   * @param map
+   * @param root
+   * @return number removed
+   */
+  public static int removeMapKeys(Map<String, ?> map, String root) {
+    Lst<String> list = new Lst<String>();
+    for (String key: map.keySet())
+      if (key.startsWith(root))
+        list.addLast(key);
+    for (int i = list.size(); --i >= 0;)
+      map.remove(list.get(i));
+    return list.size();
+  }
+
+       public static boolean isAS(Object x) {
+               return x instanceof String[];
+       }
+
+       public static boolean isASS(Object x) {
+               return x instanceof String[][];
+       }
+
+       public static boolean isAP(Object x) {
+               return x instanceof T3[];
+       }
+
+       public static boolean isAF(Object x) {
+         return x instanceof float[];
+       }
+
+       public static boolean isAFloat(Object x) {
+         return x instanceof Float[];
+       }
+
+       public static boolean isAD(Object x) {
+         return x instanceof double[];
+       }
+
+       public static boolean isADD(Object x) {
+         return x instanceof double[][];
+       }
+
+       public static boolean isAB(Object x) {
+         return x instanceof byte[];
+       }
+
+       public static boolean isAI(Object x) {
+         return x instanceof int[];
+       }
+
+       public static boolean isAII(Object x) {
+         return (x instanceof int[][]);
+       }
+
+       public static boolean isAFF(Object x) {
+         return x instanceof float[][];
+       }
+
+       public static boolean isAFFF(Object x) {
+         return x instanceof float[][][];
+       }
+       
+       /**
+        * Ensure that we have signed and not unsigned bytes coming out of any
+        * process, but particularly out of file reading.
+        * 
+        * @param b
+        * @return b
+        */
+       public static byte[] ensureSignedBytes(byte[] b) {
+               if (b != null) {
+                       /**
+                        * @j2sNative
+                        * 
+                        *                      for (var i = b.length; --i >= 0;) { var j = b[i] &
+                        *            0xFF; if (j >= 0x80) j -= 0x100; b[i] = j; }
+                        * 
+                        */
+                       {
+                       }
+               }
+               return b;
+       }
+
+
+}
diff --git a/src2/javajs/util/AjaxURLConnection.java b/src2/javajs/util/AjaxURLConnection.java
new file mode 100644 (file)
index 0000000..0b038c3
--- /dev/null
@@ -0,0 +1,120 @@
+package javajs.util;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLConnection;
+
+import javajs.api.js.J2SObjectInterface;
+
+/**
+ * 
+ * A method to allow a JavaScript Ajax 
+ * 
+ */
+public class AjaxURLConnection extends URLConnection {
+
+  protected AjaxURLConnection(URL url) {
+    super(url);
+  }
+
+  byte[] bytesOut;
+  String postOut = "";
+
+  /**
+   * 
+   * doAjax() is where the synchronous call to AJAX is to happen. or at least
+   * where we wait for the asynchronous call to return. This method should fill
+   * the dataIn field with either a string or byte array, or null if you want to
+   * throw an error.
+   * 
+   * url, bytesOut, and postOut are all available for use
+   * 
+   * the method is "private", but in JavaScript that can still be overloaded.
+   * Just set something to org.jmol.awtjs.JmolURLConnection.prototype.doAjax
+   * 
+   * 
+   * @param isBinary 
+   * 
+   * @return file data as a javajs.util.SB or byte[] depending upon the file
+   *         type.
+   * 
+   * 
+   */
+  @SuppressWarnings("null")
+  private Object doAjax(boolean isBinary) {
+    J2SObjectInterface j2s = null;
+    /**
+     * @j2sNative
+     * 
+     *            j2s = J2S;
+     * 
+     */
+    {
+    }
+    return j2s._doAjax(url, postOut, bytesOut, isBinary);
+  }
+
+  @Override
+  public void connect() throws IOException {
+    // not expected to be used. 
+  }
+
+  public void outputBytes(byte[] bytes) {
+    //      type = "application/octet-stream;";
+    bytesOut = bytes;
+  }
+
+  public void outputString(String post) {
+    postOut = post;
+    //     type = "application/x-www-form-urlencoded";
+  }
+
+       @Override
+       public InputStream getInputStream() {
+               BufferedInputStream is = getAttachedStreamData(url, false);
+               return (is == null ? attachStreamData(url, doAjax(true)) : is);
+       }
+
+       /**
+        * J2S will attach the data (String, SB, or byte[]) to any URL that is 
+        * retrieved using a ClassLoader. This improves performance by
+        * not going back to the server every time a second time, since
+        * the first time in Java is usually just to see if it exists. 
+        * 
+        * @param url
+        * @return String, SB, or byte[]
+        */
+       public static BufferedInputStream getAttachedStreamData(URL url, boolean andDelete) {
+       
+               Object data = null;
+               /**
+                * @j2sNative
+                * 
+                *       data = url._streamData;
+                *       if (andDelete) url._streamData = null;
+                */
+               {
+               }
+               return (data == null ? null : Rdr.toBIS(data));
+       }
+
+   public static BufferedInputStream attachStreamData(URL url, Object o) {
+          /**
+           * @j2sNative
+           * 
+           *   url._streamData = o;
+           */
+          
+           return (o == null ? null : Rdr.toBIS(o));
+  }
+
+  /**
+   * @return javajs.util.SB or byte[], depending upon the file type
+   */
+  public Object getContents() {
+    return doAjax(false);
+  }
+
+}
diff --git a/src2/javajs/util/AjaxURLStreamHandler.java b/src2/javajs/util/AjaxURLStreamHandler.java
new file mode 100644 (file)
index 0000000..3d6d4d7
--- /dev/null
@@ -0,0 +1,53 @@
+package javajs.util;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+
+
+
+/**
+ * 
+ * A method to allow a JavaScript AJAX adapter to 
+ * deliver web content to JSmol. This handler is just a formality.
+ * 
+ */
+public class AjaxURLStreamHandler extends URLStreamHandler {
+
+       String protocol;
+
+       public AjaxURLStreamHandler(String protocol) {
+               this.protocol = protocol;
+       }
+
+       @Override
+       protected URLConnection openConnection(URL url) throws IOException {
+               return new AjaxURLConnection(url);
+       }
+
+
+  @Override
+  protected String toExternalForm(URL u) {
+    SB result = new SB();
+    result.append(u.getProtocol());
+    result.append(":");
+    if (u.getAuthority() != null && u.getAuthority().length() > 0) {
+      result.append("//");
+      result.append(u.getAuthority());
+    }
+    if (u.getPath() != null) {
+      result.append(u.getPath());
+    }
+    if (u.getQuery() != null) {
+      result.append("?");
+      result.append(u.getQuery());
+    }
+    if (u.getRef() != null) {
+      result.append("#");
+      result.append(u.getRef());
+    }
+    return result.toString();
+  }
+
+}
diff --git a/src2/javajs/util/AjaxURLStreamHandlerFactory.java b/src2/javajs/util/AjaxURLStreamHandlerFactory.java
new file mode 100644 (file)
index 0000000..ef903a2
--- /dev/null
@@ -0,0 +1,31 @@
+package javajs.util;
+
+import java.net.URLStreamHandler;
+import java.net.URLStreamHandlerFactory;
+import java.util.Hashtable;
+import java.util.Map;
+
+
+/**
+ * 
+ * For handling URL file IO via AJAX in JavaScript version
+ * 
+ */
+
+public class AjaxURLStreamHandlerFactory implements URLStreamHandlerFactory {
+
+       Map<String, AjaxURLStreamHandler> htFactories = new Hashtable<String, AjaxURLStreamHandler>();
+       
+       public AjaxURLStreamHandlerFactory() {
+        // for reflection;
+       }
+       
+       @Override
+  public URLStreamHandler createURLStreamHandler(String protocol) {
+               AjaxURLStreamHandler fac = htFactories.get(protocol);
+               if (fac == null)
+                       htFactories.put(protocol, fac = new AjaxURLStreamHandler(protocol));
+               return (fac.protocol == null ? null : fac);
+       }
+
+}
diff --git a/src2/javajs/util/ArrayDataReader.java b/src2/javajs/util/ArrayDataReader.java
new file mode 100644 (file)
index 0000000..737a6ab
--- /dev/null
@@ -0,0 +1,57 @@
+package javajs.util;
+
+import java.io.IOException;
+
+
+
+
+
+
+/**
+ * 
+ * ArrayDataReader subclasses BufferedReader and overrides its
+ * read, readLine, mark, and reset methods so that JmolAdapter 
+ * works with String[] arrays without any further adaptation. 
+ * 
+ */
+
+public class ArrayDataReader extends DataReader {
+  private String[] data;
+  private int pt;
+  private int len;
+
+  public ArrayDataReader() {
+    super();
+  }
+  
+  @Override
+  public DataReader setData(Object data) {
+    this.data = (String[]) data;
+    len = this.data.length;
+    return this;
+  }
+
+  @Override
+  public int read(char[] buf, int off, int len) throws IOException {
+    return readBuf(buf, off, len);
+  }
+
+  @Override
+  public String readLine() {
+    return (pt < len ? data[pt++] : null);
+  }
+
+  /**
+   * 
+   * @param ptr
+   */
+  public void mark(long ptr) {
+    //ignore ptr.
+    ptMark = pt;
+  }
+
+  @Override
+  public void reset() {
+    pt = ptMark;
+  }
+}
\ No newline at end of file
diff --git a/src2/javajs/util/BArray.java b/src2/javajs/util/BArray.java
new file mode 100644 (file)
index 0000000..f09d272
--- /dev/null
@@ -0,0 +1,33 @@
+package javajs.util;
+
+public class BArray {
+  public byte[] data;
+  
+  public BArray(byte[] data) {
+    this.data = data;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (o instanceof BArray) {
+      byte[] d = ((BArray) o).data;
+      if (d.length == data.length){
+        for (int i = 0; i < d.length; i++)
+          if (d[i] != data[i])
+            return false;
+        return true;
+      }
+    }
+    return false;
+  }
+
+  @Override
+  public int hashCode() {
+    return data.hashCode();
+  }
+  
+  @Override
+  public String toString() {
+    return new String(data);
+  }
+}
diff --git a/src2/javajs/util/BC.java b/src2/javajs/util/BC.java
new file mode 100644 (file)
index 0000000..5722efd
--- /dev/null
@@ -0,0 +1,186 @@
+package javajs.util;
+
+/**
+ * byte converter
+ * 
+ * 
+ * @author Bob Hanson hansonr@stolaf.edu
+ * 
+ */
+public class BC {
+
+  public BC() {
+    // unnecessary to instantialize unless subclassed
+  }
+  
+  public static float bytesToFloat(byte[] bytes, int j, boolean isBigEndian) throws Exception {
+    return intToFloat(bytesToInt(bytes, j, isBigEndian));
+  }
+
+  public static int bytesToShort(byte[] bytes, int j, boolean isBigEndian) {
+    int n = (isBigEndian ? (bytes[j + 1] & 0xff) | (bytes[j] & 0xff) << 8
+        : (bytes[j++] & 0xff) | (bytes[j++] & 0xff) << 8);
+      return (n > 0x7FFF ? n - 0x10000 : n);
+  }
+
+  public static int bytesToInt(byte[] bytes, int j, boolean isBigEndian) {
+    int n = (isBigEndian ? (bytes[j + 3] & 0xff) | (bytes[j + 2] & 0xff) << 8
+        | (bytes[j + 1] & 0xff) << 16 | (bytes[j] & 0xff) << 24
+        : (bytes[j++] & 0xff) | (bytes[j++] & 0xff) << 8
+            | (bytes[j++] & 0xff) << 16 | (bytes[j++] & 0xff) << 24);
+    /**
+     * @j2sNative
+     * 
+     * return (n > 0x7FFFFFFF ? n - 0x100000000 : n);
+     *   
+     */
+    {
+      return n;
+    }
+  }
+
+  public static int intToSignedInt(int n) {
+    /**
+     * @j2sNative
+     * 
+     * return (n > 0x7FFFFFFF ? n - 0x100000000 : n);
+     *   
+     */
+    {
+      return n;
+    }    
+  }
+  public static float intToFloat(int x) throws Exception {
+    /**
+     * see http://en.wikipedia.org/wiki/Binary32
+     * 
+     * [sign]      [8 bits power] [23 bits fraction]
+     * 0x80000000  0x7F800000      0x7FFFFF
+     * 
+     * (untested)
+     * 
+     * @j2sNative
+     * 
+     *       if (x == 0) return 0;
+     *       var o = javajs.util.BC;
+     *       if (o.fracIEEE == null)
+     *         o.setFracIEEE();
+     *       var m = ((x & 0x7F800000) >> 23);
+     *       return ((x & 0x80000000) == 0 ? 1 : -1) * o.shiftIEEE$D$I((x & 0x7FFFFF) | 0x800000, m - 149);
+     *  
+     */
+    {
+    return Float.intBitsToFloat(x);
+    }
+  }
+
+  /**
+   * see http://en.wikipedia.org/wiki/Binary64
+   *  
+   * not concerning ourselves with very small or very large numbers and getting
+   * this exactly right. Just need a float here.
+   * 
+   * @param bytes
+   * @param j
+   * @param isBigEndian
+   * @return float
+   */
+  public static float bytesToDoubleToFloat(byte[] bytes, int j, boolean isBigEndian) {
+    {
+      // IEEE754: sign (1 bit), exponent (11 bits), fraction (52 bits).
+      // seeeeeee eeeeffff ffffffff ffffffff ffffffff xxxxxxxx xxxxxxxx xxxxxxxx
+      //     b1      b2       b3       b4       b5    ---------float ignores----
+
+        if (fracIEEE == null)
+           setFracIEEE();
+        
+      /**
+       * @j2sNative
+       *       var b1, b2, b3, b4, b5;
+       *       
+       *       if (isBigEndian) {
+       *       b1 = bytes[j] & 0xFF;
+       *       b2 = bytes[j + 1] & 0xFF;
+       *       b3 = bytes[j + 2] & 0xFF;
+       *       b4 = bytes[j + 3] & 0xFF;
+       *       b5 = bytes[j + 4] & 0xFF;
+       *       } else {
+       *       b1 = bytes[j + 7] & 0xFF;
+       *       b2 = bytes[j + 6] & 0xFF;
+       *       b3 = bytes[j + 5] & 0xFF;
+       *       b4 = bytes[j + 4] & 0xFF;
+       *       b5 = bytes[j + 3] & 0xFF;
+       *       }
+       *       var s = ((b1 & 0x80) == 0 ? 1 : -1);
+       *       var e = (((b1 & 0x7F) << 4) | (b2 >> 4)) - 1026;
+       *       b2 = (b2 & 0xF) | 0x10;
+       *       return s * (C$.shiftIEEE$D$I(b2, e) +C$.shiftIEEE$D$I(b3, e - 8) + C$.shiftIEEE$D$I(b4, e - 16)
+       *         + C$.shiftIEEE$D$I(b5, e - 24));
+       */
+      {
+        double d;
+        
+        if (isBigEndian)
+          d = Double.longBitsToDouble((((long) bytes[j]) & 0xff) << 56
+             | (((long) bytes[j + 1]) & 0xff) << 48
+             | (((long) bytes[j + 2]) & 0xff) << 40
+             | (((long) bytes[j + 3]) & 0xff) << 32
+             | (((long) bytes[j + 4]) & 0xff) << 24
+             | (((long) bytes[j + 5]) & 0xff) << 16
+             | (((long) bytes[j + 6]) & 0xff) << 8 
+             | (((long) bytes[7]) & 0xff));
+        else
+          d = Double.longBitsToDouble((((long) bytes[j + 7]) & 0xff) << 56
+             | (((long) bytes[j + 6]) & 0xff) << 48
+             | (((long) bytes[j + 5]) & 0xff) << 40
+             | (((long) bytes[j + 4]) & 0xff) << 32
+             | (((long) bytes[j + 3]) & 0xff) << 24
+             | (((long) bytes[j + 2]) & 0xff) << 16
+             | (((long) bytes[j + 1]) & 0xff) << 8 
+             | (((long) bytes[j]) & 0xff));
+        return (float) d;
+      }
+
+    }
+  }
+
+  private static float[] fracIEEE;
+
+  private static void setFracIEEE() {
+    fracIEEE = new float[270];
+    for (int i = 0; i < 270; i++)
+      fracIEEE[i] = (float) Math.pow(2, i - 141);
+    //    System.out.println(fracIEEE[0] + "  " + Parser.FLOAT_MIN_SAFE);
+    //    System.out.println(fracIEEE[269] + "  " + Float.MAX_VALUE);
+  }
+
+  /**
+   * only concerned about reasonable float values here -- private but not designated; called by JavaScript
+   * 
+   * @param f
+   * @param i
+   * @return f * 2^i
+   */
+  static double shiftIEEE(double f, int i) {
+    if (f == 0 || i < -140)
+      return 0;
+    if (i > 128)
+      return Float.MAX_VALUE;
+    return f * fracIEEE[i + 140];
+  }
+
+//  static {
+//    setFracIEEE();
+//    for (int i = -50; i < 50; i++) {
+//      float f = i * (float) (Math.random() * Math.pow(2, Math.random() * 100 - 50));
+//      int x = Float.floatToIntBits(f);
+//      int m = ((x & 0x7F800000) >> 23);
+//      float f1 = (float) (f == 0 ? 0 : ((x & 0x80000000) == 0 ? 1 : -1) * shiftIEEE((x & 0x7FFFFF) | 0x800000, m - 149));
+//      System.out.println(f + "  " + f1);
+//    }
+//    System.out.println("binarydo");
+//  }
+
+
+
+}
diff --git a/src2/javajs/util/BS.java b/src2/javajs/util/BS.java
new file mode 100644 (file)
index 0000000..1f3aaa4
--- /dev/null
@@ -0,0 +1,960 @@
+/*
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright 1995-2007 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code 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
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package javajs.util;
+
+import javajs.api.JSONEncodable;
+
+
+
+/**
+ * 
+ * a fast 32-bit BitSet optimized for Java2Script -- about 25 times faster than
+ * java.util.BitSet
+ * 
+ * @author Bob Hanson hansonr@stolaf.edu
+ * 
+ *         Additions by Bob Hanson to allow for JavaScript mix of int/long Note
+ *         that Firefox (Sept 2012) does not really treat "Int32Array" as such,
+ *         because any element can be pushed into being a 64-bit number, which
+ *         really isn't because the last 8 bits are not usable.
+ * 
+ *         This class implements a vector of bits that grows as needed. Each
+ *         component of the bit set has a {@code boolean} value. The bits of a
+ *         {@code BitSet} are indexed by nonnegative integers. Individual
+ *         indexed bits can be examined, set, or cleared. One {@code BitSet} may
+ *         be used to modify the contents of another {@code BitSet} through
+ *         logical AND, logical inclusive OR, and logical exclusive OR
+ *         operations.
+ * 
+ *         <p>
+ *         By default, all bits in the set initially have the value {@code
+ *         false}.
+ * 
+ *         <p>
+ *         Every bit set has a current size, which is the number of bits of
+ *         space currently in use by the bit set. Note that the size is related
+ *         to the implementation of a bit set, so it may change with
+ *         implementation. The length of a bit set relates to logical length of
+ *         a bit set and is defined independently of implementation.
+ * 
+ *         <p>
+ *         Unless otherwise noted, passing a null parameter to any of the
+ *         methods in a {@code BitSet} will result in a {@code
+ *         NullPointerException}.
+ * 
+ *         <p>
+ *         A {@code BitSet} is not safe for multithreaded use without external
+ *         synchronization.
+ * 
+ * @author Arthur van Hoff
+ * @author Michael McCloskey
+ * @author Martin Buchholz
+ * @since JDK1.0
+ */
+public class BS implements Cloneable, JSONEncodable {
+  /*
+   * BitSets are packed into arrays of "words."
+   * 
+   * An int, which consists of 32 bits, requiring 5 address bits, is used for
+   * the JavaScript port.
+   */
+  private final static int ADDRESS_BITS_PER_WORD = 5;
+  private final static int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD;
+  protected final static int BIT_INDEX_MASK = BITS_PER_WORD - 1;
+
+  /* Used to shift left or right for a partial word mask */
+  protected static final int WORD_MASK = 0xffffffff;
+
+
+  /**
+   * The internal field corresponding to the serialField "bits".
+   */
+  protected int[] words;
+
+  /**
+   * The number of words in the logical size of this BitSet.
+   */
+  protected transient int wordsInUse = 0;
+
+  /**
+   * Whether the size of "words" is user-specified. If so, we assume the user
+   * knows what he's doing and try harder to preserve it.
+   */
+  private transient boolean sizeIsSticky = false;
+
+  /* use serialVersionUID from JDK 1.0.2 for interoperability */
+  //private static final long serialVersionUID = 7997698588986878753L;
+
+  /**
+   * Given a bit index, return word index containing it.
+   * @param bitIndex 
+   * @return b
+   */
+  protected static int wordIndex(int bitIndex) {
+    return bitIndex >> ADDRESS_BITS_PER_WORD;
+  }
+
+  /**
+   * Sets the field wordsInUse to the logical size in words of the bit set.
+   * WARNING:This method assumes that the number of words actually in use is
+   * less than or equal to the current value of wordsInUse!
+   */
+  protected void recalculateWordsInUse() {
+    // Traverse the bitset until a used word is found
+    int i;
+    for (i = wordsInUse - 1; i >= 0; i--)
+      if (words[i] != 0)
+        break;
+
+    wordsInUse = i + 1; // The new logical size
+  }
+
+  /**
+   * Creates a new bit set. All bits are initially {@code false}.
+   */
+  public BS() {
+    initWords(BITS_PER_WORD);
+    sizeIsSticky = false;
+  }
+
+  /**
+   * Creates a bit set whose initial size is large enough to explicitly
+   * represent bits with indices in the range {@code 0} through {@code nbits-1}.
+   * All bits are initially {@code false}.
+   * 
+   * @param nbits
+   *          the initial size of the bit set
+   * @return bs
+   * @throws NegativeArraySizeException
+   *           if the specified initial size is negative
+   */
+  public static BS newN(int nbits) {
+    BS bs = new BS();
+    bs.init(nbits);
+    return bs;
+  }
+
+  protected void init(int nbits) {
+    // nbits can't be negative; size 0 is OK
+    if (nbits < 0)
+      throw new NegativeArraySizeException("nbits < 0: " + nbits);
+    initWords(nbits);
+    sizeIsSticky = true;
+  }
+
+  private void initWords(int nbits) {
+    words = new int[wordIndex(nbits - 1) + 1];
+  }
+
+  /**
+   * Ensures that the BitSet can hold enough words.
+   * 
+   * @param wordsRequired
+   *          the minimum acceptable number of words.
+   */
+  private void ensureCapacity(int wordsRequired) {
+    if (words.length < wordsRequired) {
+      // Allocate larger of doubled size or required size
+      int request = Math.max(2 * words.length, wordsRequired);
+      setLength(request);
+      sizeIsSticky = false;
+    }
+  }
+
+  /**
+   * Ensures that the BitSet can accommodate a given wordIndex, temporarily
+   * violating the invariants. The caller must restore the invariants before
+   * returning to the user, possibly using recalculateWordsInUse().
+   * 
+   * @param wordIndex
+   *          the index to be accommodated.
+   */
+  protected void expandTo(int wordIndex) {
+    int wordsRequired = wordIndex + 1;
+    if (wordsInUse < wordsRequired) {
+      ensureCapacity(wordsRequired);
+      wordsInUse = wordsRequired;
+    }
+  }
+
+
+  /**
+   * Sets the bit at the specified index to {@code true}.
+   * 
+   * @param bitIndex
+   *          a bit index
+   * @throws IndexOutOfBoundsException
+   *           if the specified index is negative
+   * @since JDK1.0
+   */
+  public void set(int bitIndex) {
+    if (bitIndex < 0)
+      throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
+
+    int wordIndex = wordIndex(bitIndex);
+    expandTo(wordIndex);
+
+    words[wordIndex] |= (1 << bitIndex); // Restores invariants
+
+  }
+
+  /**
+   * Sets the bit at the specified index to the specified value.
+   * 
+   * @param bitIndex
+   *          a bit index
+   * @param value
+   *          a boolean value to set
+   * @throws IndexOutOfBoundsException
+   *           if the specified index is negative
+   * @since 1.4
+   */
+  public void setBitTo(int bitIndex, boolean value) {
+    if (value)
+      set(bitIndex);
+    else
+      clear(bitIndex);
+  }
+
+  /**
+   * Sets the bits from the specified {@code fromIndex} (inclusive) to the
+   * specified {@code toIndex} (exclusive) to {@code true}.
+   * 
+   * @param fromIndex
+   *          index of the first bit to be set
+   * @param toIndex
+   *          index after the last bit to be set
+   * @throws IndexOutOfBoundsException
+   *           if {@code fromIndex} is negative, or {@code toIndex} is negative,
+   *           or {@code fromIndex} is larger than {@code toIndex}
+   * @since 1.4
+   */
+  public void setBits(int fromIndex, int toIndex) {
+
+    if (fromIndex == toIndex)
+      return;
+
+    // Increase capacity if necessary
+    int startWordIndex = wordIndex(fromIndex);
+    int endWordIndex = wordIndex(toIndex - 1);
+    expandTo(endWordIndex);
+
+    int firstWordMask = WORD_MASK << fromIndex;
+    int lastWordMask = WORD_MASK >>> -toIndex;
+    if (startWordIndex == endWordIndex) {
+      // Case 1: One word
+      words[startWordIndex] |= (firstWordMask & lastWordMask);
+    } else {
+      // Case 2: Multiple words
+      // Handle first word
+      words[startWordIndex] |= firstWordMask;
+
+      // Handle intermediate words, if any
+      for (int i = startWordIndex + 1; i < endWordIndex; i++)
+        words[i] = WORD_MASK;
+
+      // Handle last word (restores invariants)
+      words[endWordIndex] |= lastWordMask;
+    }
+  }
+
+  /**
+   * Sets the bit specified by the index to {@code false}.
+   * 
+   * @param bitIndex
+   *          the index of the bit to be cleared
+   * @throws IndexOutOfBoundsException
+   *           if the specified index is negative
+   * @since JDK1.0
+   */
+  public void clear(int bitIndex) {
+    if (bitIndex < 0)
+      throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
+
+    int wordIndex = wordIndex(bitIndex);
+    if (wordIndex >= wordsInUse)
+      return;
+
+    words[wordIndex] &= ~(1 << bitIndex);
+
+    recalculateWordsInUse();
+  }
+
+  /**
+   * Sets the bits from the specified {@code fromIndex} (inclusive) to the
+   * specified {@code toIndex} (exclusive) to {@code false}.
+   * 
+   * @param fromIndex
+   *          index of the first bit to be cleared
+   * @param toIndex
+   *          index after the last bit to be cleared
+   * @throws IndexOutOfBoundsException
+   *           if {@code fromIndex} is negative, or {@code toIndex} is negative,
+   *           or {@code fromIndex} is larger than {@code toIndex}
+   * @since 1.4
+   */
+  public void clearBits(int fromIndex, int toIndex) {
+    if (fromIndex == toIndex)
+      return;
+
+    int startWordIndex = wordIndex(fromIndex);
+    if (startWordIndex >= wordsInUse)
+      return;
+
+    int endWordIndex = wordIndex(toIndex - 1);
+    if (endWordIndex >= wordsInUse) {
+      toIndex = length();
+      endWordIndex = wordsInUse - 1;
+    }
+
+    int firstWordMask = WORD_MASK << fromIndex;
+    int lastWordMask = WORD_MASK >>> -toIndex;
+    if (startWordIndex == endWordIndex) {
+      // Case 1: One word
+      words[startWordIndex] &= ~(firstWordMask & lastWordMask);
+    } else {
+      // Case 2: Multiple words
+      // Handle first word
+      words[startWordIndex] &= ~firstWordMask;
+
+      // Handle intermediate words, if any
+      for (int i = startWordIndex + 1; i < endWordIndex; i++)
+        words[i] = 0;
+
+      // Handle last word
+      words[endWordIndex] &= ~lastWordMask;
+    }
+
+    recalculateWordsInUse();
+  }
+
+  /**
+   * Sets all of the bits in this BitSet to {@code false}.
+   * 
+   * @since 1.4
+   */
+  public void clearAll() {
+    while (wordsInUse > 0)
+      words[--wordsInUse] = 0;
+  }
+
+  /**
+   * Returns the value of the bit with the specified index. The value is {@code
+   * true} if the bit with the index {@code bitIndex} is currently set in this
+   * {@code BitSet}; otherwise, the result is {@code false}.
+   * 
+   * @param bitIndex
+   *          the bit index
+   * @return the value of the bit with the specified index
+   * @throws IndexOutOfBoundsException
+   *           if the specified index is negative
+   */
+  public boolean get(int bitIndex) {
+    if (bitIndex < 0)
+      throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
+
+    int wordIndex = wordIndex(bitIndex);
+    return (wordIndex < wordsInUse)
+        && ((words[wordIndex] & (1 << bitIndex)) != 0);
+  }
+
+  /**
+   * Returns the index of the first bit that is set to {@code true} that occurs
+   * on or after the specified starting index. If no such bit exists then
+   * {@code -1} is returned.
+   * 
+   * <p>
+   * To iterate over the {@code true} bits in a {@code BitSet}, use the
+   * following loop:
+   * 
+   * <pre>
+   * @code
+   * for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
+   *     // operate on index i here
+   * }}
+   * </pre>
+   * 
+   * @param fromIndex
+   *          the index to start checking from (inclusive)
+   * @return the index of the next set bit, or {@code -1} if there is no such
+   *         bit
+   * @throws IndexOutOfBoundsException
+   *           if the specified index is negative
+   * @since 1.4
+   */
+  public int nextSetBit(int fromIndex) {
+    if (fromIndex < 0)
+      throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
+
+    int u = wordIndex(fromIndex);
+    if (u >= wordsInUse)
+      return -1;
+
+    int word = words[u] & (WORD_MASK << fromIndex);
+
+    while (true) {
+      if (word != 0)
+        return (u * BITS_PER_WORD) + Integer.numberOfTrailingZeros(word);
+      if (++u == wordsInUse)
+        return -1;
+      word = words[u];
+    }
+  }
+
+  /**
+   * Returns the index of the first bit that is set to {@code false} that occurs
+   * on or after the specified starting index.
+   * 
+   * @param fromIndex
+   *          the index to start checking from (inclusive)
+   * @return the index of the next clear bit
+   * @throws IndexOutOfBoundsException
+   *           if the specified index is negative
+   * @since 1.4
+   */
+  public int nextClearBit(int fromIndex) {
+    // Neither spec nor implementation handle bitsets of maximal length.
+    // See 4816253.
+    if (fromIndex < 0)
+      throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
+
+    int u = wordIndex(fromIndex);
+    if (u >= wordsInUse)
+      return fromIndex;
+
+    int word = ~words[u] & (WORD_MASK << fromIndex);
+
+    while (true) {
+      if (word != 0)
+        return (u * BITS_PER_WORD) + Integer.numberOfTrailingZeros(word);
+      if (++u == wordsInUse)
+        return wordsInUse * BITS_PER_WORD;
+      word = ~words[u];
+    }
+  }
+
+  /**
+   * Returns the "logical size" of this {@code BitSet}: the index of the highest
+   * set bit in the {@code BitSet} plus one. Returns zero if the {@code BitSet}
+   * contains no set bits.
+   * 
+   * @return the logical size of this {@code BitSet}
+   * @since 1.2
+   */
+  public int length() {
+    if (wordsInUse == 0)
+      return 0;
+
+    return BITS_PER_WORD * (wordsInUse - 1)
+        + (BITS_PER_WORD - Integer.numberOfLeadingZeros(words[wordsInUse - 1]));
+  }
+
+  /**
+   * Returns true if this {@code BitSet} contains no bits that are set to
+   * {@code true}.
+   * 
+   * @return boolean indicating whether this {@code BitSet} is empty
+   * @since 1.4
+   */
+  public boolean isEmpty() {
+    return wordsInUse == 0;
+  }
+
+  /**
+   * Returns true if the specified {@code BitSet} has any bits set to {@code
+   * true} that are also set to {@code true} in this {@code BitSet}.
+   * 
+   * @param set
+   *          {@code BitSet} to intersect with
+   * @return boolean indicating whether this {@code BitSet} intersects the
+   *         specified {@code BitSet}
+   * @since 1.4
+   */
+  public boolean intersects(BS set) {
+    for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)
+      if ((words[i] & set.words[i]) != 0)
+        return true;
+    return false;
+  }
+
+  /**
+   * Returns the number of bits set to {@code true} in this {@code BitSet}.
+   * 
+   * @return the number of bits set to {@code true} in this {@code BitSet}
+   * @since 1.4
+   */
+  public int cardinality() {
+    int sum = 0;
+    for (int i = 0; i < wordsInUse; i++)
+      sum += Integer.bitCount(words[i]);
+    return sum;
+  }
+
+  /**
+   * Performs a logical <b>AND</b> of this target bit set with the argument bit
+   * set. This bit set is modified so that each bit in it has the value {@code
+   * true} if and only if it both initially had the value {@code true} and the
+   * corresponding bit in the bit set argument also had the value {@code true}.
+   * 
+   * @param set
+   *          a bit set
+   */
+  public void and(BS set) {
+    if (this == set)
+      return;
+
+    while (wordsInUse > set.wordsInUse)
+      words[--wordsInUse] = 0;
+
+    // Perform logical AND on words in common
+    for (int i = 0; i < wordsInUse; i++)
+      words[i] &= set.words[i];
+
+    recalculateWordsInUse();
+  }
+
+  /**
+   * Performs a logical <b>OR</b> of this bit set with the bit set argument.
+   * This bit set is modified so that a bit in it has the value {@code true} if
+   * and only if it either already had the value {@code true} or the
+   * corresponding bit in the bit set argument has the value {@code true}.
+   * 
+   * @param set
+   *          a bit set
+   */
+  public void or(BS set) {
+    if (this == set)
+      return;
+
+    int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);
+
+    if (wordsInUse < set.wordsInUse) {
+      ensureCapacity(set.wordsInUse);
+      wordsInUse = set.wordsInUse;
+    }
+
+    // Perform logical OR on words in common
+    for (int i = 0; i < wordsInCommon; i++)
+      words[i] |= set.words[i];
+
+    // Copy any remaining words
+    if (wordsInCommon < set.wordsInUse)
+      System.arraycopy(set.words, wordsInCommon, words, wordsInCommon,
+          wordsInUse - wordsInCommon);
+
+  }
+
+  /**
+   * Performs a logical <b>XOR</b> of this bit set with the bit set argument.
+   * This bit set is modified so that a bit in it has the value {@code true} if
+   * and only if one of the following statements holds:
+   * <ul>
+   * <li>The bit initially has the value {@code true}, and the corresponding bit
+   * in the argument has the value {@code false}.
+   * <li>The bit initially has the value {@code false}, and the corresponding
+   * bit in the argument has the value {@code true}.
+   * </ul>
+   * 
+   * @param set
+   *          a bit set
+   */
+  public void xor(BS set) {
+    int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);
+
+    if (wordsInUse < set.wordsInUse) {
+      ensureCapacity(set.wordsInUse);
+      wordsInUse = set.wordsInUse;
+    }
+
+    // Perform logical XOR on words in common
+    for (int i = 0; i < wordsInCommon; i++)
+      words[i] ^= set.words[i];
+
+    // Copy any remaining words
+    if (wordsInCommon < set.wordsInUse)
+      System.arraycopy(set.words, wordsInCommon, words, wordsInCommon,
+          set.wordsInUse - wordsInCommon);
+
+    recalculateWordsInUse();
+  }
+
+  /**
+   * Clears all of the bits in this {@code BitSet} whose corresponding bit is
+   * set in the specified {@code BitSet}.
+   * 
+   * @param set
+   *          the {@code BitSet} with which to mask this {@code BitSet}
+   * @since 1.2
+   */
+  public void andNot(BS set) {
+    // Perform logical (a & !b) on words in common
+    for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)
+      words[i] &= ~set.words[i];
+
+    recalculateWordsInUse();
+  }
+
+  /**
+   * Returns a hash code value for this bit set. The hash code depends only on
+   * which bits have been set within this <code>BitSet</code>. The algorithm
+   * used to compute it may be described as follows.
+   * <p>
+   * Suppose the bits in the <code>BitSet</code> were to be stored in an array
+   * of <code>long</code> integers called, say, <code>words</code>, in such a
+   * manner that bit <code>k</code> is set in the <code>BitSet</code> (for
+   * nonnegative values of <code>k</code>) if and only if the expression
+   * 
+   * <pre>
+   * ((k &gt;&gt; 6) &lt; words.length) &amp;&amp; ((words[k &gt;&gt; 6] &amp; (1 &lt;&lt; (bit &amp; 0x3F))) != 0)
+   * </pre>
+   * 
+   * is true. Then the following definition of the <code>hashCode</code> method
+   * would be a correct implementation of the actual algorithm:
+   * 
+   * <pre>
+   * public int hashCode() {
+   *  long h = 1234;
+   *  for (int i = words.length; --i &gt;= 0;) {
+   *    h &circ;= words[i] * (i + 1);
+   *  }
+   *  return (int) ((h &gt;&gt; 32) &circ; h);
+   * }
+   * </pre>
+   * 
+   * Note that the hash code values change if the set of bits is altered.
+   * <p>
+   * Overrides the <code>hashCode</code> method of <code>Object</code>.
+   * 
+   * @return a hash code value for this bit set.
+   */
+  @Override
+  public int hashCode() {
+    long h = 1234;
+    for (int i = wordsInUse; --i >= 0;)
+      h ^= words[i] * (i + 1);
+
+    return (int) ((h >> 32) ^ h);
+  }
+
+  /**
+   * Returns the number of bits of space actually in use by this {@code BitSet}
+   * to represent bit values. The maximum element in the set is the size - 1st
+   * element.
+   * 
+   * @return the number of bits currently in this bit set
+   */
+  public int size() {
+    return words.length * BITS_PER_WORD;
+  }
+
+  /**
+   * Compares this object against the specified object. The result is {@code
+   * true} if and only if the argument is not {@code null} and is a {@code
+   * Bitset} object that has exactly the same set of bits set to {@code true} as
+   * this bit set. That is, for every nonnegative {@code int} index {@code k},
+   * 
+   * <pre>
+   * ((BitSet) obj).get(k) == this.get(k)
+   * </pre>
+   * 
+   * must be true. The current sizes of the two bit sets are not compared.
+   * 
+   * @param obj
+   *          the object to compare with
+   * @return {@code true} if the objects are the same; {@code false} otherwise
+   * @see #size()
+   */
+  @Override
+  public boolean equals(Object obj) {
+    if (!(obj instanceof BS))
+      return false;
+    if (this == obj)
+      return true;
+
+    BS set = (BS) obj;
+
+    if (wordsInUse != set.wordsInUse)
+      return false;
+
+    // Check words in use by both BitSets
+    for (int i = 0; i < wordsInUse; i++)
+      if (words[i] != set.words[i])
+        return false;
+
+    return true;
+  }
+
+  /**
+   * Cloning this {@code BitSet} produces a new {@code BitSet} that is equal to
+   * it. The clone of the bit set is another bit set that has exactly the same
+   * bits set to {@code true} as this bit set.
+   * 
+   * @return a clone of this bit set
+   * @see #size()
+   */
+  @Override
+  public Object clone() {
+    if (!sizeIsSticky && wordsInUse != words.length)
+      setLength(wordsInUse);
+    return copy(this);
+  }
+
+  /**
+   * Attempts to reduce internal storage used for the bits in this bit set.
+   * Calling this method may, but is not required to, affect the value returned
+   * by a subsequent call to the {@link #size()} method.
+   * @param n 
+   */
+  private void setLength(int n) {
+    /**
+     * @j2sNative
+     *     if (n == this.words.length) return;
+     *     if (n == this.wordsInUse) {
+     *      this.words = Clazz.array(-1, this.words, 0, n);
+     *      return;
+     *     }
+     */
+    {}
+    int[] a = new int[n];
+    System.arraycopy(words, 0, a, 0, wordsInUse);
+    words = a;    
+  }
+
+  /**
+   * Returns a string representation of this bit set. For every index for which
+   * this {@code BitSet} contains a bit in the set state, the decimal
+   * representation of that index is included in the result. Such indices are
+   * listed in order from lowest to highest, separated by ",&nbsp;" (a comma and
+   * a space) and surrounded by braces, resulting in the usual mathematical
+   * notation for a set of integers.
+   * 
+   * <p>
+   * Example:
+   * 
+   * <pre>
+   * BitSet drPepper = new BitSet();
+   * </pre>
+   * 
+   * Now {@code drPepper.toString()} returns "{}".
+   * <p>
+   * 
+   * <pre>
+   * drPepper.set(2);
+   * </pre>
+   * 
+   * Now {@code drPepper.toString()} returns "{2}".
+   * <p>
+   * 
+   * <pre>
+   * drPepper.set(4);
+   * drPepper.set(10);
+   * </pre>
+   * 
+   * Now {@code drPepper.toString()} returns "{2, 4, 10}".
+   * 
+   * @return a string representation of this bit set
+   */
+  @Override
+  public String toString() {
+    return escape(this, '(', ')');
+  }
+  
+  private final static int[] emptyBitmap = new int[0];
+
+  /**
+   * fast copy
+   * 
+   * @param bitsetToCopy
+   * @return bs
+   */
+  public static BS copy(BS bitsetToCopy) {
+    BS bs;
+    /**
+     * Clazz.clone will copy wordsInUse and sizeIsSticky, 
+     * but just a pointer to the words array.
+     * 
+     * @j2sNative
+     * 
+     *            bs = Clazz.clone(bitsetToCopy);
+     * 
+     */
+    {
+      bs = new BS();
+    }
+    int wordCount = bitsetToCopy.wordsInUse;
+    if (wordCount == 0) {
+      bs.words = emptyBitmap;
+    } else {
+      
+      /**
+       * Clazz.clone will copy wordsInUse and sizeIsSticky, 
+       * but just a pointer to the words array.
+       * 
+       * @j2sNative
+       * 
+       *   bs.words = Clazz.array(-1, bitsetToCopy.words, 0, bs.wordsInUse = wordCount);
+       * 
+       */
+      {
+        bs.words = new int[bs.wordsInUse = wordCount];
+        System.arraycopy(bitsetToCopy.words, 0, bs.words, 0, wordCount);
+      }
+
+    }
+    return bs;
+  }
+
+  /**
+   * 
+   * @param max
+   * @return n bits below max
+   */
+  public int cardinalityN(int max) {
+    int n = cardinality();
+    for (int i = length(); --i >= max;)
+      if (get(i))
+        n--;
+    return n;
+  }
+
+  @Override
+  public String toJSON() {
+
+    int numBits = (wordsInUse > 128 ? cardinality() : wordsInUse
+        * BITS_PER_WORD);
+    SB b = SB.newN(6 * numBits + 2);
+    b.appendC('[');
+
+    int i = nextSetBit(0);
+    if (i != -1) {
+      b.appendI(i);
+      for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) {
+        int endOfRun = nextClearBit(i);
+        do {
+          b.append(", ").appendI(i);
+        } while (++i < endOfRun);
+      }
+    }
+
+    b.appendC(']');
+    return b.toString();
+  }
+
+  public static String escape(BS bs, char chOpen, char chClose) {
+    if (bs == null)
+      return chOpen + "{}" + chClose;
+    SB s = new SB();
+    s.append(chOpen + "{");
+    int imax = bs.length();
+    int iLast = -1;
+    int iFirst = -2;
+    int i = -1;
+    while (++i <= imax) {
+      boolean isSet = bs.get(i);
+      if (i == imax || iLast >= 0 && !isSet) {
+        if (iLast >= 0 && iFirst != iLast)
+          s.append((iFirst == iLast - 1 ? " " : ":") + iLast);
+        if (i == imax)
+          break;
+        iLast = -1;
+      }
+      if (bs.get(i)) {
+        if (iLast < 0) {
+          s.append((iFirst == -2 ? "" : " ") + i);
+          iFirst = i;
+        }
+        iLast = i;
+      }
+    }
+    s.append("}").appendC(chClose);
+    return s.toString();
+  }
+
+  public static BS unescape(String str) {
+    char ch;
+    int len;
+    if (str == null || (len = (str = str.trim()).length()) < 4
+        || str.equalsIgnoreCase("({null})") 
+        || (ch = str.charAt(0)) != '(' && ch != '[' 
+        || str.charAt(len - 1) != (ch == '(' ? ')' : ']')
+        || str.charAt(1) != '{' || str.indexOf('}') != len - 2)
+      return null;
+    len -= 2;
+    for (int i = len; --i >= 2;)
+      if (((ch = str.charAt(i)) < 48 || ch > 57) && ch != ' ' && ch != '\t'
+          && ch != ':')
+        return null;
+    int lastN = len;
+    while (48 <= (ch = str.charAt(--lastN)) && ch <= 57) {
+      // loop
+    }
+    if (++lastN == len)
+      lastN = 0;
+    else
+      try {
+        lastN = Integer.parseInt(str.substring(lastN, len));
+      } catch (NumberFormatException e) {
+        return null;
+      }
+    BS bs = BS.newN(lastN);
+    lastN = -1;
+    int iPrev = -1;
+    int iThis = -2;
+    for (int i = 2; i <= len; i++) {
+      switch (ch = str.charAt(i)) {
+      case '\t':
+      case ' ':
+      case '}':
+        if (iThis < 0)
+          break;
+        if (iThis < lastN)
+          return null;
+        lastN = iThis;
+        if (iPrev < 0)
+          iPrev = iThis;
+        bs.setBits(iPrev, iThis + 1);
+        iPrev = -1;
+        iThis = -2;
+        break;
+      case ':':
+        iPrev = lastN = iThis;
+        iThis = -2;
+        break;
+      default:
+        if (48 <= ch && ch <= 57) {
+          if (iThis < 0)
+            iThis = 0;
+          iThis = (iThis * 10) + (ch - 48);
+        }
+      }
+    }
+    return (iPrev >= 0 ? null : bs);
+  }
+
+}
diff --git a/src2/javajs/util/Base64.java b/src2/javajs/util/Base64.java
new file mode 100644 (file)
index 0000000..a7ac3a9
--- /dev/null
@@ -0,0 +1,120 @@
+// Version 1.0a
+// Copyright (C) 1998, James R. Weeks and BioElectroMech.
+// Visit BioElectroMech at www.obrador.com.  Email James@obrador.com.
+
+// See license.txt for details about the allowed used of this software.
+// This software is based in part on the work of the Independent JPEG Group.
+// See IJGreadme.txt for details about the Independent JPEG Group's license.
+
+// This encoder is inspired by the Java Jpeg encoder by Florian Raemy,
+// studwww.eurecom.fr/~raemy.
+// It borrows a great deal of code and structure from the Independent
+// Jpeg Group's Jpeg 6a library, Copyright Thomas G. Lane.
+// See license.txt for details.
+
+package javajs.util;
+
+
+public class Base64 {
+
+  //                              0         1         2         3         4         5         6
+  //                              0123456789012345678901234567890123456789012345678901234567890123
+  private static String base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+  //                              41----------------------5A
+  //                                                        61----------------------7A
+  //                                                                                  30------39    
+  //                                                                                            2B  
+  //                                                                                             2F
+  //                                                 alternative "URL-SAFE"     2D and 5F       -_
+  
+  private static int[] decode64 = new int[] {
+    0,0,0,0,     0,0,0,0,     0,0,0,0,     0,0,0,0,      //0x00-0x0F
+    0,0,0,0,     0,0,0,0,     0,0,0,0,     0,0,0,0,      //0x10-0x1F
+    0,0,0,0,     0,0,0,0,     0,0,0,62,    0,62,0,63,    //0x20-0x2F
+    52,53,54,55, 56,57,58,59, 60,61,0,0,   0,0,0,0,      //0x30-0x3F
+    0,0,1,2,     3,4,5,6,     7,8,9,10,    11,12,13,14,  //0x40-0x4F
+    15,16,17,18, 19,20,21,22, 23,24,25,0,  0,0,0,63,     //0x50-0x5F
+    0,26,27,28,  29,30,31,32, 33,34,35,36, 37,38,39,40,  //0x60-0x6F
+    41,42,43,44, 45,46,47,48, 49,50,51,0,  0,0,0,0,      //0x70-0x7F
+  };
+    
+//  public static void write(byte[] bytes, OutputChannel out) {
+//    SB sb = getBase64(bytes);
+//    int len = sb.length();
+//    byte[] b = new byte[1];
+//    for (int i = 0; i < len; i++) {
+//      b[0] = (byte) sb.charAt(i);
+//      out.write(b, 0, 1);
+//    }
+//  }
+
+  public static byte[] getBytes64(byte[] bytes) {
+    return getBase64(bytes).toBytes(0, -1);
+  }
+
+  /**
+   * 
+   * @param bytes
+   * @return BASE64-encoded string, without ";base64,"
+   */
+  public static SB getBase64(byte[] bytes) {
+    long nBytes = bytes.length;
+    SB sout = new SB();
+    if (nBytes == 0)
+      return sout;
+    for (int i = 0, nPad = 0; i < nBytes && nPad == 0;) {
+      if (i % 75 == 0 && i != 0)
+        sout.append("\r\n");
+      nPad = (i + 2 == nBytes ? 1 : i + 1 == nBytes ? 2 : 0);
+      int outbytes = ((bytes[i++] << 16) & 0xFF0000)
+          | ((nPad == 2 ? 0 : bytes[i++] << 8) & 0x00FF00)
+          | ((nPad >= 1 ? 0 : (int) bytes[i++]) & 0x0000FF);
+      //System.out.println(Integer.toHexString(outbytes));
+      sout.appendC(base64.charAt((outbytes >> 18) & 0x3F));
+      sout.appendC(base64.charAt((outbytes >> 12) & 0x3F));
+      sout.appendC(nPad == 2 ? '=' : base64.charAt((outbytes >> 6) & 0x3F));
+      sout.appendC(nPad >= 1 ? '=' : base64.charAt(outbytes & 0x3F));
+    }
+    return sout;
+  }
+
+  //Note: Just a simple decoder here. Nothing fancy at all
+  //      Because of the 0s in decode64, this is not a VERIFIER
+  //      Rather, it may decode even bad Base64-encoded data
+  //
+  // Bob Hanson 4/2007
+  
+  public static byte[] decodeBase64(String strBase64) {
+    int nBytes = 0;
+    int ch;
+    int pt0 = strBase64.indexOf(";base64,") + 1;
+    if (pt0 > 0)
+      pt0 += 7;
+    char[] chars64 = strBase64.toCharArray();
+    int len64 = chars64.length;
+    if (len64 == 0)
+      return new byte[0];
+    for (int i = len64; --i >= pt0;)
+      nBytes += ((ch = chars64[i] & 0x7F) == 'A' || decode64[ch] > 0 ? 3 : 0);
+    nBytes = nBytes >> 2;
+    byte[] bytes = new byte[nBytes];
+    int offset = 18;
+    for (int i = pt0, pt = 0, b = 0; i < len64; i++) {
+      if (decode64[ch = chars64[i] & 0x7F] > 0 || ch == 'A' || ch == '=') {
+        b |= decode64[ch] << offset;
+        //System.out.println(chars64[i] + " " + decode64[ch] + " " + offset + " " + Integer.toHexString(b));
+        offset -= 6;
+        if (offset < 0) {
+          bytes[pt++] = (byte) ((b & 0xFF0000) >> 16);
+          if (pt < nBytes)
+            bytes[pt++] = (byte) ((b & 0xFF00) >> 8);
+          if (pt < nBytes)
+            bytes[pt++] = (byte) (b & 0xFF);
+          offset = 18;
+          b =  0;
+        }
+      }
+    }
+    return bytes;
+  }    
+}
\ No newline at end of file
diff --git a/src2/javajs/util/BinaryDocument.java b/src2/javajs/util/BinaryDocument.java
new file mode 100644 (file)
index 0000000..73ec57b
--- /dev/null
@@ -0,0 +1,356 @@
+/* $RCSfile$
+ * $Date: 2006-03-18 15:59:33 -0600 (Sat, 18 Mar 2006) $
+ * $Revision: 4652 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2003-2005  Miguel, Jmol Development, www.jmol.org
+ *
+ * Contact: hansonr@stolaf.edu
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.util;
+
+
+import java.io.BufferedInputStream;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.util.Map;
+
+import javajs.api.GenericBinaryDocument;
+import javajs.api.GenericOutputChannel;
+
+/* a basic binary file reader (extended by CompoundDocument). 
+ * 
+ * Note that YOU are responsible for determining whether a file
+ * is bigEndian or littleEndian; the default is bigEndian.
+ * 
+ * JavaScript note: readShort() malfunctioned because (short) (xx << 8) 
+ * isn't the same as (int) (xx << 8); same problem in java.io.DataStream
+ * 
+ * 
+ */
+
+public class BinaryDocument extends BC implements GenericBinaryDocument {
+
+  public BinaryDocument() {  
+  }
+
+
+  // called by reflection
+  
+  protected DataInputStream stream;
+  protected boolean isRandom = false;
+  protected boolean isBigEndian = true;
+  protected BufferedInputStream bis;
+  protected long nBytes;  
+  protected GenericOutputChannel out;
+  
+
+  @Override
+  public void close() {
+    if (stream != null)
+      try {
+        stream.close();
+      } catch (IOException e) {
+        // ignore
+      }
+    if (out != null)
+       out.closeChannel();
+  }
+  
+  @Override
+  public BinaryDocument setStream(BufferedInputStream bis, boolean isBigEndian) {
+    this.bis = bis;
+    if (bis != null) {
+      stream = new DataInputStream(bis);
+    }
+    this.isBigEndian = isBigEndian;
+    return this;
+  }
+
+  @Override
+  public BufferedInputStream getInputStream() {
+    return bis;
+  }
+  
+  @Override
+  public void setStreamData(DataInputStream stream, boolean isBigEndian) {
+    if (stream != null)
+      this.stream = stream;
+    this.isBigEndian = isBigEndian;
+  }
+  
+  @Override
+  public void setOutputChannel(GenericOutputChannel out) {
+      this.out = out;
+  }
+
+  public void setRandom(boolean TF) {
+    isRandom = TF;
+    //CANNOT be random for web 
+  }
+  
+  @Override
+  public byte readByte() throws IOException {
+    nBytes++;
+    return ioReadByte();
+  }
+
+  @Override
+  public int readUInt8() throws IOException {
+    nBytes++;
+    int b = stream.readUnsignedByte();
+    if (out != null)
+      out.writeByteAsInt(b);
+    return b;
+  }
+
+  private byte ioReadByte() throws IOException {
+    byte b = stream.readByte();
+    if (out != null)
+      out.writeByteAsInt(b);
+    return b;
+  }
+
+  @Override
+  public byte[] readBytes(int n) throws IOException {
+    byte[] b = new byte[n];
+    readByteArray(b, 0, n);
+    return b;
+  }
+
+  @Override
+  public int readByteArray(byte[] b, int off, int len) throws IOException {
+    int n = ioRead(b, off, len);
+    nBytes += n;
+    return n;
+  }
+
+  private int ioRead(byte[] b, int off, int len) throws IOException {
+    int m = 0;
+    while (len > 0) {
+      int n = stream.read(b, off, len);
+      m += n;
+      if (n > 0 && out != null)
+        out.write(b, off, n);
+      if (n >= len)
+        break;
+      off += n;
+      len -= n;
+    }
+    return m;
+  }
+
+  @Override
+  public String readString(int nChar) throws IOException {
+    byte[] temp = new byte[nChar];
+    int n = readByteArray(temp, 0, nChar);
+    return new String(temp, 0, n, "UTF-8");
+  }
+  
+  @Override
+  public short readShort() throws IOException {
+    nBytes += 2;
+    short n = (isBigEndian ? ioReadShort()
+        : (short) ((ioReadByte() & 0xff) 
+                 | (ioReadByte() & 0xff) << 8));
+    /**
+     * @j2sNative
+     *
+     * return (n > 0x7FFF ? n - 0x10000 : n);
+     */
+    {
+      return n;
+    }
+  }
+
+  private short ioReadShort() throws IOException {
+    short b = stream.readShort();
+    if (out != null)
+      out.writeShort(b);
+    return b;
+  }
+
+
+  @Override
+  public int readIntLE() throws IOException {
+    nBytes += 4;
+    return readLEInt();
+  }
+  
+  @Override
+  public int readInt() throws IOException {
+    nBytes += 4;
+    return (isBigEndian ? ioReadInt() : readLEInt());
+  }
+  
+  private int ioReadInt() throws IOException {
+    int i = stream.readInt();
+    if (out != null)
+      out.writeInt(i);
+    return i;
+  }
+
+  @Override
+  public int swapBytesI(int n) {
+    return (((n >> 24) & 0xff)
+        | ((n >> 16) & 0xff) << 8
+        | ((n >> 8) & 0xff) << 16 
+        | (n & 0xff) << 24);
+  }
+
+  @Override
+  public short swapBytesS(short n) {
+    return (short) ((((n >> 8) & 0xff)
+        | (n & 0xff) << 8));
+  }
+
+  
+  @Override
+  public int readUnsignedShort() throws IOException {
+    nBytes += 2;
+    int a = (ioReadByte() & 0xff);
+    int b = (ioReadByte() & 0xff);
+    return (isBigEndian ? (a << 8) + b : (b << 8) + a);
+  }
+  
+  @Override
+  public long readLong() throws IOException {
+    nBytes += 8;
+    return (isBigEndian ? ioReadLong()
+       : ((((long) ioReadByte()) & 0xff)
+        | (((long) ioReadByte()) & 0xff) << 8
+        | (((long) ioReadByte()) & 0xff) << 16
+        | (((long) ioReadByte()) & 0xff) << 24
+        | (((long) ioReadByte()) & 0xff) << 32
+        | (((long) ioReadByte()) & 0xff) << 40
+        | (((long) ioReadByte()) & 0xff) << 48 
+        | (((long) ioReadByte()) & 0xff) << 54));
+  }
+
+  private long ioReadLong() throws IOException {
+    long b = stream.readLong();
+    if (out != null)
+      out.writeLong(b);
+    return b;
+  }
+
+  private int readLEInt() throws IOException {
+    ioRead(t8, 0, 4);
+    return bytesToInt(t8, 0, false);
+  }
+
+  byte[] t8 = new byte[8];
+  
+  @Override
+  public float readFloat() throws Exception {
+    return intToFloat(readInt());
+  }
+
+  @SuppressWarnings("unused")
+  @Override
+  public double readDouble() throws IOException {
+    /**
+     * 
+     * reading the float equivalent here in JavaScript
+     * 
+     * @j2sNative
+     * 
+     * 
+     */
+    {
+      nBytes += 8;
+      if (true)
+        return (isBigEndian ? ioReadDouble()
+            : Double.longBitsToDouble(readLELong()));
+    }
+    // this is the JavaScript-only part
+    this.readByteArray(this.t8, 0, 8);
+    return bytesToDoubleToFloat(this.t8, 0, this.isBigEndian);
+  }
+  
+  private double ioReadDouble() throws IOException {
+    double d = stream.readDouble();
+    if (out != null)
+      out.writeLong(Double.doubleToRawLongBits(d));
+    return d;
+  }
+
+  private long readLELong() throws IOException {
+    return ((((long) ioReadByte()) & 0xff)
+          | (((long) ioReadByte()) & 0xff) << 8
+          | (((long) ioReadByte()) & 0xff) << 16 
+          | (((long) ioReadByte()) & 0xff) << 24
+          | (((long) ioReadByte()) & 0xff) << 32
+          | (((long) ioReadByte()) & 0xff) << 40
+          | (((long) ioReadByte()) & 0xff) << 48
+          | (((long) ioReadByte()) & 0xff) << 56);
+  }
+
+  @Override
+  public void seek(long offset) {
+    // slower, but all that is available using the applet
+    try {
+      if (offset == nBytes)
+        return;
+      if (offset < nBytes) {
+        stream.reset();
+        if (out != null && nBytes != 0)
+          out.reset();
+        nBytes = 0;
+      } else {
+        offset -= nBytes;
+      }
+      if (out == null) {
+        stream.skipBytes((int)offset);
+      } else {
+        readByteArray(new byte[(int)offset], 0, (int) offset);
+      }
+      nBytes += offset;
+    } catch (IOException e) {
+      System.out.println(e.toString());
+    }
+  }
+
+  @Override
+  public long getPosition() {
+    return nBytes;
+  }
+
+  @Override
+  public SB getAllDataFiles(String binaryFileList, String firstFile) {
+    return null;
+  }
+
+  @Override
+  public void getAllDataMapped(String replace, String string,
+                               Map<String, String> fileData) {
+  }
+
+
+/*  random access -- application only:
+ * 
+    void seekFile(long offset) {
+    try {
+      file.seek(offset);
+    } catch (IOException e) {
+      System.out.println(e.getMessage());
+    }
+  }
+*/
+}
diff --git a/src2/javajs/util/CU.java b/src2/javajs/util/CU.java
new file mode 100644 (file)
index 0000000..e46287e
--- /dev/null
@@ -0,0 +1,555 @@
+package javajs.util;
+
+import java.util.Hashtable;
+import java.util.Map;
+
+import javajs.api.GenericColor;
+
+/**
+ * ColorUtility 
+ * 
+ */
+
+public class CU {
+
+  public static String toRGBHexString(GenericColor c) {
+    int rgb = c.getRGB();    
+    if (rgb == 0)
+      return "000000";
+    String r  = "00" + Integer.toHexString((rgb >> 16) & 0xFF);
+    r = r.substring(r.length() - 2);
+    String g  = "00" + Integer.toHexString((rgb >> 8) & 0xFF);
+    g = g.substring(g.length() - 2);
+    String b  = "00" + Integer.toHexString(rgb & 0xFF);
+    b = b.substring(b.length() - 2);
+    return r + g + b;
+  }
+
+  public static String toCSSString(GenericColor c) {
+    int opacity = c.getOpacity255();
+    if (opacity == 255)
+      return "#" + toRGBHexString(c);
+    int rgb = c.getRGB();
+    return "rgba(" + ((rgb>>16)&0xFF) + "," + ((rgb>>8)&0xff) + "," + (rgb&0xff) + "," + opacity/255f  + ")"; 
+  }
+  
+  private final static String[] colorNames = {
+    "black",                // 000000
+    "pewhite",              // ffffff
+    "pecyan",               // 00ffff
+    "pepurple",             // d020ff
+    "pegreen",              // 00ff00
+    "peblue",               // 6060ff
+    "peviolet",             // ff80c0
+    "pebrown",              // a42028
+    "pepink",               // ffd8d8
+    "peyellow",             // ffff00
+    "pedarkgreen",          // 00c000
+    "peorange",             // ffb000
+    "pelightblue",          // b0b0ff
+    "pedarkcyan",           // 00a0a0
+    "pedarkgray",           // 606060
+  
+    "aliceblue",            // F0F8FF
+    "antiquewhite",         // FAEBD7
+    "aqua",                 // 00FFFF
+    "aquamarine",           // 7FFFD4
+    "azure",                // F0FFFF
+    "beige",                // F5F5DC
+    "bisque",               // FFE4C4
+    "blanchedalmond",       // FFEBCD
+    "blue",                 // 0000FF
+    "blueviolet",           // 8A2BE2
+    "brown",                // A52A2A
+    "burlywood",            // DEB887
+    "cadetblue",            // 5F9EA0
+    "chartreuse",           // 7FFF00
+    "chocolate",            // D2691E
+    "coral",                // FF7F50
+    "cornflowerblue",       // 6495ED
+    "cornsilk",             // FFF8DC
+    "crimson",              // DC143C
+    "cyan",                 // 00FFFF
+    "darkblue",             // 00008B
+    "darkcyan",             // 008B8B
+    "darkgoldenrod",        // B8860B
+    "darkgray",             // A9A9A9
+    "darkgreen",            // 006400
+    "darkkhaki",            // BDB76B
+    "darkmagenta",          // 8B008B
+    "darkolivegreen",       // 556B2F
+    "darkorange",           // FF8C00
+    "darkorchid",           // 9932CC
+    "darkred",              // 8B0000
+    "darksalmon",           // E9967A
+    "darkseagreen",         // 8FBC8F
+    "darkslateblue",        // 483D8B
+    "darkslategray",        // 2F4F4F
+    "darkturquoise",        // 00CED1
+    "darkviolet",           // 9400D3
+    "deeppink",             // FF1493
+    "deepskyblue",          // 00BFFF
+    "dimgray",              // 696969
+    "dodgerblue",           // 1E90FF
+    "firebrick",            // B22222
+    "floralwhite",          // FFFAF0 16775920
+    "forestgreen",          // 228B22
+    "fuchsia",              // FF00FF
+    "gainsboro",            // DCDCDC
+    "ghostwhite",           // F8F8FF
+    "gold",                 // FFD700
+    "goldenrod",            // DAA520
+    "gray",                 // 808080
+    "green",                // 008000
+    "greenyellow",          // ADFF2F
+    "honeydew",             // F0FFF0
+    "hotpink",              // FF69B4
+    "indianred",            // CD5C5C
+    "indigo",               // 4B0082
+    "ivory",                // FFFFF0
+    "khaki",                // F0E68C
+    "lavender",             // E6E6FA
+    "lavenderblush",        // FFF0F5
+    "lawngreen",            // 7CFC00
+    "lemonchiffon",         // FFFACD
+    "lightblue",            // ADD8E6
+    "lightcoral",           // F08080
+    "lightcyan",            // E0FFFF
+    "lightgoldenrodyellow", // FAFAD2
+    "lightgreen",           // 90EE90
+    "lightgrey",            // D3D3D3
+    "lightgray",            // D3D3D3
+    "lightpink",            // FFB6C1
+    "lightsalmon",          // FFA07A
+    "lightseagreen",        // 20B2AA
+    "lightskyblue",         // 87CEFA
+    "lightslategray",       // 778899
+    "lightsteelblue",       // B0C4DE
+    "lightyellow",          // FFFFE0
+    "lime",                 // 00FF00
+    "limegreen",            // 32CD32
+    "linen",                // FAF0E6
+    "magenta",              // FF00FF
+    "maroon",               // 800000
+    "mediumaquamarine",     // 66CDAA
+    "mediumblue",           // 0000CD
+    "mediumorchid",         // BA55D3
+    "mediumpurple",         // 9370DB
+    "mediumseagreen",       // 3CB371
+    "mediumslateblue",      // 7B68EE
+    "mediumspringgreen",    // 00FA9A
+    "mediumturquoise",      // 48D1CC
+    "mediumvioletred",      // C71585
+    "midnightblue",         // 191970
+    "mintcream",            // F5FFFA
+    "mistyrose",            // FFE4E1
+    "moccasin",             // FFE4B5
+    "navajowhite",          // FFDEAD
+    "navy",                 // 000080
+    "oldlace",              // FDF5E6
+    "olive",                // 808000
+    "olivedrab",            // 6B8E23
+    "orange",               // FFA500
+    "orangered",            // FF4500
+    "orchid",               // DA70D6
+    "palegoldenrod",        // EEE8AA
+    "palegreen",            // 98FB98
+    "paleturquoise",        // AFEEEE
+    "palevioletred",        // DB7093
+    "papayawhip",           // FFEFD5
+    "peachpuff",            // FFDAB9
+    "peru",                 // CD853F
+    "pink",                 // FFC0CB
+    "plum",                 // DDA0DD
+    "powderblue",           // B0E0E6
+    "purple",               // 800080
+    "red",                  // FF0000
+    "rosybrown",            // BC8F8F
+    "royalblue",            // 4169E1
+    "saddlebrown",          // 8B4513
+    "salmon",               // FA8072
+    "sandybrown",           // F4A460
+    "seagreen",             // 2E8B57
+    "seashell",             // FFF5EE
+    "sienna",               // A0522D
+    "silver",               // C0C0C0
+    "skyblue",              // 87CEEB
+    "slateblue",            // 6A5ACD
+    "slategray",            // 708090
+    "snow",                 // FFFAFA 16775930
+    "springgreen",          // 00FF7F
+    "steelblue",            // 4682B4
+    "tan",                  // D2B48C
+    "teal",                 // 008080
+    "thistle",              // D8BFD8
+    "tomato",               // FF6347
+    "turquoise",            // 40E0D0
+    "violet",               // EE82EE
+    "wheat",                // F5DEB3
+    "white",                // FFFFFF 16777215
+    "whitesmoke",           // F5F5F5
+    "yellow",               // FFFF00
+    "yellowgreen",          // 9ACD32
+    // plus a few rasmol names/values
+    "bluetint",             // AFD7FF
+    "greenblue",            // 2E8B57
+    "greentint",            // 98FFB3
+    "grey",                 // 808080
+    "gray",                 
+    "pinktint",             // FFABBB
+    "redorange",            // FF4500
+    "yellowtint",           // F6F675
+  };
+  
+  private final static int[] colorArgbs = {
+  //#FFFFC3 hover
+    0xFF000000, // black
+    // plus the PE chain colors
+    0xFFffffff, // pewhite
+    0xFF00ffff, // pecyan
+    0xFFd020ff, // pepurple
+    0xFF00ff00, // pegreen
+    0xFF6060ff, // peblue
+    0xFFff80c0, // peviolet
+    0xFFa42028, // pebrown
+    0xFFffd8d8, // pepink
+    0xFFffff00, // peyellow
+    0xFF00c000, // pedarkgreen
+    0xFFffb000, // peorange
+    0xFFb0b0ff, // pelightblue
+    0xFF00a0a0, // pedarkcyan
+    0xFF606060, // pedarkgray
+    // standard JavaScript
+    0xFFF0F8FF, // aliceblue
+    0xFFFAEBD7, // antiquewhite
+    0xFF00FFFF, // aqua
+    0xFF7FFFD4, // aquamarine
+    0xFFF0FFFF, // azure
+    0xFFF5F5DC, // beige
+    0xFFFFE4C4, // bisque
+    0xFFFFEBCD, // blanchedalmond
+    0xFF0000FF, // blue
+    0xFF8A2BE2, // blueviolet
+    0xFFA52A2A, // brown
+    0xFFDEB887, // burlywood
+    0xFF5F9EA0, // cadetblue
+    0xFF7FFF00, // chartreuse
+    0xFFD2691E, // chocolate
+    0xFFFF7F50, // coral
+    0xFF6495ED, // cornflowerblue
+    0xFFFFF8DC, // cornsilk
+    0xFFDC143C, // crimson
+    0xFF00FFFF, // cyan
+    0xFF00008B, // darkblue
+    0xFF008B8B, // darkcyan
+    0xFFB8860B, // darkgoldenrod
+    0xFFA9A9A9, // darkgray
+    0xFF006400, // darkgreen
+  
+    0xFFBDB76B, // darkkhaki
+    0xFF8B008B, // darkmagenta
+    0xFF556B2F, // darkolivegreen
+    0xFFFF8C00, // darkorange
+    0xFF9932CC, // darkorchid
+    0xFF8B0000, // darkred
+    0xFFE9967A, // darksalmon
+    0xFF8FBC8F, // darkseagreen
+    0xFF483D8B, // darkslateblue
+    0xFF2F4F4F, // darkslategray
+    0xFF00CED1, // darkturquoise
+    0xFF9400D3, // darkviolet
+    0xFFFF1493, // deeppink
+    0xFF00BFFF, // deepskyblue
+    0xFF696969, // dimgray
+    0xFF1E90FF, // dodgerblue
+    0xFFB22222, // firebrick
+    0xFFFFFAF0, // floralwhite
+    0xFF228B22, // forestgreen
+    0xFFFF00FF, // fuchsia
+    0xFFDCDCDC, // gainsboro
+    0xFFF8F8FF, // ghostwhite
+    0xFFFFD700, // gold
+    0xFFDAA520, // goldenrod
+    0xFF808080, // gray
+    0xFF008000, // green
+    0xFFADFF2F, // greenyellow
+    0xFFF0FFF0, // honeydew
+    0xFFFF69B4, // hotpink
+    0xFFCD5C5C, // indianred
+    0xFF4B0082, // indigo
+    0xFFFFFFF0, // ivory
+    0xFFF0E68C, // khaki
+    0xFFE6E6FA, // lavender
+    0xFFFFF0F5, // lavenderblush
+    0xFF7CFC00, // lawngreen
+    0xFFFFFACD, // lemonchiffon
+    0xFFADD8E6, // lightblue
+    0xFFF08080, // lightcoral
+    0xFFE0FFFF, // lightcyan
+    0xFFFAFAD2, // lightgoldenrodyellow
+    0xFF90EE90, // lightgreen
+    0xFFD3D3D3, // lightgrey
+    0xFFD3D3D3, // lightgray
+    0xFFFFB6C1, // lightpink
+    0xFFFFA07A, // lightsalmon
+    0xFF20B2AA, // lightseagreen
+    0xFF87CEFA, // lightskyblue
+    0xFF778899, // lightslategray
+    0xFFB0C4DE, // lightsteelblue
+    0xFFFFFFE0, // lightyellow
+    0xFF00FF00, // lime
+    0xFF32CD32, // limegreen
+    0xFFFAF0E6, // linen
+    0xFFFF00FF, // magenta
+    0xFF800000, // maroon
+    0xFF66CDAA, // mediumaquamarine
+    0xFF0000CD, // mediumblue
+    0xFFBA55D3, // mediumorchid
+    0xFF9370DB, // mediumpurple
+    0xFF3CB371, // mediumseagreen
+    0xFF7B68EE, // mediumslateblue
+    0xFF00FA9A, // mediumspringgreen
+    0xFF48D1CC, // mediumturquoise
+    0xFFC71585, // mediumvioletred
+    0xFF191970, // midnightblue
+    0xFFF5FFFA, // mintcream
+    0xFFFFE4E1, // mistyrose
+    0xFFFFE4B5, // moccasin
+    0xFFFFDEAD, // navajowhite
+    0xFF000080, // navy
+    0xFFFDF5E6, // oldlace
+    0xFF808000, // olive
+    0xFF6B8E23, // olivedrab
+    0xFFFFA500, // orange
+    0xFFFF4500, // orangered
+    0xFFDA70D6, // orchid
+    0xFFEEE8AA, // palegoldenrod
+    0xFF98FB98, // palegreen
+    0xFFAFEEEE, // paleturquoise
+    0xFFDB7093, // palevioletred
+    0xFFFFEFD5, // papayawhip
+    0xFFFFDAB9, // peachpuff
+    0xFFCD853F, // peru
+    0xFFFFC0CB, // pink
+    0xFFDDA0DD, // plum
+    0xFFB0E0E6, // powderblue
+    0xFF800080, // purple
+    0xFFFF0000, // red
+    0xFFBC8F8F, // rosybrown
+    0xFF4169E1, // royalblue
+    0xFF8B4513, // saddlebrown
+    0xFFFA8072, // salmon
+    0xFFF4A460, // sandybrown
+    0xFF2E8B57, // seagreen
+    0xFFFFF5EE, // seashell
+    0xFFA0522D, // sienna
+    0xFFC0C0C0, // silver
+    0xFF87CEEB, // skyblue
+    0xFF6A5ACD, // slateblue
+    0xFF708090, // slategray
+    0xFFFFFAFA, // snow
+    0xFF00FF7F, // springgreen
+    0xFF4682B4, // steelblue
+    0xFFD2B48C, // tan
+    0xFF008080, // teal
+    0xFFD8BFD8, // thistle
+    0xFFFF6347, // tomato
+    0xFF40E0D0, // turquoise
+    0xFFEE82EE, // violet
+    0xFFF5DEB3, // wheat
+    0xFFFFFFFF, // white
+    0xFFF5F5F5, // whitesmoke
+    0xFFFFFF00, // yellow
+    0xFF9ACD32, // yellowgreen
+    // plus a few rasmol names/values
+    0xFFAFD7FF, // bluetint
+    0xFF2E8B57, // greenblue
+    0xFF98FFB3, // greentint
+    0xFF808080, // grey
+    0xFF808080, // gray
+    0xFFFFABBB, // pinktint
+    0xFFFF4500, // redorange
+    0xFFF6F675, // yellowtint
+  };
+
+  private static final Map<String, Integer> mapJavaScriptColors = new Hashtable<String, Integer>();
+
+  static {
+    for (int i = colorNames.length; --i >= 0; )
+      mapJavaScriptColors.put(colorNames[i], Integer.valueOf(colorArgbs[i]));
+  }
+
+  /**
+   * accepts [xRRGGBB] or [0xRRGGBB] or [0xFFRRGGBB] or #RRGGBB or
+   * [red,green,blue] or a valid JavaScript color
+   * 
+   * @param strColor
+   * @return 0 if invalid or integer color
+   */
+  public static int getArgbFromString(String strColor) {
+    int len = 0;
+    if (strColor == null || (len = strColor.length()) == 0)
+      return 0;
+    strColor = strColor.toLowerCase();
+    if (strColor.charAt(0) == '[' && strColor.charAt(len - 1) == ']') {
+      String check;
+      if (strColor.indexOf(",") >= 0) {
+        String[] tokens = PT.split(strColor.substring(1, strColor
+            .length() - 1), ",");
+        if (tokens.length != 3)
+          return 0;
+        float red = PT.parseFloat(tokens[0]);
+        float grn = PT.parseFloat(tokens[1]);
+        float blu = PT.parseFloat(tokens[2]);
+        return colorTriadToFFRGB(red, grn, blu);
+      }
+      switch (len) {
+      case 9:
+        check = "x";
+        break;
+      case 10:
+        check = "0x";
+        break;
+      default:
+        return 0;
+      }
+      if (strColor.indexOf(check) != 1)
+        return 0;
+      strColor = "#" + strColor.substring(len - 7, len - 1);
+      len = 7;
+    }
+    if (len == 7 && strColor.charAt(0) == '#') {
+      try {
+        return PT.parseIntRadix(strColor.substring(1, 7), 16) | 0xFF000000;
+      } catch (Exception e) {
+        return 0;
+      }
+    }
+    Integer boxedArgb = mapJavaScriptColors.get(strColor);
+    return (boxedArgb == null ? 0 : boxedArgb.intValue());
+  }
+
+  public static int colorTriadToFFRGB(float x, float y, float z) {
+    if (x <= 1 && y <= 1 && z <= 1) {
+      if (x > 0)
+        x = x * 256 - 1;
+      if (y > 0)
+        y = y * 256 - 1;
+      if (z > 0)
+        z = z * 256 - 1;
+    }
+    return rgb((int) x, (int) y, (int) z);
+  }
+
+  public static int rgb(int red, int grn, int blu) {
+    return 0xFF000000 | (red << 16) | (grn << 8) | blu;
+  }
+
+  public final static P3 colorPtFromString(String colorName) {
+    return colorPtFromInt(getArgbFromString(colorName), null);
+  }
+
+  public final static P3 colorPtFromInt(int color, P3 pt) {
+    if (pt == null)
+      pt = new P3();
+    pt.set((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF);
+    return pt;
+  }
+
+  public static int colorPtToFFRGB(T3 pt) {
+    return colorTriadToFFRGB(pt.x, pt.y, pt.z);
+  }
+
+  public static void toRGB3f(int c, float[] f) {
+    f[0] = ((c >> 16) & 0xFF) / 255f; // red
+    f[1] = ((c >> 8) & 0xFF) / 255f;
+    f[2] = (c & 0xFF) / 255f;
+  }
+
+  /**
+   * Return a greyscale rgb value 0-FF using NTSC color lightness algorithm
+   *<p>
+   * the alpha component is set to 0xFF. If you want a value in the
+   * range 0-255 then & the result with 0xFF;
+   *
+   * @param rgb the rgb value
+   * @return a grayscale value in the range 0 - 255 decimal
+   */
+  public static int toFFGGGfromRGB(int rgb) {
+    int grey = (((2989 * ((rgb >> 16) & 0xFF)) +
+                (5870 * ((rgb >> 8) & 0xFF)) +
+                (1140 * (rgb & 0xFF)) + 5000) / 10000) & 0xFFFFFF;
+    return rgb(grey, grey, grey);
+  }
+  
+  
+  /**
+   * Convert RGB values to HSL (hue/saturation/lightness)
+   * 
+   * @param rgb
+   *        range 255 255 255
+   * @param doRound
+   *        set to false when just using this for 
+   *        for RGB -- HSL -- HSL' -- RGB' conversion
+   * 
+   * @return the HSL as P3 range 360 100 100
+   * @author hansonr
+   */
+
+  public static P3 rgbToHSL(P3 rgb, boolean doRound) {
+    // adapted from http://tips4java.wordpress.com/2009/07/05/hsl-color/
+    // see http://en.wikipedia.org/wiki/HSL_color_space
+    float r = rgb.x / 255;
+    float g = rgb.y / 255;
+    float b = rgb.z / 255;
+    float min = Math.min(r, Math.min(g, b));
+    float max = Math.max(r, Math.max(g, b));
+
+    //  lightness is just p * 50
+
+    float p = (max + min);
+    float q = (max - min);
+
+    float h = (60 * ((q == 0 ? 0 : max == r ? ((g - b) / q + 6)
+        : max == g ? (b - r) / q + 2 : (r - g) / q + 4))) % 360;
+
+    float s = q / (q == 0 ? 1 : p <= 1 ? p : 2 - p);
+
+    // we round to tenths for HSL so that we can  return enough
+    // precision to get back 1-255 in RGB
+    return (doRound ? P3.new3(Math.round(h*10)/10f, Math.round(s * 1000)/10f,
+        Math.round(p * 500)/10f) : P3.new3(h, s * 100, p * 50));
+  }
+
+  /**
+   * Convert HSL (hue/saturation/luninance) values to RGB
+   *
+   * @param hsl in the range 360, 100, 100
+   * @return the RGB as P3 range 0 to 255
+   * @author hansonr
+   */
+  public static P3 hslToRGB(P3 hsl) {
+    // adapted from http://tips4java.wordpress.com/2009/07/05/hsl-color/
+    // see http://en.wikipedia.org/wiki/HSL_color_space
+    
+    // highly condensed
+    
+    float h = Math.max(0,  Math.min(360, hsl.x)) / 60;
+    float s = Math.max(0,  Math.min(100, hsl.y)) / 100;
+    float l = Math.max(0,  Math.min(100, hsl.z)) / 100;
+
+    float p = l - (l < 0.5 ? l : 1 - l) * s;    
+    float q = 2 * (l - p); 
+        
+    float r = toRGB(p, q, h + 2);
+    float g = toRGB(p, q, h);
+    float b = toRGB(p, q, h - 2);
+    return P3.new3(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
+  }
+
+  private static float toRGB(float p, float q, float h) {
+    return ((h = (h + (h < 0 ? 6 : h > 6 ? -6 : 0))) < 1 ? p + q * h
+        : h < 3 ? p + q : h < 4 ? p + q * (4 - h) : p);
+  }
+
+}
diff --git a/src2/javajs/util/CifDataParser.java b/src2/javajs/util/CifDataParser.java
new file mode 100644 (file)
index 0000000..51e969c
--- /dev/null
@@ -0,0 +1,905 @@
+package javajs.util;
+
+import java.io.BufferedReader;
+
+import java.util.Hashtable;
+
+import java.util.Map;
+
+import javajs.api.GenericCifDataParser;
+import javajs.api.GenericLineReader;
+
+
+// BH 11/21/16 -- adds support for array grouping [...] - used in 2016-format magCIF files
+
+/**
+*
+* A CIF 1.0 tokenizer class for dealing with quoted strings in CIF files.
+* 
+* Subclassed by org.jmol.adapters.readers.cif.Cif2DataParser
+* 
+* Greek letters implemented in Jmol 13.3.9 and only for 
+* titles and space groups. All other mark ups ignored.
+* 
+*<p>
+* regarding the treatment of single quotes vs. primes in
+* cif file, PMR wrote:
+*</p>
+*<p>
+*   * There is a formal grammar for CIF
+* (see http://www.iucr.org/iucr-top/cif/index.html)
+* which confirms this. The textual explanation is
+*<p />
+*<p>
+* 14. Matching single or double quote characters (' or ") may
+* be used to bound a string representing a non-simple data value
+* provided the string does not extend over more than one line.
+*<p />
+*<p>
+* 15. Because data values are invariably separated from other
+* tokens in the file by white space, such a quote-delimited
+* character string may contain instances of the character used
+* to delimit the string provided they are not followed by white
+* space. For example, the data item
+*<code>
+*  _example  'a dog's life'
+*</code>
+* is legal; the data value is a dog's life.
+*</p>
+*<p>
+* [PMR - the terminating character(s) are quote+whitespace.
+* That would mean that:
+*<code>
+*  _example 'Jones' life'
+*</code>
+* would be an error
+*</p>
+*<p>
+* The CIF format was developed in that late 1980's under the aegis of the
+* International Union of Crystallography (I am a consultant to the COMCIFs 
+* committee). It was ratified by the Union and there have been several 
+* workshops. mmCIF is an extension of CIF which includes a relational 
+* structure. The formal publications are:
+*</p>
+*<p>
+* Hall, S. R. (1991). "The STAR File: A New Format for Electronic Data 
+* Transfer and Archiving", J. Chem. Inform. Comp. Sci., 31, 326-333.
+* Hall, S. R., Allen, F. H. and Brown, I. D. (1991). "The Crystallographic
+* Information File (CIF): A New Standard Archive File for Crystallography",
+* Acta Cryst., A47, 655-685.
+* Hall, S.R. & Spadaccini, N. (1994). "The STAR File: Detailed 
+* Specifications," J. Chem. Info. Comp. Sci., 34, 505-508.
+*</p>
+*/
+
+public class CifDataParser implements GenericCifDataParser {
+
+  protected int getVersion() {
+    return 1;
+  }
+
+  /**
+   * The maximum number of columns (data keys) passed to the parser or found in the file
+   * for a given loop_ or category.subkey listing.
+   * 
+   */
+  public static final int KEY_MAX = 100;
+
+  private GenericLineReader reader;
+  private BufferedReader br;
+
+  /**
+   * from buffered reader
+   */
+  protected String line;
+  
+  /**
+   * working string (buffer)
+   * 
+   */
+  protected String str;
+  
+  /**
+   * pointer to current character on str
+   */
+  protected int ich;
+  
+  /**
+   * length of str
+   * 
+   */
+  protected int cch;
+  
+  /**
+   * whether we are processing an unquoted value or key
+   */
+  protected boolean wasUnquoted;
+  
+  /**
+   * optional token terminator; in CIF 2.0 could be } or ] 
+   */
+  protected char cterm = '\0';
+  
+  /**
+   * string to return for CIF data value . and ?
+   */
+  protected String nullString = "\0";
+
+  /**
+   * A flag to create and return Java objects, not strings.
+   * Used only by Jmol scripting x = getProperty("cifInfo", filename).
+   */
+  protected boolean asObject;
+
+  
+  /**
+   * debugging flag passed from reader; unused
+   * 
+   */
+  protected boolean debugging;
+
+
+  /**
+   * private processing fields
+   * 
+   */
+  private Object strPeeked;
+  private int ichPeeked;
+  private int columnCount;
+  private String[] columnNames;
+  private Object[] columnData = new Object[KEY_MAX];
+  private boolean isLoop;
+  private boolean haveData;
+  
+  /**
+   * comments at the top of a file, including #\#CIF_2.0, for example
+   */
+  private SB fileHeader = new SB(); 
+  private boolean isHeader = true;
+
+
+  /**
+   * Set the string value of what is returned for "." and "?"
+   * 
+   * @param nullString null here returns "." and "?"; default is "\0"
+   * 
+   */
+  public void setNullValue(String nullString) {
+    this.nullString  = nullString;    
+  }
+
+  /**
+   * A global, static map that contains field information. The assumption is that
+   * if we read a set of fields for, say, atom_site, once in a lifetime, then
+   * that should be good forever. Those are static lists. Or should be....
+   */
+  private static Map<String, Integer> htFields = new Hashtable<String, Integer>();
+  
+  ////////////////////////////////////////////////////////////////
+  // special tokenizer class
+  ////////////////////////////////////////////////////////////////
+
+  public CifDataParser() {
+    // for reflection
+  }
+    
+  @Override
+  public Object getColumnData(int i) {
+    return columnData[i];
+  }
+
+  @Override
+  public int getColumnCount() {
+    return columnCount;
+  }
+
+  @Override
+  public String getColumnName(int i) {
+    return columnNames[i];
+  }
+
+  /**
+   * A Chemical Information File data parser.
+   * 
+   * set() should be called immediately upon construction.
+   *  
+   * Two options; one of reader or br should be null, or reader will be
+   * ignored. Just simpler this way...
+   * 
+   * @param reader  Anything that can deliver a line of text or null
+   * @param br      A standard BufferedReader.
+   * @param debugging 
+   *  
+   */
+  @Override
+  public CifDataParser set(GenericLineReader reader, BufferedReader br, boolean debugging) {
+    this.reader = reader;
+    this.br = br;
+    this.debugging = debugging;
+    return this;
+  }
+
+
+  /**
+   * 
+   * @return commented-out section at the start of a CIF file.
+   * 
+   */
+  @Override
+  public String getFileHeader() {
+    return fileHeader.toString();
+  }
+  
+  
+  /**
+   * Parses all CIF data for a reader defined in the constructor
+   * into a standard Map structure and close the BufferedReader if
+   * it exists. 
+   * 
+   * @return Hashtable of models Vector of Hashtable data
+   */
+  @Override
+  public Map<String, Object> getAllCifData() {
+    line = "";
+    String key;
+    Map<String, Object> data = null, data0 = null;
+    Map<String, Object> allData = new Hashtable<String, Object>();
+    Lst<Map<String, Object>> models = new  Lst<Map<String,Object>>();
+    allData.put("models", models);
+    asObject = (getVersion() >= 2);
+    nullString = null;
+    Lst<Map<String, Object>> saveFrames = new Lst<Map<String, Object>>();
+    try {
+      while ((key = getNextToken()) != null) {
+        if (key.startsWith("global_") || key.startsWith("data_")) {
+          models.addLast(data0 = data = new Hashtable<String, Object>());
+          data.put("name", key);
+          continue;
+        }
+        if (key.startsWith("loop_")) {
+          getAllCifLoopData(data);
+          continue;
+        }
+        if (key.startsWith("save_")) {
+          if (key.equals("save_")) {
+            int n = saveFrames.size();
+            if (n == 0) {
+              System.out.println("CIF ERROR ? save_ without corresponding save_xxxx");
+              data = data0;
+            } else {
+              data = saveFrames.removeItemAt(n - 1);
+            }
+          } else {
+            saveFrames.addLast(data);
+            Map<String, Object> d = data;
+            data = new Hashtable<String, Object>();
+            d.put(key, data);
+          }
+          continue;
+        }
+        if (key.charAt(0) != '_') {
+          System.out.println("CIF ERROR ? should be an underscore: " + key);
+        } else {
+          Object value = (asObject ? getNextTokenObject() : getNextToken());
+          if (value == null) {
+            System.out.println("CIF ERROR ? end of file; data missing: " + key);
+          } else {
+            data.put(fixKey(key), value);
+          }
+        }
+      }
+    } catch (Exception e) {
+      // ?
+    }
+    asObject = false;
+    try {
+      if (br != null)
+        br.close();
+    } catch (Exception e) {
+      // ?
+    }
+    nullString = "\0";
+    return allData;
+  }
+
+  /**
+   * create our own list of keywords and for each one create a list
+   * of data associated with that keyword. For example, a list of all 
+   * x coordinates, then a list of all y coordinates, etc.
+   * 
+   * @param data
+   * @throws Exception
+   */
+  @SuppressWarnings("unchecked")
+  private void getAllCifLoopData(Map<String, Object> data) throws Exception {
+    String key;
+    Lst<String> keyWords = new  Lst<String>();
+    Object o;
+    while ((o = peekToken()) != null && o instanceof String &&  ((String) o).charAt(0) == '_') {
+      key = fixKey((String) getTokenPeeked());
+      keyWords.addLast(key);
+      data.put(key, new  Lst<String>());
+    }
+    columnCount = keyWords.size();
+    if (columnCount == 0)
+      return;
+    isLoop = true;
+    while (getData())
+      for (int i = 0; i < columnCount; i++)
+        ((Lst<Object>)data.get(keyWords.get(i))).addLast(columnData[i]);
+    isLoop = false;
+  }
+
+  @Override
+  public String readLine() {
+    try {
+      line = (reader == null ? br.readLine() : reader.readNextLine());
+      if (line == null)
+        return null;
+      if (isHeader) {
+        if (line.startsWith("#"))
+          fileHeader.append(line).appendC('\n');
+        else
+          isHeader = false;
+      }
+      return line;
+    } catch (Exception e) {
+      return null;
+    }
+  }
+  
+  /**
+   * The work horse; a general reader for loop data. Fills colunnData with
+   * fieldCount fields.
+   * 
+   * @return false if EOF
+   * @throws Exception
+   */
+  @Override
+  public boolean getData() throws Exception {
+    // line is already present, and we leave with the next line to parse
+    if (isLoop) {
+      for (int i = 0; i < columnCount; ++i)
+        if ((columnData[i] = getNextDataToken()) == null)
+          return false;
+    } else if (haveData) {
+      haveData = false;
+    } else {
+      return false;
+    }
+    return (columnCount > 0);
+  }
+
+  /**
+   * 
+   * Skips all associated loop data. (Skips to next control word.)
+   * 
+   * @throws Exception
+   */
+  @Override
+  public String skipLoop(boolean doReport) throws Exception {
+    String str;
+    SB ret = (doReport ? new SB() : null);
+    int n = 0;
+    while ((str = (String) peekToken()) != null && str.charAt(0) == '_') {
+      if (ret != null)
+        ret.append(str).append("\n");
+      getTokenPeeked();
+      n++;
+    }
+    if (n == 0)
+      n = columnCount; // end-of-label-section skip 
+    int m = 0;
+    while ((str = (String) getNextDataToken()) != null) {
+      if (ret == null)
+        continue; 
+      ret.append(str).append(" ");
+      if ((++m % n) == 0)
+        ret.append("\n");
+    }
+    return (ret == null ? null : ret.toString());
+  }
+
+  /**
+   * Get a token as a String value (for the reader)
+   * 
+   * @return the next token of any kind, or null
+   * @throws Exception
+   */
+  @Override
+  public String getNextToken() throws Exception {
+    wasUnquoted = true;
+    return (String) getNextTokenProtected();
+  }
+
+  /**
+   * Get the token as a Java Object
+   * 
+   * @return the next token of any kind, or null
+   * @throws Exception
+   */
+  public Object getNextTokenObject() throws Exception {
+    wasUnquoted = true;
+    return getNextTokenProtected();
+  }
+
+  /**
+   * Just makes sure
+   * @return String from buffer.
+   * @throws Exception
+   */
+  protected Object getNextTokenProtected() throws Exception {
+    return (getNextLine() ? nextStrToken() : null);
+  }
+
+  /**
+   * 
+   * first checks to see if the next token is an unquoted
+   * control code, and if so, returns null 
+   * 
+   * @return next data token or null
+   * @throws Exception
+   */
+  @Override
+  public Object getNextDataToken() throws Exception { 
+    Object o = peekToken();
+    if (o == null)
+      return null;
+    if (wasUnquoted && o instanceof String) {
+      String str = (String) o;
+      if (str.charAt(0) == '_' || str.startsWith("loop_")
+          || str.startsWith("data_")
+          || str.startsWith("save_")
+          || str.startsWith("stop_")
+          || str.startsWith("global_"))
+        return null;
+    }
+    return getTokenPeeked();
+  }
+  
+  /**
+   * Just look at the next token. Saves it for retrieval 
+   * using getTokenPeeked()
+   * 
+   * @return next token or null if EOF
+   * @throws Exception
+   */
+  @Override
+  public Object peekToken() throws Exception {
+    if (!getNextLine())
+      return null;
+    int ich = this.ich;
+    strPeeked = nextStrToken();
+    ichPeeked= this.ich;
+    this.ich = ich;
+    return strPeeked;
+  }
+  
+  /**
+   * grab a new line if necessary and prepare it 
+   * if it starts with ";"
+   * 
+   * @return updated this.str
+   * @throws Exception
+   */
+  private boolean getNextLine() throws Exception {
+    while (!strHasMoreTokens())
+      if (prepareNextLine() == null)
+        return false;
+    return true;
+  }
+
+  /**
+   * 
+   * @return the token last acquired; may be null
+   */
+  @Override
+  public Object getTokenPeeked() {
+    ich = ichPeeked;
+    return strPeeked;
+  }
+  
+  /**
+   * Used especially for data that might be multi-line data that
+   * might have unwanted white space at start or end.
+   * 
+   * @param str
+   * @return str without any leading/trailing white space, and no '\n'
+   */
+  @Override
+  public String fullTrim(String str) {
+    int pt0 = -1;
+    int pt1 = str.length();
+    while (++pt0 < pt1 && PT.isWhitespace(str.charAt(pt0))) {
+    }
+    while (--pt1 > pt0 && PT.isWhitespace(str.charAt(pt1))) {      
+    }
+    return str.substring(pt0, pt1 + 1);
+  }
+
+  private final static String grABC =
+      "ABX\u0394E\u03A6\u0393H"   // ABCDEFGH
+      + "I_K\u039BMNO\u03A0"      // I_KLMNOP
+      + "\u0398P\u03A3TY_\u03A9\u039E\u03A5Z"; // QRSTU_WXYZ
+  private final static String grabc =
+      "\u03B1\u03B2\u03C7\u03A4\u03A5\u03C6\u03B3\u03B7" // abcdefgh
+      + "\u03B9_\u03BA\u03BB\u03BC\u03BD\u03BF\u03C0"    // i_klmnop
+      + "\u03B8\u03C1\u03C3\u03C4\u03C5_\u03C9\u03BE\u03C5\u03B6"; // qrstu_wxyz
+
+  /**
+   * Only translating the basic Greek set here, not all the other stuff. See
+   * http://www.iucr.org/resources/cif/spec/version1.1/semantics#markup
+   * 
+   * @param data
+   * @return cleaned string
+   */
+  @Override
+  public String toUnicode(String data) {
+    int pt;
+    try {
+      while ((pt = data.indexOf('\\')) >= 0) {
+        int c = data.charAt(pt + 1);
+        String ch = (c >= 65 && c <= 90 ? grABC.substring(c - 65, c - 64)
+            : c >= 97 && c <= 122 ? grabc.substring(c - 97, c - 96) : "_");
+        data = data.substring(0, pt) + ch + data.substring(pt + 2);
+      }
+    } catch (Exception e) {
+      // ignore
+    }
+
+    return data;
+  }
+
+  /**
+   * Process a data block, with or without a loop_.
+   * 
+   * Passed an array of field names, this method fills two int[] arrays. The
+   * first, key2col, maps desired key values to actual order of appearance
+   * (column number) in the file; the second, col2key, is a reverse loop-up for
+   * that, mapping column numbers to desired field indices. 
+   * 
+   * When called within a loop_ context, this.columnData will be created but not filled.
+   * 
+   * Alternatively, if fields is null, then this.fieldNames is
+   * filled, in order, with key data, and both key2col and col2key will be
+   * simply 0,1,2,... This array is used in cases such as matrices for which
+   * there are simply too many possibilities to list, and the key name itself
+   * contains information that we need.
+   * 
+   * When not a loop_ context, keys are expected to be in the mmCIF form
+   * category.subkey and will be unique within a data block (see
+   * http://mmcif.wwpdb.org/docs/tutorials/mechanics/pdbx-mmcif-syntax.html).
+   * Keys and data will be read for all data in the same category, filling this.columnData.
+   * 
+   * 
+   * In this way, the calling class does not need to enumerate all possible
+   * category names, but instead can focus on just those of interest.
+   * 
+   * 
+   * @param fields
+   *        list of normalized field names, such as
+   *        "_pdbx_struct_assembly_gen_assembly_id" (with "_" instead of ".")
+   * @param key
+   *        null to indicate a loop_ construct, otherwise the initial category.subkey
+   *        found
+   * @param data
+   *        when not loop_ the initial data read, otherwise ignored
+   * @param key2col
+   *        map of desired keys to actual columns
+   * @param col2key
+   *        map of actual columns to desired keys
+   * @throws Exception
+   */
+  @Override
+  public void parseDataBlockParameters(String[] fields, String key,
+                                 String data, int[] key2col, int[] col2key) throws Exception {
+    isLoop = (key == null);
+    Object o;
+    String s;
+    if (fields == null) {
+      // for reading full list of keys, as for matrices
+      columnNames = new String[KEY_MAX];
+    } else {
+      if (!htFields.containsKey(fields[0]))
+        for (int i = fields.length; --i >= 0;)
+          htFields.put(fields[i], Integer.valueOf(i));
+      for (int i = fields.length; --i >= 0;)
+        key2col[i] = NONE;
+    }
+    columnCount = 0;
+    int pt, i;
+    if (isLoop) {
+      while (true) {
+        o = peekToken();
+        if (o == null) {
+          // we are PREMATURELY done; reset
+          columnCount = 0;
+          break;
+        }
+        // end of the loop is a new token not starting with underscore
+        if (!(o instanceof String) || ((String) o).charAt(0) != '_')
+          break;
+
+        pt = columnCount++;
+        s = fixKey((String) getTokenPeeked());
+        if (fields == null) {
+          // just make a linear model, saving the list
+          columnNames[col2key[pt] = key2col[pt] = pt] = s;
+          continue;
+        }
+        Integer iField = htFields.get(s);
+        i = (iField == null ? NONE : iField.intValue());
+        if ((col2key[pt] = i) != NONE)
+          key2col[i] = pt;
+      }
+    } else {
+      pt = key.indexOf(".");
+      String str0 = (pt < 0 ? key : key.substring(0, pt + 1));
+      while (true) {
+        // end of the loop is a new token not starting with underscore
+        pt = columnCount++;
+        if (key == null) {
+          key = (String) getTokenPeeked();
+          data = getNextToken();
+        }
+        Integer iField = htFields.get(fixKey(key));
+        i = (iField == null ? NONE : iField.intValue());
+        if ((col2key[pt] = i) != NONE) 
+          columnData[key2col[i] = pt] = data;
+        if ((o = peekToken()) == null || !(o instanceof String) ||  !((String) o).startsWith(str0))
+          break;
+        key = null;
+      }
+      haveData = (columnCount > 0);
+    }
+  }
+
+  @Override
+  public String fixKey(String key) {
+    // PRELIMINARY -- BilBao _magnetic
+    // PRELIMINARY -- Jana2006
+    return (
+        key.startsWith("_magnetic") ? key.substring(9) 
+            : key.startsWith("_jana") ? key.substring(5) 
+            : key).replace('.', '_').toLowerCase();
+  }
+
+  //////////////////// private methods ////////////////////
+  
+  
+  /**
+   * sets global str and line to be parsed from the beginning
+   * 
+   * \1 .... \1  indicates an embedded fully escaped data object
+   * 
+   * @param str new data string
+   * @return str
+   */
+  protected String setString(String str) {
+    this.str = line = str;
+    cch = (str == null ? 0 : str.length());
+    ich = 0;
+    return str;
+  }
+
+  /*
+   * http://www.iucr.org/resources/cif/spec/version1.1/cifsyntax
+   * 
+   * 17. The special sequence of end-of-line followed 
+   * immediately by a semicolon in column one (denoted "<eol>;") 
+   * may also be used as a delimiter at the beginning and end 
+   * of a character string comprising a data value. The complete 
+   * bounded string is called a text field, and may be used to 
+   * convey multi-line values. The end-of-line associated with 
+   * the closing semicolon does not form part of the data value. 
+   * Within a multi-line text field, leading white space within 
+   * text lines must be retained as part of the data value; trailing 
+   * white space on a line may however be elided.
+   * 
+   * 18. A text field delimited by the <eol>; digraph may not 
+   * include a semicolon at the start of a line of text as 
+   * part of its value.
+   * 
+   * 20. For example, the data value foo may be expressed 
+   * equivalently as an unquoted string foo, as a quoted 
+   * string 'foo' or as a text field
+   *
+   *;foo
+   *;
+   *
+   * By contrast the value of the text field
+   *
+   *; foo
+   *  bar
+   *;
+   *
+   * is  foo<eol>  bar (where <eol> represents an end-of-line); 
+   * the embedded space characters are significant.
+   * 
+   * 
+   * I (BH) note, however, that we sometimes have:
+   * 
+   * _some_name
+   * ;
+   * the name here
+   * ;
+   * 
+   * so this should actually be
+   * 
+   * ;the name here
+   * ;
+   * 
+   * for this, we use fullTrim();
+   * 
+   */
+  
+  /**
+   * 
+   * sets the string for parsing to be from the next line 
+   * when the token buffer is empty, and if ';' is at the 
+   * beginning of that line, extends the string to include
+   * that full multiline string. Uses \1 to indicate that 
+   * this is a special quotation. 
+   * 
+   * 
+   * 
+   * @return  the next line or null if EOF
+   * @throws Exception
+   */
+  protected String prepareNextLine() throws Exception {
+    setString(readLine());
+    if (line == null || line.length() == 0)
+      return line;
+    if (line.charAt(0) == ';')
+      return preprocessString();
+    if (str.startsWith("###non-st#"))
+        ich = 10;
+    return line;
+ }
+
+  /**
+   * Preprocess the string on a line starting with a semicolon
+   * to produce a string with a \1 ... \1 segment
+   * that will be picked up in the next round
+   *  
+   * @return escaped part with attached extra data
+   * @throws Exception 
+   */
+  protected String preprocessString() throws Exception {
+    return setString(preprocessSemiString());
+  }
+
+  /**
+   * Encapsulate a multi-line ; .... ;  string with \1 ... \1
+   * 
+   * CIF 1.0 and CIF 2.0
+   * 
+   * @return ecapsulated string
+   * @throws Exception 
+   */
+  protected String preprocessSemiString() throws Exception {
+    ich = 1;
+    String str = '\1' + line.substring(1) + '\n';
+    while (readLine() != null) {
+      if (line.startsWith(";")) {
+        // remove trailing <eol> only, and attach rest of next line
+        str = str.substring(0, str.length() - 1)
+          + '\1' + line.substring(1);
+        break;
+      }
+      str += line + '\n';
+    }
+    return str;
+  }
+
+  /**
+   * @return TRUE if there are more tokens in the line buffer
+   * 
+   */
+  private boolean strHasMoreTokens() {
+    if (str == null)
+      return false;
+    char ch = '#';
+    while (ich < cch && ((ch = str.charAt(ich)) == ' ' || ch == '\t'))
+      ++ich;
+    return (ich < cch && ch != '#');
+  }
+
+  /**
+   * assume that hasMoreTokens() has been called and that ich is pointing at a
+   * non-white character. Also sets boolean wasUnQuoted, because we need to know
+   * if we should be checking for a control keyword. 'loop_' is different from
+   * just loop_ without the quotes.
+   * 
+   * @return null if no more tokens, "\0" if '.' or '?', or next token
+   */
+  private Object nextStrToken() {
+    if (ich == cch)
+      return null;
+    char ch = str.charAt(ich);
+    if (isQuote(ch)) {
+      wasUnquoted = false;
+      return getQuotedStringOrObject(ch);
+    }
+    int ichStart = ich;
+    wasUnquoted = true;
+    while (ich < cch && !isTerminator(ch = str.charAt(ich)))
+      ++ich;
+    if (ich == ichStart + 1)
+      if (nullString != null
+          && (str.charAt(ichStart) == '.' || str.charAt(ichStart) == '?'))
+        return nullString;
+    String s = str.substring(ichStart, ich);
+    return unquoted(s);
+  }
+
+  /**
+   * In CIF 2.0, this method turns a String into an Integer or Float
+   * In CIF 1.0 (here) just return the unchanged value.
+   * @param s unquoted string
+   * @return unchanged value
+   */
+  protected Object unquoted(String s) {
+    return s;
+  }
+
+  /**
+   * The token terminator is space or tab in CIF 1.0, 
+   * but it can be quoted strings in CIF 2.0.
+   * 
+   * @param c
+   * @return true if this character is a terminator
+   */
+  protected boolean isTerminator(char c) {
+    return  c == ' ' || c == '\t' || c == cterm ;
+  }
+
+  /**
+   * CIF 1.0 only; we handle various quote types here 
+   * @param ch
+   * @return true if this character is a (starting) quote
+   */
+  protected boolean isQuote(char ch) {
+    switch (ch) {
+    case '\'':
+    case '\"':
+    case '\1':
+      return  true;
+    }
+    return false;
+  }
+
+  /**
+   * CIF 1.0 only. 
+   * 
+   *  
+   * @param ch current character being pointed to
+   * @return a String data object
+   */
+  protected Object getQuotedStringOrObject(char ch) {
+    int ichStart = ich;
+    char chClosingQuote = ch;
+    boolean wasQuote = false;
+    while (++ich < cch) {
+      ch = str.charAt(ich);
+      // CIF 1.0 rules require that the closing ' or ""  be followed by space or tab or EOL
+      if (wasQuote && (ch == ' ' || ch == '\t'))
+        break;
+      wasQuote = (ch == chClosingQuote);
+    }
+    int pt1 = ichStart + 1;
+    int pt2 = ich - 1;
+    if (ich == cch && !wasQuote) {
+      // reached the end of the string without finding closing '
+      // so take the whole thing. Probably a bad CIF file.
+      pt1--;
+      pt2++;
+    } else {
+      // throw away the last white character
+      ++ich; 
+    }
+    return str.substring(pt1, pt2);
+  }
+
+  
+}
\ No newline at end of file
diff --git a/src2/javajs/util/CompoundDocDirEntry.java b/src2/javajs/util/CompoundDocDirEntry.java
new file mode 100644 (file)
index 0000000..a57f6af
--- /dev/null
@@ -0,0 +1,101 @@
+/* $RCSfile$
+ * $Author$
+ * $Date$
+ * $Revision$
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2011  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301, USA.
+ */
+
+package javajs.util;
+
+
+class CompoundDocDirEntry {
+
+  private final CompoundDocument cd;
+
+  /**
+   * @param compoundDocument
+   */
+  CompoundDocDirEntry(CompoundDocument compoundDocument) {
+    cd = compoundDocument;
+  }
+
+  // 128 bytes
+  //offset 0:
+  byte[] unicodeName64 = new byte[64];
+  short nBytesUnicodeName; // twice the ascii length, including terminating 0
+  byte entryType; // 0 empty; 1 storage; 2 stream; 5 root storage
+  //byte entryColor; // 0 red or 1 black
+  //int DIDchildLeft;
+  //int DIDchildRight;
+  //int DIDstorageRoot;
+  byte[] uniqueID16 = new byte[16];
+  byte[] userflags4 = new byte[4];
+  //long timeStamp1;
+  //long timeStamp2;
+  //offset 116:
+  int SIDfirstSector; // either SAT or SSAT
+  int lenStream;
+  byte[] unused = new byte[8];
+
+  // derived:
+
+  String entryName;
+  boolean isStandard;
+  boolean isEmpty;
+
+  final boolean readData() {
+    try {
+      cd.readByteArray(unicodeName64, 0, 64);
+      nBytesUnicodeName = cd.readShort();
+      entryType = cd.readByte();
+      /*entryColor = */cd.readByte();
+      /*DIDchildLeft = */cd.readInt();
+      /*DIDchildRight = */cd.readInt();
+      /*DIDstorageRoot = */cd.readInt();
+      cd.readByteArray(uniqueID16, 0, 16);
+      cd.readByteArray(userflags4, 0, 4);
+      /*timeStamp1 = */      cd.readByteArray(unused, 0, 8);//cd.readLong();
+      /*timeStamp2 = */      cd.readByteArray(unused, 0, 8);//cd.readLong();
+      //offset 116:
+      SIDfirstSector = cd.readInt();
+      lenStream = cd.readInt();
+      cd.readByteArray(unused, 0, 4);
+    } catch (Exception e) {
+      System.out.println(e.toString());
+      return false;
+    }
+    entryName = "";
+    for (int i = 0; i < nBytesUnicodeName - 2; i += 2)
+      entryName += (char) unicodeName64[i];
+    isStandard = (entryType == 5 || lenStream >= cd.header.minBytesStandardStream);
+    isEmpty = (entryType == 0 || lenStream <= 0);
+    //System.out.println(entryName + " type " + entryType);
+    return true;
+  }
+  
+  @Override
+  public String toString() {
+    return entryName + " " + lenStream;
+  }
+}
\ No newline at end of file
diff --git a/src2/javajs/util/CompoundDocHeader.java b/src2/javajs/util/CompoundDocHeader.java
new file mode 100644 (file)
index 0000000..72317fe
--- /dev/null
@@ -0,0 +1,115 @@
+/* $RCSfile$
+ * $Author$
+ * $Date$
+ * $Revision$
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2011  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301, USA.
+ */
+
+package javajs.util;
+
+
+class CompoundDocHeader {
+
+  /**
+   * 
+   */
+  private final CompoundDocument cd;
+
+  /**
+   * @param compoundDocument
+   */
+  CompoundDocHeader(CompoundDocument compoundDocument) {
+    cd = compoundDocument;
+  }
+
+  //512 bytes
+  //offset 0:
+  byte[] magicNumbers = new byte[8]; // D0CF11E0A1B11AE1
+  byte[] uniqueID16 = new byte[16];
+  byte revNumber; // 3E = 62
+  //byte unusedb1;
+  byte verNumber; // 3
+  //byte unusedb2;
+  //short byteOrder; // -2 littleEndian
+  short sectorPower; // 2^sectorPower = sector size; 512 = 2^9
+  short shortSectorPower; // 2^shortSectorPower = short sector size; 64 = 2^6
+  byte[] unused = new byte[10];
+  int nSATsectors; // number of sectors for sector allocation table
+  int SID_DIR_start; // sector identifier of start of directory sector
+  //offset 56:
+  int minBytesStandardStream; // less than this (and not DIR) will be "short"
+  int SID_SSAT_start; // start of short sector allocation table (SSAT)
+  int nSSATsectors; // number of sectors allocated to SSAT
+  int SID_MSAT_next; // pointer to next master sector allocation table sector
+  int nAdditionalMATsectors; // number of sectors allocated to more MSAT sectors
+  //offset 76; 436 bytes:      
+  int[] MSAT0 = new int[109]; // beginning of master allocation table 
+
+  /*
+   *  Sector 0 is first sector AFTER this header
+   *  
+   *  If sectorPower = 9, then this allows for 109 PAGES
+   *  of sector allocation tables, with 127 pointers per
+   *  page (plus 1 pointer to the next SAT page), each 
+   *  pointing to a sector of 512 bytes. Thus, with no additional
+   *  MSAT pages, the header allows for 109*128*512 = 7.1 Mb file
+   *  
+   */
+
+  final boolean readData() {
+    try {
+      cd.readByteArray(magicNumbers, 0, 8);
+      if ((magicNumbers[0] & 0xFF) != 0xD0 || (magicNumbers[1] & 0xFF) != 0xCF
+          || (magicNumbers[2] & 0xFF) != 0x11 || (magicNumbers[3] & 0xFF) != 0xE0
+          || (magicNumbers[4] & 0xFF) != 0xA1 || (magicNumbers[5] & 0xFF) != 0xB1
+          || (magicNumbers[6] & 0xFF) != 0x1A || (magicNumbers[7] & 0xFF) != 0xE1)
+        return false;
+      cd.readByteArray(uniqueID16, 0, 16);
+      revNumber = cd.readByte();
+      cd.readByte();
+      verNumber = cd.readByte();
+      cd.readByte();
+      byte b1 = cd.readByte();
+      byte b2 = cd.readByte();
+      cd.isBigEndian = (b1 == -1 && b2 == -2);
+      sectorPower = cd.readShort();
+      shortSectorPower = cd.readShort();
+      cd.readByteArray(unused, 0, 10);
+      nSATsectors = cd.readInt();
+      SID_DIR_start = cd.readInt();
+      cd.readByteArray(unused, 0, 4);
+      minBytesStandardStream = cd.readInt();
+      SID_SSAT_start = cd.readInt();
+      nSSATsectors = cd.readInt();
+      SID_MSAT_next = cd.readInt();
+      nAdditionalMATsectors = cd.readInt();
+      for (int i = 0; i < 109; i++)
+        MSAT0[i] = cd.readInt();
+    } catch (Exception e) {
+      System.out.println(e.toString());
+      return false;
+    }
+    return true;
+  }
+}
\ No newline at end of file
diff --git a/src2/javajs/util/CompoundDocument.java b/src2/javajs/util/CompoundDocument.java
new file mode 100644 (file)
index 0000000..2e2c242
--- /dev/null
@@ -0,0 +1,395 @@
+/* $RCSfile$
+ * $Author: egonw $
+ * $Date: 2006-03-18 15:59:33 -0600 (Sat, 18 Mar 2006) $
+ * $Revision: 4652 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2003-2005  Miguel, Jmol Development, www.jmol.org
+ *
+ * Contact: hansonr@stolaf.edu
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.util;
+
+
+import java.io.DataInputStream;
+import java.io.BufferedInputStream;
+
+
+import java.util.Map;
+
+import javajs.api.GenericZipTools;
+
+
+
+/* a simple compound document reader. 
+ * 
+ * DIRECTORY STRUCTURE IS NOT REGENERATED
+ * 
+ * See http://sc.openoffice.org/compdocfileformat.pdf
+ * 
+ * random access file info: 
+ * http://java.sun.com/docs/books/tutorial/essential/io/rafs.html
+ * 
+ * SHOOT! random access is only for applications, not applets!
+ * 
+ * With a bit more work, this could be set up to deliver binary files, but
+ * right now I've only implemented it for string-based data. 
+ * 
+ */
+
+public class CompoundDocument extends BinaryDocument{
+
+//  RandomAccessFile file;
+  CompoundDocHeader header = new CompoundDocHeader(this);
+  Lst<CompoundDocDirEntry> directory = new  Lst<CompoundDocDirEntry>();
+  CompoundDocDirEntry rootEntry;
+
+  protected GenericZipTools jzt;
+
+  int[] SAT;
+  int[] SSAT;
+  int sectorSize;
+  int shortSectorSize;
+  int nShortSectorsPerStandardSector;
+  int nIntPerSector;
+  int nDirEntriesperSector;
+
+  // called by reflection
+  
+  public CompoundDocument(){
+    super();
+    this.isBigEndian = true;
+  }
+  
+  public void setDocStream(GenericZipTools jzt, BufferedInputStream bis) {
+    this.jzt = jzt;
+    if (!isRandom) {
+      stream = new DataInputStream(bis);
+    }
+    stream.mark(Integer.MAX_VALUE);
+    if (!readHeader())
+      return;
+    getSectorAllocationTable();
+    getShortSectorAllocationTable();
+    getDirectoryTable();
+  }
+
+  public Lst<CompoundDocDirEntry> getDirectory() {
+    return directory;
+  }
+
+  public String getDirectoryListing(String separator) {
+    SB sb = new SB();
+    for (int i = 0; i < directory.size(); i++) {
+      CompoundDocDirEntry thisEntry = directory.get(i);
+      if (!thisEntry.isEmpty)
+        sb.append(separator).append(thisEntry.entryName)
+        .append("\tlen=").appendI(thisEntry.lenStream)
+        .append("\tSID=").appendI(thisEntry.SIDfirstSector)
+        .append(thisEntry.isStandard ? "\tfileOffset="
+                + getOffset(thisEntry.SIDfirstSector) : "");
+    }
+    return sb.toString();
+  }
+
+  public SB getAllData() {
+    return getAllDataFiles(null, null);
+  }
+
+  /**
+   * reads a compound document directory and saves all data in a Hashtable
+   * so that the files may be organized later in a different order. Also adds
+   * a #Directory_Listing entry.
+   * 
+   * Files are bracketed by BEGIN Directory Entry and END Directory Entry lines, 
+   * similar to ZipUtil.getAllData.
+   * 
+   * @param prefix
+   * @param binaryFileList   |-separated list of files that should be saved
+   *                         as xx xx xx hex byte strings. The directory listing
+   *                         is appended with ":asBinaryString"
+   * @param fileData
+   */
+  @Override
+  public void getAllDataMapped(String prefix, 
+                         String binaryFileList, Map<String, String> fileData) {
+    fileData.put("#Directory_Listing", getDirectoryListing("|"));
+    binaryFileList = "|" + binaryFileList + "|";
+    for (int i = 0; i < directory.size(); i++) {
+      CompoundDocDirEntry thisEntry = directory.get(i);
+      if (!thisEntry.isEmpty && thisEntry.entryType != 5) {
+      String name = thisEntry.entryName;
+        System.out.println("CompoundDocument file " + name);
+        boolean isBinary = (binaryFileList.indexOf("|" + name + "|") >= 0);
+        if (isBinary)
+          name += ":asBinaryString";
+        fileData.put(prefix + "/" + name, appendData(new SB(), name, thisEntry, isBinary).toString());
+      }
+    }
+    close();
+  }
+
+  @Override
+  public SB getAllDataFiles(String binaryFileList, String firstFile) {
+// firstFile is now ignored
+//    if (firstFile != null) {
+//      for (int i = 0; i < directory.size(); i++) {
+//        CompoundDocDirEntry thisEntry = directory.get(i);
+//        if (thisEntry.entryName.equals(firstFile)) {
+//          directory.remove(i);
+//          directory.add(1, thisEntry); // after ROOT_ENTRY
+//          break;
+//        }
+//      }
+//    }
+    SB data = new SB();
+    data.append("Compound Document File Directory: ");
+    data.append(getDirectoryListing("|"));
+    data.append("\n");
+    CompoundDocDirEntry thisEntry;
+    binaryFileList = "|" + binaryFileList + "|";
+    for (int i = 0, n = directory.size(); i < n; i++) {
+      thisEntry = directory.get(i);
+      //System.out.println("CompoundDocument reading " + thisEntry.entryName);
+      String name = thisEntry.entryName;
+      switch (thisEntry.entryType) {
+      case 5: // root
+        break;
+      case 1: // user storage (dir)
+        data.append("NEW Directory ").append(name).append("\n");            
+        break;
+      case 2: // user stream (file)
+        if (name.endsWith(".gz"))
+          name = name.substring(0, name.length() - 3);
+        appendData(data, name, thisEntry, binaryFileList.indexOf("|" + thisEntry.entryName + "|") >= 0);
+        break;
+      }
+    }
+    close();
+    return data;
+  }
+
+  private SB appendData(SB data, String name, CompoundDocDirEntry thisEntry,
+                          boolean isBinary) {
+    data.append("BEGIN Directory Entry ").append(name).append("\n");            
+    data.appendSB(getEntryAsString(thisEntry, isBinary));
+    data.append("\nEND Directory Entry ").append(name).append("\n");
+    return data;
+  }
+
+  public SB getFileAsString(String entryName) {
+    for (int i = 0; i < directory.size(); i++) {
+      CompoundDocDirEntry thisEntry = directory.get(i);
+      if (thisEntry.entryName.equals(entryName))
+        return getEntryAsString(thisEntry, false);
+    }
+    return new SB();
+  }
+
+  private long getOffset(int SID) {
+    return (SID + 1) * sectorSize;
+  }
+
+  private void gotoSector(int SID) {
+    seek(getOffset(SID));
+  }
+
+  private boolean readHeader() {
+    if (!header.readData())
+      return false;
+    sectorSize = 1 << header.sectorPower;
+    shortSectorSize = 1 << header.shortSectorPower;
+    nShortSectorsPerStandardSector = sectorSize / shortSectorSize; // e.g. 512 / 64 = 8
+    nIntPerSector = sectorSize / 4; // e.g. 512 / 4 = 128
+    nDirEntriesperSector = sectorSize / 128; // e.g. 512 / 128 = 4
+//    System.out.println(
+//          "compound document: revNum=" + header.revNumber +
+//          " verNum=" + header.verNumber + " isBigEndian=" + isBigEndian +
+//          " bytes per standard/short sector=" + sectorSize + "/" + shortSectorSize);
+    return true;
+  }
+
+  private void getSectorAllocationTable() {
+    int nSID = 0;
+    int thisSID;
+    SAT = new int[header.nSATsectors * nIntPerSector + 109];
+
+    try {
+      for (int i = 0; i < 109; i++) {
+        thisSID = header.MSAT0[i];
+        if (thisSID < 0)
+          break;
+        gotoSector(thisSID);
+        for (int j = 0; j < nIntPerSector; j++) {
+          SAT[nSID++] = readInt();
+          //Logger.debug(thisSID+"."+j + "/" + (nSID - 1) + " : " + SAT[nSID - 1]);
+        }
+      }
+      int nMaster = header.nAdditionalMATsectors;
+      thisSID = header.SID_MSAT_next;
+      int[] MSAT = new int[nIntPerSector];
+      out: while (nMaster-- > 0 && thisSID >= 0) {
+        // read a page of sector identifiers pointing to SAT sectors
+        gotoSector(thisSID);
+        for (int i = 0; i < nIntPerSector; i++)
+          MSAT[i] = readInt();
+        // read each page of SAT sector identifiers 
+        // last entry is pointer to next master sector allocation table page
+        for (int i = 0; i < nIntPerSector - 1; i++) {
+          thisSID = MSAT[i];
+          if (thisSID < 0)
+            break out;
+          gotoSector(thisSID);
+          for (int j = nIntPerSector; --j >= 0;)
+            SAT[nSID++] = readInt();
+        }
+        thisSID = MSAT[nIntPerSector - 1];
+      }
+    } catch (Exception e) {
+      System.out.println(e.toString());
+    }
+  }
+
+  private void getShortSectorAllocationTable() {
+    int nSSID = 0;
+    int thisSID = header.SID_SSAT_start;
+    int nMax = header.nSSATsectors * nIntPerSector;
+    SSAT = new int[nMax];
+    try {
+      while (thisSID > 0 && nSSID < nMax) {
+        gotoSector(thisSID);
+        for (int j = 0; j < nIntPerSector; j++) {
+          SSAT[nSSID++] = readInt();
+          //System.out.println("short: " + thisSID+"."+j+" SSID=" +(nSSID-1)+" "+SSAT[nSSID-1]);
+        }
+        thisSID = SAT[thisSID];
+      }
+    } catch (Exception e) {
+      System.out.println(e.toString());
+    }
+  }
+
+  private void getDirectoryTable() {
+    int thisSID = header.SID_DIR_start;
+    CompoundDocDirEntry thisEntry;
+    rootEntry = null;
+    try {
+      while (thisSID > 0) {
+        gotoSector(thisSID);
+        for (int j = nDirEntriesperSector; --j >= 0;) {
+          thisEntry = new CompoundDocDirEntry(this);
+          thisEntry.readData();
+          directory.addLast(thisEntry);
+          if (thisEntry.entryType == 5)
+            rootEntry = thisEntry;
+        }
+        thisSID = SAT[thisSID];
+      }
+    } catch (Exception e) {
+      System.out.println(e.toString());
+    }
+//    System.out.println("CompoundDocument directory entry: \n"
+//        + getDirectoryListing("\n"));
+  }
+
+  private SB getEntryAsString(CompoundDocDirEntry thisEntry, boolean asBinaryString) {
+    if(thisEntry.isEmpty)
+      return new SB();
+    //System.out.println(thisEntry.entryName + " " + thisEntry.entryType + " " + thisEntry.lenStream + " " + thisEntry.isStandard + " " + thisEntry.SIDfirstSector);
+    return (thisEntry.isStandard ? getStandardStringData(
+            thisEntry.SIDfirstSector, thisEntry.lenStream, asBinaryString)
+            : getShortStringData(thisEntry.SIDfirstSector, thisEntry.lenStream, asBinaryString));
+  }
+  private SB getStandardStringData(int thisSID, int nBytes,
+                                             boolean asBinaryString) {
+    SB data = new SB();
+    byte[] byteBuf = new byte[sectorSize];
+    ZipData gzipData = new ZipData(nBytes);
+    try {
+      while (thisSID > 0 && nBytes > 0) {
+        gotoSector(thisSID);
+        nBytes = getSectorData(data, byteBuf, sectorSize, nBytes, asBinaryString, gzipData);
+        thisSID = SAT[thisSID];
+      }
+      if (nBytes == -9999)
+        return new SB();
+    } catch (Exception e) {
+      System.out.println(e.toString());
+    }
+    if (gzipData.isEnabled)
+      gzipData.addTo(jzt, data);
+    return data;
+  }
+
+  private int getSectorData(SB data, byte[] byteBuf,
+                            int nSectorBytes, int nBytes, 
+                            boolean asBinaryString, ZipData gzipData)
+      throws Exception {
+    readByteArray(byteBuf, 0, byteBuf.length);
+    int n = gzipData.addBytes(byteBuf, nSectorBytes, nBytes);
+    if (n >= 0)
+      return n;
+    if (asBinaryString) {
+      for (int i = 0; i < nSectorBytes; i++) {
+        data.append(Integer.toHexString(byteBuf[i] & 0xFF)).appendC(' ');
+        if (--nBytes < 1)
+          break;
+      }
+    } else {
+      for (int i = 0; i < nSectorBytes; i++) {
+        if (byteBuf[i] == 0)
+          return -9999; // don't allow binary data
+        data.appendC((char) byteBuf[i]);
+        if (--nBytes < 1)
+          break;
+      }
+    }
+    return nBytes;
+  }
+
+  private SB getShortStringData(int shortSID, int nBytes, boolean asBinaryString) {
+    SB data = new SB();
+    if (rootEntry == null)
+      return data;
+    int thisSID = rootEntry.SIDfirstSector;
+    int ptShort = 0;
+    byte[] byteBuf = new byte[shortSectorSize];
+    ZipData gzipData = new ZipData(nBytes);
+    try {
+      //System.out.println("CD shortSID=" + shortSID);
+      // point to correct short data sector, 512/64 = 4 per page
+      while (thisSID >= 0 && shortSID >= 0 && nBytes > 0) {
+        while (shortSID - ptShort >= nShortSectorsPerStandardSector) {
+          ptShort += nShortSectorsPerStandardSector;
+          thisSID = SAT[thisSID];
+        }
+        seek(getOffset(thisSID) + (shortSID - ptShort) * shortSectorSize);
+        nBytes = getSectorData(data, byteBuf, shortSectorSize, nBytes, asBinaryString, gzipData);
+        shortSID = SSAT[shortSID];
+        //System.out.println("CD shortSID=" + shortSID);
+      }
+    } catch (Exception e) {
+      System.out.println(data.toString());
+      System.out.println("reader error in CompoundDocument " + e.toString());
+    }
+    if (gzipData.isEnabled)
+      gzipData.addTo(jzt, data);
+    return data;
+  }  
+}
diff --git a/src2/javajs/util/DF.java b/src2/javajs/util/DF.java
new file mode 100644 (file)
index 0000000..b5c8717
--- /dev/null
@@ -0,0 +1,174 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2007-04-26 16:57:51 -0500 (Thu, 26 Apr 2007) $
+ * $Revision: 7502 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package javajs.util;
+
+/**
+ * created to remove ambiguities and make a simpler DecimalFormat
+ */
+public class DF {
+
+  private final static String[] formattingStrings = { "0", "0.0", "0.00",
+      "0.000", "0.0000", "0.00000", "0.000000", "0.0000000", "0.00000000",
+      "0.000000000" };
+  private final static String zeros = "0000000000000000000000000000000000000000";
+
+  private final static float[] formatAdds = { 0.5f, 0.05f, 0.005f, 0.0005f,
+      0.00005f, 0.000005f, 0.0000005f, 0.00000005f, 0.000000005f, 0.0000000005f };
+
+  private final static Boolean[] useNumberLocalization = new Boolean[] { Boolean.TRUE };
+
+  public static void setUseNumberLocalization(boolean TF) {
+    useNumberLocalization[0] = (TF ? Boolean.TRUE : Boolean.FALSE);
+  }
+
+  public static String formatDecimalDbl(double value, int decimalDigits) {
+    if (decimalDigits == Integer.MAX_VALUE 
+        || value == Double.NEGATIVE_INFINITY
+        || value == Double.POSITIVE_INFINITY 
+        || Double.isNaN(value))
+      return "" + value;
+    return DF.formatDecimal((float) value, decimalDigits);
+  }
+
+  /**
+   * a simple alternative to DecimalFormat (which Java2Script does not have
+   * and which is quite too complex for our use here.)
+   * 
+   * @param value
+   * @param decimalDigits
+   * @return  formatted decimal
+   */
+  public static String formatDecimal(float value, int decimalDigits) {
+    if (decimalDigits == Integer.MAX_VALUE 
+        || value == Float.NEGATIVE_INFINITY || value == Float.POSITIVE_INFINITY || Float.isNaN(value))
+      return "" + value;
+    int n;
+    if (decimalDigits < 0) {
+      decimalDigits = -decimalDigits;
+      if (decimalDigits > formattingStrings.length)
+        decimalDigits = formattingStrings.length;
+      if (value == 0)
+        return formattingStrings[decimalDigits - 1] + "E+0";
+      //scientific notation
+      n = 0;
+      double d;
+      if (Math.abs(value) < 1) {
+        n = 10;
+        d = value * 1e-10;
+      } else {
+        n = -10;
+        d = value * 1e10;
+      }
+      String s = ("" + d).toUpperCase();
+      int i = s.indexOf("E");
+      n = PT.parseInt(s.substring(i + 1)) + n;
+      String sf;
+      if (i < 0) {
+        sf = "" + value;
+      } else {
+        float f = PT.parseFloat(s.substring(0, i));
+        if (f == 10 || f == -10) {
+          //d = 9.99999997465; n = -6 --> 10.00000E-5
+          f /= 10;
+          n += (n < 0 ? 1 : -1);          
+        }
+        sf = formatDecimal(f, decimalDigits - 1);
+      }
+      return sf  + "E" + (n >= 0 ? "+" : "") + n;
+    }
+  
+    if (decimalDigits >= formattingStrings.length)
+      decimalDigits = formattingStrings.length - 1;
+    String s1 = ("" + value).toUpperCase();
+    int pt = s1.indexOf(".");
+    if (pt < 0) // specifically JavaScript "-2" not "-2.0"
+      return s1 + formattingStrings[decimalDigits].substring(1);
+    boolean isNeg = s1.startsWith("-");
+    if (isNeg) {
+      s1 = s1.substring(1);
+      pt--;
+    }
+    int pt1 = s1.indexOf("E-");
+    if (pt1 > 0) {
+      n = PT.parseInt(s1.substring(pt1 + 1));
+      // 3.567E-2
+      // 0.03567
+      s1 = "0." + zeros.substring(0, -n - 1) + s1.substring(0, 1) + s1.substring(2, pt1);
+      pt = 1; 
+    }
+  
+    pt1 = s1.indexOf("E");
+    // 3.5678E+3
+    // 3567.800000000
+    // 1.234E10 %3.8f -> 12340000000.00000000
+    if (pt1 > 0) {
+      n = PT.parseInt(s1.substring(pt1 + 1));
+      s1 = s1.substring(0, 1) + s1.substring(2, pt1) + zeros;
+      s1 = s1.substring(0, n + 1) + "." + s1.substring(n + 1);
+      pt = s1.indexOf(".");
+    } 
+    // "234.345667  len == 10; pt = 3
+    // "  0.0 "  decimalDigits = 1
+    
+    int len = s1.length();
+    int pt2 = decimalDigits + pt + 1;
+    if (pt2 < len && s1.charAt(pt2) >= '5') {
+      return formatDecimal(
+          value + (isNeg ? -1 : 1) * formatAdds[decimalDigits], decimalDigits);
+    }
+  
+    SB sb = SB.newS(s1.substring(0, (decimalDigits == 0 ? pt
+        : ++pt)));
+    for (int i = 0; i < decimalDigits; i++, pt++) {
+      if (pt < len)
+        sb.appendC(s1.charAt(pt));
+      else
+        sb.appendC('0');
+    }
+    s1 = (isNeg ? "-" : "") + sb;
+    return (Boolean.TRUE.equals(useNumberLocalization[0]) ? s1 : s1.replace(',',
+        '.'));
+  }
+
+  /**
+   * an alternative to DecimalFormat "0.#"
+   * 
+   * @param x
+   * @param precision
+   * @return  formatted number 
+   */
+  public static String formatDecimalTrimmed(double x, int precision) {
+    String str = formatDecimalDbl(x, precision);
+    int m = str.length() - 1;
+    char zero = '0';
+    while (m >= 0 && str.charAt(m) == zero)
+      m--;
+    return str.substring(0, m + 1); // 0.##...
+  }
+
+}
diff --git a/src2/javajs/util/DataReader.java b/src2/javajs/util/DataReader.java
new file mode 100644 (file)
index 0000000..1eb8ade
--- /dev/null
@@ -0,0 +1,56 @@
+package javajs.util;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+
+/**
+ * Just a simple abstract class to join a String reader and a String[]
+ * reader under the same BufferedReader umbrella.
+ * 
+ * Subclassed as StringDataReader, ArrayDataReader, and ListDataReader
+ * 
+ */
+
+public abstract class DataReader extends BufferedReader {
+
+  public abstract DataReader setData(Object data);
+  
+  protected int ptMark;
+
+  public DataReader() {
+    super(new StringReader(""));
+  }
+
+  protected DataReader(Reader in) {
+    super(in);
+  }
+
+  public BufferedReader getBufferedReader() {
+    return this;
+  }
+
+  protected int readBuf(char[] buf, int off, int len) throws IOException {
+    // not used by StringDataReader
+    int nRead = 0;
+    String line = readLine();
+    if (line == null)
+      return 0;
+    int linept = 0;
+    int linelen = line.length();
+    for (int i = off; i < len && linelen >= 0; i++) {
+      if (linept >= linelen) {
+        linept = 0;
+        buf[i] = '\n';
+        line = readLine();
+        linelen = (line == null ? -1 : line.length());
+      } else {
+        buf[i] = line.charAt(linept++);
+      }
+      nRead++;
+    }
+    return nRead;
+  }
+
+}
\ No newline at end of file
diff --git a/src2/javajs/util/DebugJS.java b/src2/javajs/util/DebugJS.java
new file mode 100644 (file)
index 0000000..ab22558
--- /dev/null
@@ -0,0 +1,28 @@
+package javajs.util;
+
+/**
+ * A class to insert a JavaScript debug statement for Firefox or Chrome debugger
+ * 
+ */
+
+public class DebugJS {
+
+       /**
+        * Insert a JavaScript debug statement
+        * 
+        */
+                public static void _(String msg) {
+               /**
+                * @j2sNative
+                * 
+                * if (Clazz._debugging) {
+                * 
+                * debugger;
+                * 
+                * }
+                * 
+                */
+               {}
+       }
+
+}
diff --git a/src2/javajs/util/Eigen.java b/src2/javajs/util/Eigen.java
new file mode 100644 (file)
index 0000000..52736c0
--- /dev/null
@@ -0,0 +1,1063 @@
+/* $RCSfile$
+ * $Author: egonw $
+ * $Date: 2005-11-10 09:52:44f -0600 (Thu, 10 Nov 2005) $
+ * $Revision: 4255 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2003-2005  Miguel, Jmol Development, www.jmol.org
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package javajs.util;
+
+import javajs.api.EigenInterface;
+
+
+/**
+ * Eigenvalues and eigenvectors of a real matrix.
+ * See javajs.api.EigenInterface() as well.
+ * 
+ * adapted by Bob Hanson from http://math.nist.gov/javanumerics/jama/ (public
+ * domain); adding quaternion superimposition capability; removing
+ * nonsymmetric reduction to Hessenberg form, which we do not need in Jmol.
+ * 
+ * Output is as a set of double[n] columns, but for the EigenInterface
+ * we return them as V3[3] and float[3] (or double[3]) values.
+ * 
+ * Eigenvalues and eigenvectors are sorted from smallest to largest eigenvalue.
+ * 
+ * <P>
+ * If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is diagonal
+ * and the eigenvector matrix V is orthogonal. I.e. A =
+ * V.times(D.times(V.transpose())) and V.times(V.transpose()) equals the
+ * identity matrix.
+ * <P>
+ * If A is not symmetric, then the eigenvalue matrix D is block diagonal with
+ * the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, lambda +
+ * i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The columns of V represent
+ * the eigenvectors in the sense that A*V = V*D, i.e. A.times(V) equals
+ * V.times(D). The matrix V may be badly conditioned, or even singular, so the
+ * validity of the equation A = V*D*inverse(V) depends upon V.cond().
+ **/
+
+public class Eigen implements EigenInterface {
+
+  /* ------------------------
+  Public Methods
+  * ------------------------ */
+
+  public Eigen() {}
+  
+  public Eigen set(int n) {
+    this.n = n;
+    V = new double[n][n];
+    d = new double[n];
+    e = new double[n];
+    return this;
+  }
+
+  @Override
+  public Eigen setM(double[][] m) {
+    set(m.length);
+    calc(m);
+    return this;
+  }
+
+  /**
+   * return values sorted from smallest to largest value.
+   */
+  @Override
+  public double[] getEigenvalues() {
+    return d;
+  }
+
+  /**
+   * Specifically for 3x3 systems, returns eigenVectors as V3[3]
+   * and values as float[3]; sorted from smallest to largest value.
+   * 
+   * @param eigenVectors  returned vectors
+   * @param eigenValues   returned values
+   * 
+   */
+  @Override
+  public void fillFloatArrays(V3[] eigenVectors, float[] eigenValues) {
+    for (int i = 0; i < 3; i++) {
+      if (eigenVectors != null) {
+        if (eigenVectors[i] == null)
+          eigenVectors[i] = new V3();
+        eigenVectors[i].set((float) V[0][i], (float) V[1][i], (float) V[2][i]);
+      }
+      if (eigenValues != null)
+        eigenValues[i] = (float) d[i];
+    }
+  }
+
+  /**
+   * Transpose V and turn into floats; sorted from smallest to largest value.
+   * 
+   * @return ROWS of eigenvectors f[0], f[1], f[2], etc.
+   */
+  @Override
+  public float[][] getEigenvectorsFloatTransposed() {
+    float[][] f = new float[n][n];
+    for (int i = n; --i >= 0;)
+      for (int j = n; --j >= 0;)
+        f[j][i] = (float) V[i][j];
+    return f;
+  }
+
+
+  /**
+   * Check for symmetry, then construct the eigenvalue decomposition
+   * 
+   * @param A
+   *        Square matrix
+   */
+
+  public void calc(double[][] A) {
+
+    /* Jmol only has need of symmetric solutions 
+     * 
+    issymmetric = true;
+    
+    for (int j = 0; (j < n) & issymmetric; j++) {
+      for (int i = 0; (i < n) & issymmetric; i++) {
+        issymmetric = (A[i][j] == A[j][i]);
+      }
+    }
+
+    if (issymmetric) {
+     */
+    for (int i = 0; i < n; i++) {
+      for (int j = 0; j < n; j++) {
+        V[i][j] = A[i][j];
+      }
+    }
+
+    // Tridiagonalize.
+    tred2();
+
+    // Diagonalize.
+    tql2();
+    /*
+      } else {
+        H = new double[n][n];
+        ort = new double[n];
+
+        for (int j = 0; j < n; j++) {
+          for (int i = 0; i < n; i++) {
+            H[i][j] = A[i][j];
+          }
+        }
+
+        // Reduce to Hessenberg form.
+        orthes();
+
+        // Reduce Hessenberg to real Schur form.
+        hqr2();
+      }
+    */
+
+  }
+
+  /**
+   * Return the real parts of the eigenvalues
+   * 
+   * @return real(diag(D))
+   */
+
+  public double[] getRealEigenvalues() {
+    return d;
+  }
+
+  /**
+   * Return the imaginary parts of the eigenvalues
+   * 
+   * @return imag(diag(D))
+   */
+
+  public double[] getImagEigenvalues() {
+    return e;
+  }
+
+  /* ------------------------
+     Class variables
+   * ------------------------ */
+
+  /**
+   * Row and column dimension (square matrix).
+   * 
+   * @serial matrix dimension.
+   */
+  private int n = 3;
+
+  /**
+   * Symmetry flag.
+   * 
+   * @serial internal symmetry flag.
+   */
+  //private boolean issymmetric = true;
+
+  /**
+   * Arrays for internal storage of eigenvalues.
+   * 
+   * @serial internal storage of eigenvalues.
+   */
+  private double[] d, e;
+
+  /**
+   * Array for internal storage of eigenvectors.
+   * 
+   * @serial internal storage of eigenvectors.
+   */
+  private double[][] V;
+
+  /**
+   * Array for internal storage of nonsymmetric Hessenberg form.
+   * 
+   * @serial internal storage of nonsymmetric Hessenberg form.
+   */
+  //private double[][] H;
+
+  /**
+   * Working storage for nonsymmetric algorithm.
+   * 
+   * @serial working storage for nonsymmetric algorithm.
+   */
+  //private double[] ort;
+
+  /* ------------------------
+     Private Methods
+   * ------------------------ */
+
+  // Symmetric Householder reduction to tridiagonal form.
+
+  private void tred2() {
+
+    //  This is derived from the Algol procedures tred2 by
+    //  Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
+    //  Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
+    //  Fortran subroutine in EISPACK.
+
+    for (int j = 0; j < n; j++) {
+      d[j] = V[n - 1][j];
+    }
+
+    // Householder reduction to tridiagonal form.
+
+    for (int i = n - 1; i > 0; i--) {
+
+      // Scale to avoid under/overflow.
+
+      double scale = 0.0;
+      double h = 0.0;
+      for (int k = 0; k < i; k++) {
+        scale = scale + Math.abs(d[k]);
+      }
+      if (scale == 0.0) {
+        e[i] = d[i - 1];
+        for (int j = 0; j < i; j++) {
+          d[j] = V[i - 1][j];
+          V[i][j] = 0.0;
+          V[j][i] = 0.0;
+        }
+      } else {
+
+        // Generate Householder vector.
+
+        for (int k = 0; k < i; k++) {
+          d[k] /= scale;
+          h += d[k] * d[k];
+        }
+        double f = d[i - 1];
+        double g = Math.sqrt(h);
+        if (f > 0) {
+          g = -g;
+        }
+        e[i] = scale * g;
+        h = h - f * g;
+        d[i - 1] = f - g;
+        for (int j = 0; j < i; j++) {
+          e[j] = 0.0;
+        }
+
+        // Apply similarity transformation to remaining columns.
+
+        for (int j = 0; j < i; j++) {
+          f = d[j];
+          V[j][i] = f;
+          g = e[j] + V[j][j] * f;
+          for (int k = j + 1; k <= i - 1; k++) {
+            g += V[k][j] * d[k];
+            e[k] += V[k][j] * f;
+          }
+          e[j] = g;
+        }
+        f = 0.0;
+        for (int j = 0; j < i; j++) {
+          e[j] /= h;
+          f += e[j] * d[j];
+        }
+        double hh = f / (h + h);
+        for (int j = 0; j < i; j++) {
+          e[j] -= hh * d[j];
+        }
+        for (int j = 0; j < i; j++) {
+          f = d[j];
+          g = e[j];
+          for (int k = j; k <= i - 1; k++) {
+            V[k][j] -= (f * e[k] + g * d[k]);
+          }
+          d[j] = V[i - 1][j];
+          V[i][j] = 0.0;
+        }
+      }
+      d[i] = h;
+    }
+
+    // Accumulate transformations.
+
+    for (int i = 0; i < n - 1; i++) {
+      V[n - 1][i] = V[i][i];
+      V[i][i] = 1.0;
+      double h = d[i + 1];
+      if (h != 0.0) {
+        for (int k = 0; k <= i; k++) {
+          d[k] = V[k][i + 1] / h;
+        }
+        for (int j = 0; j <= i; j++) {
+          double g = 0.0;
+          for (int k = 0; k <= i; k++) {
+            g += V[k][i + 1] * V[k][j];
+          }
+          for (int k = 0; k <= i; k++) {
+            V[k][j] -= g * d[k];
+          }
+        }
+      }
+      for (int k = 0; k <= i; k++) {
+        V[k][i + 1] = 0.0;
+      }
+    }
+    for (int j = 0; j < n; j++) {
+      d[j] = V[n - 1][j];
+      V[n - 1][j] = 0.0;
+    }
+    V[n - 1][n - 1] = 1.0;
+    e[0] = 0.0;
+  }
+
+  // Symmetric tridiagonal QL algorithm.
+
+  private void tql2() {
+
+    //  This is derived from the Algol procedures tql2, by
+    //  Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
+    //  Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
+    //  Fortran subroutine in EISPACK.
+
+    for (int i = 1; i < n; i++) {
+      e[i - 1] = e[i];
+    }
+    e[n - 1] = 0.0;
+
+    double f = 0.0;
+    double tst1 = 0.0;
+    double eps = Math.pow(2.0, -52.0);
+    for (int l = 0; l < n; l++) {
+
+      // Find small subdiagonal element
+
+      tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));
+      int m = l;
+      while (m < n) {
+        if (Math.abs(e[m]) <= eps * tst1) {
+          break;
+        }
+        m++;
+      }
+
+      // If m == l, d[l] is an eigenvalue,
+      // otherwise, iterate.
+
+      if (m > l) {
+        int iter = 0;
+        do {
+          iter = iter + 1; // (Could check iteration count here.)
+
+          // Compute implicit shift
+
+          double g = d[l];
+          double p = (d[l + 1] - g) / (2.0 * e[l]);
+          double r = hypot(p, 1.0);
+          if (p < 0) {
+            r = -r;
+          }
+          d[l] = e[l] / (p + r);
+          d[l + 1] = e[l] * (p + r);
+          double dl1 = d[l + 1];
+          double h = g - d[l];
+          for (int i = l + 2; i < n; i++) {
+            d[i] -= h;
+          }
+          f = f + h;
+
+          // Implicit QL transformation.
+
+          p = d[m];
+          double c = 1.0;
+          double c2 = c;
+          double c3 = c;
+          double el1 = e[l + 1];
+          double s = 0.0;
+          double s2 = 0.0;
+          for (int i = m - 1; i >= l; i--) {
+            c3 = c2;
+            c2 = c;
+            s2 = s;
+            g = c * e[i];
+            h = c * p;
+            r = hypot(p, e[i]);
+            e[i + 1] = s * r;
+            s = e[i] / r;
+            c = p / r;
+            p = c * d[i] - s * g;
+            d[i + 1] = h + s * (c * g + s * d[i]);
+
+            // Accumulate transformation.
+
+            for (int k = 0; k < n; k++) {
+              h = V[k][i + 1];
+              V[k][i + 1] = s * V[k][i] + c * h;
+              V[k][i] = c * V[k][i] - s * h;
+            }
+          }
+          p = -s * s2 * c3 * el1 * e[l] / dl1;
+          e[l] = s * p;
+          d[l] = c * p;
+
+          // Check for convergence.
+
+        } while (Math.abs(e[l]) > eps * tst1);
+      }
+      d[l] = d[l] + f;
+      e[l] = 0.0;
+    }
+
+    // Sort eigenvalues and corresponding vectors.
+
+    for (int i = 0; i < n - 1; i++) {
+      int k = i;
+      double p = d[i];
+      for (int j = i + 1; j < n; j++) {
+        if (d[j] < p) {
+          k = j;
+          p = d[j];
+        }
+      }
+      if (k != i) {
+        d[k] = d[i];
+        d[i] = p;
+        for (int j = 0; j < n; j++) {
+          p = V[j][i];
+          V[j][i] = V[j][k];
+          V[j][k] = p;
+        }
+      }
+    }
+  }
+
+  private static double hypot(double a, double b) {
+
+    // sqrt(a^2 + b^2) without under/overflow. 
+
+    double r;
+    if (Math.abs(a) > Math.abs(b)) {
+      r = b / a;
+      r = Math.abs(a) * Math.sqrt(1 + r * r);
+    } else if (b != 0) {
+      r = a / b;
+      r = Math.abs(b) * Math.sqrt(1 + r * r);
+    } else {
+      r = 0.0;
+    }
+    return r;
+  }
+
+  // Nonsymmetric reduction to Hessenberg form.
+
+  /*
+  private void orthes() {
+
+    //  This is derived from the Algol procedures orthes and ortran,
+    //  by Martin and Wilkinson, Handbook for Auto. Comp.,
+    //  Vol.ii-Linear Algebra, and the corresponding
+    //  Fortran subroutines in EISPACK.
+
+    int low = 0;
+    int high = n - 1;
+
+    for (int m = low + 1; m <= high - 1; m++) {
+
+      // Scale column.
+
+      double scale = 0.0;
+      for (int i = m; i <= high; i++) {
+        scale = scale + Math.abs(H[i][m - 1]);
+      }
+      if (scale != 0.0) {
+
+        // Compute Householder transformation.
+
+        double h = 0.0;
+        for (int i = high; i >= m; i--) {
+          ort[i] = H[i][m - 1] / scale;
+          h += ort[i] * ort[i];
+        }
+        double g = Math.sqrt(h);
+        if (ort[m] > 0) {
+          g = -g;
+        }
+        h = h - ort[m] * g;
+        ort[m] = ort[m] - g;
+
+        // Apply Householder similarity transformation
+        // H = (I-u*u'/h)*H*(I-u*u')/h)
+
+        for (int j = m; j < n; j++) {
+          double f = 0.0;
+          for (int i = high; i >= m; i--) {
+            f += ort[i] * H[i][j];
+          }
+          f = f / h;
+          for (int i = m; i <= high; i++) {
+            H[i][j] -= f * ort[i];
+          }
+        }
+
+        for (int i = 0; i <= high; i++) {
+          double f = 0.0;
+          for (int j = high; j >= m; j--) {
+            f += ort[j] * H[i][j];
+          }
+          f = f / h;
+          for (int j = m; j <= high; j++) {
+            H[i][j] -= f * ort[j];
+          }
+        }
+        ort[m] = scale * ort[m];
+        H[m][m - 1] = scale * g;
+      }
+    }
+
+    // Accumulate transformations (Algol's ortran).
+
+    for (int i = 0; i < n; i++) {
+      for (int j = 0; j < n; j++) {
+        V[i][j] = (i == j ? 1.0 : 0.0);
+      }
+    }
+
+    for (int m = high - 1; m >= low + 1; m--) {
+      if (H[m][m - 1] != 0.0) {
+        for (int i = m + 1; i <= high; i++) {
+          ort[i] = H[i][m - 1];
+        }
+        for (int j = m; j <= high; j++) {
+          double g = 0.0;
+          for (int i = m; i <= high; i++) {
+            g += ort[i] * V[i][j];
+          }
+          // Double division avoids possible underflow
+          g = (g / ort[m]) / H[m][m - 1];
+          for (int i = m; i <= high; i++) {
+            V[i][j] += g * ort[i];
+          }
+        }
+      }
+    }
+  }
+
+  // Complex scalar division.
+
+  private transient double cdivr, cdivi;
+
+  private void cdiv(double xr, double xi, double yr, double yi) {
+    double r, d;
+    if (Math.abs(yr) > Math.abs(yi)) {
+      r = yi / yr;
+      d = yr + r * yi;
+      cdivr = (xr + r * xi) / d;
+      cdivi = (xi - r * xr) / d;
+    } else {
+      r = yr / yi;
+      d = yi + r * yr;
+      cdivr = (r * xr + xi) / d;
+      cdivi = (r * xi - xr) / d;
+    }
+  }
+
+  // Nonsymmetric reduction from Hessenberg to real Schur form.
+
+  private void hqr2() {
+
+    //  This is derived from the Algol procedure hqr2,
+    //  by Martin and Wilkinson, Handbook for Auto. Comp.,
+    //  Vol.ii-Linear Algebra, and the corresponding
+    //  Fortran subroutine in EISPACK.
+
+    // Initialize
+
+    int nn = this.n;
+    int n = nn - 1;
+    int low = 0;
+    int high = nn - 1;
+    double eps = Math.pow(2.0, -52.0);
+    double exshift = 0.0;
+    double p = 0, q = 0, r = 0, s = 0, z = 0, t, w, x, y;
+
+    // Store roots isolated by balanc and compute matrix norm
+
+    double norm = 0.0;
+    for (int i = 0; i < nn; i++) {
+      if (i < low || i > high) {
+        d[i] = H[i][i];
+        e[i] = 0.0;
+      }
+      for (int j = Math.max(i - 1, 0); j < nn; j++) {
+        norm = norm + Math.abs(H[i][j]);
+      }
+    }
+
+    // Outer loop over eigenvalue index
+
+    int iter = 0;
+    while (n >= low) {
+
+      // Look for single small sub-diagonal element
+
+      int l = n;
+      while (l > low) {
+        s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]);
+        if (s == 0.0) {
+          s = norm;
+        }
+        if (Math.abs(H[l][l - 1]) < eps * s) {
+          break;
+        }
+        l--;
+      }
+
+      // Check for convergence
+      // One root found
+
+      if (l == n) {
+        H[n][n] = H[n][n] + exshift;
+        d[n] = H[n][n];
+        e[n] = 0.0;
+        n--;
+        iter = 0;
+
+        // Two roots found
+
+      } else if (l == n - 1) {
+        w = H[n][n - 1] * H[n - 1][n];
+        p = (H[n - 1][n - 1] - H[n][n]) / 2.0;
+        q = p * p + w;
+        z = Math.sqrt(Math.abs(q));
+        H[n][n] = H[n][n] + exshift;
+        H[n - 1][n - 1] = H[n - 1][n - 1] + exshift;
+        x = H[n][n];
+
+        // Real pair
+
+        if (q >= 0) {
+          if (p >= 0) {
+            z = p + z;
+          } else {
+            z = p - z;
+          }
+          d[n - 1] = x + z;
+          d[n] = d[n - 1];
+          if (z != 0.0) {
+            d[n] = x - w / z;
+          }
+          e[n - 1] = 0.0;
+          e[n] = 0.0;
+          x = H[n][n - 1];
+          s = Math.abs(x) + Math.abs(z);
+          p = x / s;
+          q = z / s;
+          r = Math.sqrt(p * p + q * q);
+          p = p / r;
+          q = q / r;
+
+          // Row modification
+
+          for (int j = n - 1; j < nn; j++) {
+            z = H[n - 1][j];
+            H[n - 1][j] = q * z + p * H[n][j];
+            H[n][j] = q * H[n][j] - p * z;
+          }
+
+          // Column modification
+
+          for (int i = 0; i <= n; i++) {
+            z = H[i][n - 1];
+            H[i][n - 1] = q * z + p * H[i][n];
+            H[i][n] = q * H[i][n] - p * z;
+          }
+
+          // Accumulate transformations
+
+          for (int i = low; i <= high; i++) {
+            z = V[i][n - 1];
+            V[i][n - 1] = q * z + p * V[i][n];
+            V[i][n] = q * V[i][n] - p * z;
+          }
+
+          // Complex pair
+
+        } else {
+          d[n - 1] = x + p;
+          d[n] = x + p;
+          e[n - 1] = z;
+          e[n] = -z;
+        }
+        n = n - 2;
+        iter = 0;
+
+        // No convergence yet
+
+      } else {
+
+        // Form shift
+
+        x = H[n][n];
+        y = 0.0;
+        w = 0.0;
+        if (l < n) {
+          y = H[n - 1][n - 1];
+          w = H[n][n - 1] * H[n - 1][n];
+        }
+
+        // Wilkinson's original ad hoc shift
+
+        if (iter == 10) {
+          exshift += x;
+          for (int i = low; i <= n; i++) {
+            H[i][i] -= x;
+          }
+          s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]);
+          x = y = 0.75 * s;
+          w = -0.4375 * s * s;
+        }
+
+        // MATLAB's new ad hoc shift
+
+        if (iter == 30) {
+          s = (y - x) / 2.0;
+          s = s * s + w;
+          if (s > 0) {
+            s = Math.sqrt(s);
+            if (y < x) {
+              s = -s;
+            }
+            s = x - w / ((y - x) / 2.0 + s);
+            for (int i = low; i <= n; i++) {
+              H[i][i] -= s;
+            }
+            exshift += s;
+            x = y = w = 0.964;
+          }
+        }
+
+        iter = iter + 1; // (Could check iteration count here.)
+
+        // Look for two consecutive small sub-diagonal elements
+
+        int m = n - 2;
+        while (m >= l) {
+          z = H[m][m];
+          r = x - z;
+          s = y - z;
+          p = (r * s - w) / H[m + 1][m] + H[m][m + 1];
+          q = H[m + 1][m + 1] - z - r - s;
+          r = H[m + 2][m + 1];
+          s = Math.abs(p) + Math.abs(q) + Math.abs(r);
+          p = p / s;
+          q = q / s;
+          r = r / s;
+          if (m == l) {
+            break;
+          }
+          if (Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r)) < eps
+              * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math
+                  .abs(H[m + 1][m + 1])))) {
+            break;
+          }
+          m--;
+        }
+
+        for (int i = m + 2; i <= n; i++) {
+          H[i][i - 2] = 0.0;
+          if (i > m + 2) {
+            H[i][i - 3] = 0.0;
+          }
+        }
+
+        // Double QR step involving rows l:n and columns m:n
+
+        for (int k = m; k <= n - 1; k++) {
+          boolean notlast = (k != n - 1);
+          if (k != m) {
+            p = H[k][k - 1];
+            q = H[k + 1][k - 1];
+            r = (notlast ? H[k + 2][k - 1] : 0.0);
+            x = Math.abs(p) + Math.abs(q) + Math.abs(r);
+            if (x != 0.0) {
+              p = p / x;
+              q = q / x;
+              r = r / x;
+            }
+          }
+          if (x == 0.0) {
+            break;
+          }
+          s = Math.sqrt(p * p + q * q + r * r);
+          if (p < 0) {
+            s = -s;
+          }
+          if (s != 0) {
+            if (k != m) {
+              H[k][k - 1] = -s * x;
+            } else if (l != m) {
+              H[k][k - 1] = -H[k][k - 1];
+            }
+            p = p + s;
+            x = p / s;
+            y = q / s;
+            z = r / s;
+            q = q / p;
+            r = r / p;
+
+            // Row modification
+
+            for (int j = k; j < nn; j++) {
+              p = H[k][j] + q * H[k + 1][j];
+              if (notlast) {
+                p = p + r * H[k + 2][j];
+                H[k + 2][j] = H[k + 2][j] - p * z;
+              }
+              H[k][j] = H[k][j] - p * x;
+              H[k + 1][j] = H[k + 1][j] - p * y;
+            }
+
+            // Column modification
+
+            for (int i = 0; i <= Math.min(n, k + 3); i++) {
+              p = x * H[i][k] + y * H[i][k + 1];
+              if (notlast) {
+                p = p + z * H[i][k + 2];
+                H[i][k + 2] = H[i][k + 2] - p * r;
+              }
+              H[i][k] = H[i][k] - p;
+              H[i][k + 1] = H[i][k + 1] - p * q;
+            }
+
+            // Accumulate transformations
+
+            for (int i = low; i <= high; i++) {
+              p = x * V[i][k] + y * V[i][k + 1];
+              if (notlast) {
+                p = p + z * V[i][k + 2];
+                V[i][k + 2] = V[i][k + 2] - p * r;
+              }
+              V[i][k] = V[i][k] - p;
+              V[i][k + 1] = V[i][k + 1] - p * q;
+            }
+          } // (s != 0)
+        } // k loop
+      } // check convergence
+    } // while (n >= low)
+
+    // Backsubstitute to find vectors of upper triangular form
+
+    if (norm == 0.0) {
+      return;
+    }
+
+    for (n = nn - 1; n >= 0; n--) {
+      p = d[n];
+      q = e[n];
+
+      // Real vector
+
+      if (q == 0) {
+        int l = n;
+        H[n][n] = 1.0;
+        for (int i = n - 1; i >= 0; i--) {
+          w = H[i][i] - p;
+          r = 0.0;
+          for (int j = l; j <= n; j++) {
+            r = r + H[i][j] * H[j][n];
+          }
+          if (e[i] < 0.0) {
+            z = w;
+            s = r;
+          } else {
+            l = i;
+            if (e[i] == 0.0) {
+              if (w != 0.0) {
+                H[i][n] = -r / w;
+              } else {
+                H[i][n] = -r / (eps * norm);
+              }
+
+              // Solve real equations
+
+            } else {
+              x = H[i][i + 1];
+              y = H[i + 1][i];
+              q = (d[i] - p) * (d[i] - p) + e[i] * e[i];
+              t = (x * s - z * r) / q;
+              H[i][n] = t;
+              if (Math.abs(x) > Math.abs(z)) {
+                H[i + 1][n] = (-r - w * t) / x;
+              } else {
+                H[i + 1][n] = (-s - y * t) / z;
+              }
+            }
+
+            // Overflow control
+
+            t = Math.abs(H[i][n]);
+            if ((eps * t) * t > 1) {
+              for (int j = i; j <= n; j++) {
+                H[j][n] = H[j][n] / t;
+              }
+            }
+          }
+        }
+
+        // Complex vector
+
+      } else if (q < 0) {
+        int l = n - 1;
+
+        // Last vector component imaginary so matrix is triangular
+
+        if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) {
+          H[n - 1][n - 1] = q / H[n][n - 1];
+          H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1];
+        } else {
+          cdiv(0.0, -H[n - 1][n], H[n - 1][n - 1] - p, q);
+          H[n - 1][n - 1] = cdivr;
+          H[n - 1][n] = cdivi;
+        }
+        H[n][n - 1] = 0.0;
+        H[n][n] = 1.0;
+        for (int i = n - 2; i >= 0; i--) {
+          double ra, sa, vr, vi;
+          ra = 0.0;
+          sa = 0.0;
+          for (int j = l; j <= n; j++) {
+            ra = ra + H[i][j] * H[j][n - 1];
+            sa = sa + H[i][j] * H[j][n];
+          }
+          w = H[i][i] - p;
+
+          if (e[i] < 0.0) {
+            z = w;
+            r = ra;
+            s = sa;
+          } else {
+            l = i;
+            if (e[i] == 0) {
+              cdiv(-ra, -sa, w, q);
+              H[i][n - 1] = cdivr;
+              H[i][n] = cdivi;
+            } else {
+
+              // Solve complex equations
+
+              x = H[i][i + 1];
+              y = H[i + 1][i];
+              vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;
+              vi = (d[i] - p) * 2.0 * q;
+              if (vr == 0.0 & vi == 0.0) {
+                vr = eps
+                    * norm
+                    * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math
+                        .abs(z));
+              }
+              cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);
+              H[i][n - 1] = cdivr;
+              H[i][n] = cdivi;
+              if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) {
+                H[i + 1][n - 1] = (-ra - w * H[i][n - 1] + q * H[i][n]) / x;
+                H[i + 1][n] = (-sa - w * H[i][n] - q * H[i][n - 1]) / x;
+              } else {
+                cdiv(-r - y * H[i][n - 1], -s - y * H[i][n], z, q);
+                H[i + 1][n - 1] = cdivr;
+                H[i + 1][n] = cdivi;
+              }
+            }
+
+            // Overflow control
+
+            t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n]));
+            if ((eps * t) * t > 1) {
+              for (int j = i; j <= n; j++) {
+                H[j][n - 1] = H[j][n - 1] / t;
+                H[j][n] = H[j][n] / t;
+              }
+            }
+          }
+        }
+      }
+    }
+
+    // Vectors of isolated roots
+
+    for (int i = 0; i < nn; i++) {
+      if (i < low || i > high) {
+        for (int j = i; j < nn; j++) {
+          V[i][j] = H[i][j];
+        }
+      }
+    }
+
+    // Back transformation to get eigenvectors of original matrix
+
+    for (int j = nn - 1; j >= low; j--) {
+      for (int i = low; i <= high; i++) {
+        z = 0.0;
+        for (int k = low; k <= Math.min(j, high); k++) {
+          z = z + V[i][k] * H[k][j];
+        }
+        V[i][j] = z;
+      }
+    }
+  }
+     */
+
+
+}
diff --git a/src2/javajs/util/Encoding.java b/src2/javajs/util/Encoding.java
new file mode 100644 (file)
index 0000000..8d1a9a7
--- /dev/null
@@ -0,0 +1,33 @@
+/* $RCSfile$
+ * $Author$
+ * $Date$
+ * $Revision$
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2011  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301, USA.
+ */
+
+package javajs.util;
+
+public enum Encoding {
+  NONE, UTF8, UTF_16BE, UTF_16LE, UTF_32BE, UTF_32LE
+}
\ No newline at end of file
diff --git a/src2/javajs/util/JSAudioThread.java b/src2/javajs/util/JSAudioThread.java
new file mode 100644 (file)
index 0000000..3bcb006
--- /dev/null
@@ -0,0 +1,258 @@
+package javajs.util;   
+
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioSystem;
+import javax.sound.sampled.DataLine;
+import javax.sound.sampled.SourceDataLine;
+
+import sun.audio.AudioData;
+import sun.audio.AudioDataStream;
+import sun.audio.AudioPlayer;
+
+
+/**
+ * The JSAudioThread adds a layer to JSThread that is specific for audio.
+ * This class utilizes JSAudioLine, which is not fully fleshed out.
+ * 
+ * Two very simple interfaces,
+ * 
+ * (new JSAudioThread()).playULawData(byte[] b);
+ * 
+ * and
+ * 
+ * (new JSAudioThread(audioFormat)).playOnce(byte[] b, offset, length);
+ * 
+ * allow straightforward audio production without having to work with
+ * SourceDataLine directly.
+ * 
+ * As a JSThread, this class implements myInit(), isLooping(), myLoop(),
+ * whenDone(), onException(), and doFinally().
+ * 
+ * If the constructor JSAudioThread(JSAudioThreadUser, AudioFormat, byte[]) is
+ * used, then the JSAudioThreadUser must simply implement fillAudioBuffer(),
+ * checkSoundStatus(), and audioThreadExiting() for very simple streaming audio.
+ * JSAudioThread will then take care of all the timing issues.
+ * 
+ * But the implementer is welcome to override any of the JSThread overrides
+ * themselves in order to customize this further.
+ * 
+ * The standard streaming case, then is:
+ * 
+ * audioThread = new JSAudioThread(audioUser, audioFormat, audioByteBuffer);
+ * audioThread.start();
+ * 
+ * where audioUser provides 
+ * 
+ * checkSoundStatus() (called in isLooping()),
+ * 
+ * fillAudioBuffer() (called in myLoop()),
+ * 
+ * and
+ * 
+ * audioThreadExiting() (called in doFinally()).
+ * 
+ * @author Bob Hanson
+ * 
+ */
+public class JSAudioThread extends JSThread {
+       
+       protected Owner owner;
+       protected boolean done;
+       protected int myBufferLength;
+       protected SourceDataLine line;
+       protected int rate, nChannels, bitsPerSample;
+       
+       protected byte[] audioByteBuffer;
+       protected int audioBufferByteLength;
+
+       private AudioFormat audioFormat;
+       private int myBufferOffset;
+       private int playCount;
+       
+       public JSAudioThread(Owner owner, AudioFormat audioFormat, byte[] audioByteBuffer) {
+               this.owner = owner;
+               setFormat(audioFormat);
+               setBuffer(audioByteBuffer);
+       }
+
+       /**
+        * A convenience constructor requiring standard settings of 
+        * signed (for 8-bit) and littleEndian (for 16-bit)
+        *   
+        * @param owner
+        * @param rate
+        * @param bitsPerSample
+        * @param nChannels
+        * @param audioByteBuffer
+        */
+       public JSAudioThread(Owner owner, int rate, int bitsPerSample, int nChannels, byte[] audioByteBuffer) {
+               this.owner = owner;
+               setFormat(new AudioFormat(rate, bitsPerSample, nChannels, true, false));
+               setBuffer(audioByteBuffer);
+       }
+       
+       /**
+        * primarily available for (new JSAudioThread()).playULawData
+        * 
+        */
+       public JSAudioThread() {
+       }
+
+       /**
+        * primarily available for (new JSAudioThread()).playOnce
+        * 
+        */
+       public JSAudioThread(AudioFormat audioFormat) {
+               setFormat(audioFormat);
+       }
+
+       /**
+        * 
+        * A simple 8-bit uLaw data player
+        * 
+        * @param data
+        */
+       public void playULawData(byte[] data) {
+               // this constructor uses default new AudioFormat(ULAW,8000,8,1,1,8000,true)
+               // threading is taken care of by the browser in JavaScript
+               AudioPlayer.player.start(new AudioDataStream(new AudioData(data)));
+       }
+
+
+       /**
+        * Just play once through; no additions
+        * 
+        * @param data
+        */
+       public void playOnce(byte[] data, int offset, int length) {
+               setBuffer(data);
+               myBufferOffset = offset;
+               myBufferLength = length;
+               playCount = 1;
+               start();
+       }
+
+       public void setBuffer(byte[] audioByteBuffer) {
+               this.audioByteBuffer = audioByteBuffer;
+               audioBufferByteLength = audioByteBuffer.length;
+       }
+       
+       public SourceDataLine getLine() {
+               return line;
+       }
+       
+       public AudioFormat getFormat() {
+               return audioFormat;
+       }
+                       
+       public void setFormat(AudioFormat audioFormat) {
+               this.audioFormat = audioFormat;
+               rate = (int) audioFormat.getSampleRate();
+               bitsPerSample = audioFormat.getSampleSizeInBits();
+               nChannels = audioFormat.getChannels();                  
+       }
+
+       public void resetAudio() {
+               if (line == null)
+                       return;
+               line.flush();
+               line.close();
+               line = null;
+       }
+
+       /**
+        * Standard initialization of a SourceDataLine
+        * 
+        */
+       @Override
+       protected boolean myInit() {
+               try {
+                       DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
+                       if (line != null)
+                               line.close();
+                       line = (SourceDataLine) AudioSystem.getLine(info);
+                       line.open(audioFormat, audioBufferByteLength);
+                       line.start();
+               } catch (Exception e) {
+                       e.printStackTrace();
+                       return false;
+               }
+               return true;
+       }
+       
+       @Override
+       protected boolean isLooping() {
+               return !done && (--playCount >= 0 || owner != null && owner.checkSoundStatus());
+       }
+
+       @Override
+       protected boolean myLoop() {
+               if (!done) {
+                       if ((myBufferLength = (owner == null ? myBufferLength : owner.fillAudioBuffer())) <= 0)
+                               return !(done = true);
+                       try {
+                               if (line == null)
+                                       myInit();                                       
+                               line.write(audioByteBuffer, myBufferOffset, myBufferLength);
+                       } catch (Exception e) {
+                               e.printStackTrace();
+                               done = true;
+                       }
+               }
+               return !done;
+       }
+
+       @Override
+       protected void whenDone() {
+               done = true;
+               resetAudio();
+       }
+
+       @Override
+       protected int getDelayMillis() {
+               // about 25% of the actual play time
+       return 1000                                        // ms/sec 
+                       * (myBufferLength  * 8 / bitsPerSample)        // * samples 
+                       / rate                                         // * seconds/sample) 
+                       / nChannels                                    // / number of channels
+                       / 4;                                           // * 25%
+       }
+
+       @Override
+       protected void onException(Exception e) {
+               e.printStackTrace();
+       }
+
+       @Override
+       protected void doFinally() {
+               if (owner != null)
+                       owner.audioThreadExiting();
+       }
+
+       public interface Owner {
+
+               /**
+                * 
+                * @return true if thread should continue; false if not
+                * 
+                */
+               boolean checkSoundStatus();
+
+               /** fill audio buffer
+                * 
+                * @return number of bytes to write to audio line
+                *
+                */
+               int fillAudioBuffer();
+
+               /**
+                *  called from the finally clause when complete 
+                * 
+                */
+               void audioThreadExiting();
+               
+
+       }
+
+}
+
diff --git a/src2/javajs/util/JSJSONParser.java b/src2/javajs/util/JSJSONParser.java
new file mode 100644 (file)
index 0000000..552270d
--- /dev/null
@@ -0,0 +1,325 @@
+package javajs.util;
+
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+
+/**
+ * a very simple JSON parser for JSON objects that are compatible with JavaScript
+ * A gross simplification of https://github.com/douglascrockford/JSON-java
+ * 
+ * A SUBSET of JSON with similarly to window.JSON.parse():
+ * 
+ * In JavaScript returns "null" for a null value, not null
+ * 
+ *  -- requires quoted strings for keys and values
+ *  
+ *  -- does not allow /xxx/ objects
+ *  
+ *  @author Bob Hanson
+ *  
+ */
+public class JSJSONParser {
+
+  private String str;
+  private int index;
+  private int len;
+  private boolean asHashTable;
+
+  public JSJSONParser () {
+    // for reflection
+  }
+  
+  /**
+   * requires { "key":"value", "key":"value",....}
+   * 
+   * @param str
+   * @param asHashTable TODO
+   * 
+   * @return Map or null
+   */
+  @SuppressWarnings("unchecked")
+  public Map<String, Object> parseMap(String str, boolean asHashTable) {
+    index = 0;
+    this.asHashTable = asHashTable;
+    this.str = str;
+    len = str.length();
+    if (getChar() != '{')
+      return null;
+    returnChar();
+    return (Map<String, Object>) getValue(false);
+  }
+  
+  /**
+   * Could return Integer, Float, Boolean, String, Map<String, Object>, Lst<Object>, or null
+   * 
+   * @param str
+   * @param asHashTable 
+   * @return a object equivalent to the JSON string str
+   * 
+   */
+  public Object parse(String str, boolean asHashTable) {
+    index = 0;
+    this.asHashTable = asHashTable;
+    this.str = str;
+    len = str.length();
+    return getValue(false);
+  }
+
+  private char next() {
+    return (index < len ? str.charAt(index++) : '\0');
+  }
+
+  private void returnChar() {
+    index--;
+  }
+
+  /**
+   * Get the next char in the string, skipping whitespace.
+   * 
+   * @throws JSONException
+   * @return one character, or 0 if there are no more characters.
+   */
+  private char getChar() throws JSONException {
+    for (;;) {
+      char c = next();
+      if (c == 0 || c > ' ') {
+        return c;
+      }
+    }
+  }
+
+  /**
+   * only allowing the following values:
+   * 
+   * {...} object
+   * 
+   * [...] array
+   * 
+   * Integer
+   * 
+   * Float
+   * 
+   * "quoted string"
+   * 
+   * 
+   * @param isKey if we should allow {...} and [...]
+   * @return a subclass of Object
+   * @throws JSONException
+   */
+  private Object getValue(boolean isKey) throws JSONException {
+    int i = index;
+    char c = getChar();
+    switch (c) {
+    case '\0':
+      return null;
+    case '"':
+    case '\'':
+      return getString(c);
+    case '{':
+      if (!isKey)
+        return getObject();
+      c = 0;
+      break;
+    case '[':
+      if (!isKey)
+        return getArray();
+      c = 0;
+      break;
+    default:
+      // standard syntax is assumed; not checking all possible invalid keys
+      // for example, "-" is not allowed in JavaScript, which is what this is for
+      returnChar();
+      while (c >= ' ' && "[,]{:}'\"".indexOf(c) < 0)
+        c = next();
+      returnChar();
+      if (isKey && c != ':')
+        c = 0;
+      break;
+    }
+    if (isKey && c == 0)
+      throw new JSONException("invalid key");
+
+    String string = str.substring(i, index).trim();
+
+    // check for the only valid simple words: true, false, null (lower case)
+    // and in this case, only for 
+
+    if (!isKey) {
+      if (string.equals("true")) {
+        return Boolean.TRUE;
+      }
+      if (string.equals("false")) {
+        return Boolean.FALSE;
+      }
+      if (string.equals("null")) {
+        return (asHashTable ? string : null);
+      }
+    }
+    //  only numbers from here on:
+    c = string.charAt(0);
+    if (c >= '0' && c <= '9' || c == '-')
+      try {
+        if (string.indexOf('.') < 0 && string.indexOf('e') < 0
+            && string.indexOf('E') < 0)
+          return new Integer(string);
+        // not allowing infinity or NaN
+        // using float here because Jmol does not use Double
+        Float d = Float.valueOf(string);
+        if (!d.isInfinite() && !d.isNaN())
+          return d;
+      } catch (Exception e) {
+      }
+    // not a valid number
+    System.out.println("JSON parser cannot parse " + string);
+    throw new JSONException("invalid value");
+  }
+
+  private String getString(char quote) throws JSONException {
+    char c;
+    SB sb = null;
+    int i0 = index;
+    for (;;) {
+      int i1 = index;
+      switch (c = next()) {
+      case '\0':
+      case '\n':
+      case '\r':
+        throw syntaxError("Unterminated string");
+      case '\\':
+        switch (c = next()) {
+        case '"':
+        case '\'':
+        case '\\':
+        case '/':
+          break;
+        case 'b':
+          c = '\b';
+          break;
+        case 't':
+          c = '\t';
+          break;
+        case 'n':
+          c = '\n';
+          break;
+        case 'f':
+          c = '\f';
+          break;
+        case 'r':
+          c = '\r';
+          break;
+        case 'u':
+          int i = index;
+          index += 4;
+          try {
+            c = (char) Integer.parseInt(str.substring(i, index), 16);
+          } catch (Exception e) {
+            throw syntaxError("Substring bounds error");
+          }
+          break;
+        default:
+          throw syntaxError("Illegal escape.");
+        }
+        break;
+      default:
+        if (c == quote)
+          return (sb == null ? str.substring(i0, i1) : sb.toString());
+        break;
+      }
+      if (index > i1 + 1) {
+        if (sb == null) {
+          sb = new SB();
+          sb.append(str.substring(i0, i1));
+        }
+      }
+      if (sb != null)
+        sb.appendC(c);
+    }
+  }
+
+  private Object getObject() {
+    Map<String, Object> map = (asHashTable ? new Hashtable<String, Object>() : new HashMap<String, Object>());
+    String key = null;
+    switch (getChar()) {
+    case '}':
+      return map;
+    case 0:
+      throw new JSONException("invalid object");
+    }
+    returnChar();
+    boolean isKey = false;
+    for (;;) {
+      if ((isKey = !isKey) == true)
+        key = getValue(true).toString();
+      else
+        map.put(key, getValue(false));
+      switch (getChar()) {
+      case '}':
+        return map;
+      case ':':
+        if (isKey)
+          continue;
+        isKey = true;
+        //$FALL-THROUGH$
+      case ',':
+        if (!isKey)
+          continue;
+        //$FALL-THROUGH$
+      default:
+        throw syntaxError("Expected ',' or ':' or '}'");
+      }
+    }
+  }
+
+  private Object getArray() {
+    Lst<Object> l = new Lst<Object>();
+    switch (getChar()) {
+    case ']':
+      return l;
+    case '\0':
+      throw new JSONException("invalid array");
+    }
+    returnChar();
+    boolean isNull = false;
+    for (;;) {
+      if (isNull) {
+        l.addLast(null);
+        isNull = false;
+      } else {
+        l.addLast(getValue(false));
+      }
+      switch (getChar()) {
+      case ',':
+        switch (getChar()) {
+        case ']':
+          // terminal ,
+          return l;
+        case ',':
+          // empty value
+          isNull = true;
+          //$FALL-THROUGH$
+        default:
+          returnChar();
+        }
+        continue;
+      case ']':
+        return l;
+      default:
+        throw syntaxError("Expected ',' or ']'");
+      }
+    }
+  }
+
+  /**
+   * Make a JSONException to signal a syntax error.
+   * 
+   * @param message
+   *        The error message.
+   * @return A JSONException object, suitable for throwing
+   */
+  public JSONException syntaxError(String message) {
+    return new JSONException(message + " for " + str.substring(0, Math.min(index,  len)));
+  }
+
+}
diff --git a/src2/javajs/util/JSONException.java b/src2/javajs/util/JSONException.java
new file mode 100644 (file)
index 0000000..58af722
--- /dev/null
@@ -0,0 +1,8 @@
+package javajs.util;
+
+public class JSONException extends RuntimeException {
+    public JSONException(String message) {
+        super(message);
+    }
+
+}
diff --git a/src2/javajs/util/JSThread.java b/src2/javajs/util/JSThread.java
new file mode 100644 (file)
index 0000000..be94c00
--- /dev/null
@@ -0,0 +1,216 @@
+package javajs.util;
+
+import java.awt.Toolkit;
+import java.awt.event.InvocationEvent;
+
+//import javajs.J2SRequireImport;
+import javajs.api.JSFunction;
+
+
+/**
+ * An abstract class that takes care of simple threading in Java or JavaScript.
+ * 
+ * To use it, subclass it and complete the necessary methods.
+ * 
+ * 
+ * There are three states: INIT, LOOP, and DONE.
+ * 
+ * These states are passed into run1
+ * 
+ * 
+ * @author Bob Hanson
+ * 
+ */
+//@J2SRequireImport(swingjs.JSToolkit.class)
+public abstract class JSThread extends Thread implements JSFunction {
+
+       public static final int INIT = 0;
+       public static final int LOOP = 1;
+       public static final int DONE = 2;
+       
+       public static int threadCount = 0;
+
+       protected boolean isJS;
+       
+       public JSThread() {
+               this(null, "JSThread-" + (++threadCount));
+       }
+       
+       public JSThread(String name) {
+               this(null, name);
+       }
+       
+       public JSThread(ThreadGroup group, String name) {
+               super(group, name);
+               /**
+                * @j2sNative
+                * 
+                * this.isJS = true;
+                */
+               {}
+       }
+
+       @Override
+       public void run() {
+               run1(INIT);
+       }
+
+       @Override
+       public synchronized void start() {
+
+               
+               /**
+                * @j2sNative
+                * 
+                *                        Clazz.load("swingjs.JSToolkit").dispatch$O$I$I(this, 1, 0);
+                * 
+                */
+               {
+                       super.start();
+               }
+
+       }
+
+       /**
+        * thread initialization
+        * 
+        * @return false to exit thread before any looping
+        */
+       protected abstract boolean myInit();
+       
+       /**
+        * check for continuing to loop
+        * 
+        * @return true if we are to continue looping
+        */
+       protected abstract boolean isLooping();
+       
+       /**
+        * 
+        * @return false to handle sleepAndReturn yourself
+        */
+       protected abstract boolean myLoop();
+       /**
+        * what to do when the DONE state is reached
+        * 
+        */
+       protected abstract void whenDone();
+       
+       /**
+        * 
+        * @return the sleep time in milliseconds
+        */
+       protected abstract int getDelayMillis();
+       
+       /**
+        * handle an exception -- state will be set to DONE no matter what you do here
+        * 
+        * @param e
+        */
+       protected abstract void onException(Exception e);
+       
+       /**
+        * anything you want done in  try{}catch(}finally().
+        * Note that this method is not fired if we are in JavaScript
+        * mode and the normal return from sleepAndReturn() is taken. 
+        *  
+        */
+       protected abstract void doFinally();
+       
+       /**
+        * a generic method that loops until done, either in Java or JavaScript.
+        * 
+        * In JavaScript it will reenter and continue at the appropriate spot.
+        * 
+        * This method may be overridden if desired.
+        * 
+        * @see org.uwi.SimThread
+        * 
+        * @param state
+        */
+       protected void run1(int state) {
+               boolean executeFinally = true;
+               // called by thisThread.run();
+               try {
+                       while (!interrupted()) {
+                               switch (state) {
+                               case INIT:
+                                       if (!myInit())
+                                               return;
+                                       // initial code here
+                                       state = LOOP;
+                                       continue;
+                               case LOOP:
+                                       // to stop looping, return false from isLooping()
+                                       if (!isLooping()) {
+                                               state = DONE;
+                                               continue;
+                                       }
+                                       // To handle sleepAndReturn yourself, or to skip the
+                                       // sleep when desired, return false from myLoop();
+                                       // Note that doFinally must not be executed in this case.
+                                       // This is because JavaScript will do a return here
+                                       // for every loop, and Java will not.
+                                       if (myLoop() && sleepAndReturn(getDelayMillis(), state)) {
+                                               executeFinally = false;
+                                               return;                                         
+                                       }
+                                       continue;
+                               case DONE:
+                                       whenDone();
+                                       // whatever
+                                       return;
+                               }
+                       }
+               } catch (Exception e) {
+                       onException(e);
+                       state = DONE;
+               } finally {
+                       if (executeFinally)
+                               doFinally();
+               }
+               // normal exit
+       }
+
+       /**
+        * 
+        * @param r2
+        * @param state
+        * @return true if we should interrupt (i.e. JavaScript)
+        * @throws InterruptedException
+        */
+       protected boolean sleepAndReturn(final int delay, final int state)
+                       throws InterruptedException {
+               if (!isJS) {
+                       sleep(delay);
+                       return false;
+               }
+
+               // in JavaScript, we need to do this through the system event queue,
+               // which in JSToolkit takes care of all the "thread" handling.
+
+               final JSThread me = this;
+               Runnable r = new Runnable() {
+                       @Override
+                       public void run() {
+                               me.run1(state);
+                       }
+               };
+               /**
+                * @j2sNative
+                * 
+                *            setTimeout(
+                *              function() {
+                *              java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent$java_awt_AWTEvent(
+                *              Clazz.new_(java.awt.event.InvocationEvent.c$$O$Runnable,[me, r]))}, 
+                *              delay);
+                * 
+                */
+               {
+                       Toolkit.getDefaultToolkit().getSystemEventQueue()
+                                       .postEvent(new InvocationEvent(me, r));
+               }
+               return true;
+       }
+       
+}
diff --git a/src2/javajs/util/LimitedLineReader.java b/src2/javajs/util/LimitedLineReader.java
new file mode 100644 (file)
index 0000000..e1d973f
--- /dev/null
@@ -0,0 +1,48 @@
+package javajs.util;
+
+import java.io.BufferedReader;
+
+/**
+ *  A simple class to read a designated number of bytes from a 
+ *  file and then return them line by line, skipping lines that
+ *  start with #, and including the \n or \r characters at line ends.
+ *  
+ *  Generally useful for determining what sort of data a file contains.
+ *   
+ */
+public class LimitedLineReader {
+  private char[] buf;
+  private int cchBuf;
+  private int ichCurrent;
+
+  public LimitedLineReader(BufferedReader bufferedReader, int readLimit)
+    throws Exception {  
+    bufferedReader.mark(readLimit + 1);
+    buf = new char[readLimit];
+    cchBuf = Math.max(bufferedReader.read(buf, 0, readLimit), 0);
+    ichCurrent = 0;
+    bufferedReader.reset();
+  }
+
+  public String getHeader(int n) {
+    return (n == 0 ? new String(buf) : new String(buf, 0, Math.min(cchBuf, n)));
+  }
+  
+  public String readLineWithNewline() {
+    while (ichCurrent < cchBuf) {
+      int ichBeginningOfLine = ichCurrent;
+      char ch = 0;
+      while (ichCurrent < cchBuf &&
+             (ch = buf[ichCurrent++]) != '\r' && ch != '\n') {
+      }
+      if (ch == '\r' && ichCurrent < cchBuf && buf[ichCurrent] == '\n')
+        ++ichCurrent;
+      int cchLine = ichCurrent - ichBeginningOfLine;
+      if (buf[ichBeginningOfLine] == '#')
+        continue; // flush comment lines;
+      return new String(buf, ichBeginningOfLine, cchLine);
+    }
+    return "";
+  }
+}
+
diff --git a/src2/javajs/util/ListDataReader.java b/src2/javajs/util/ListDataReader.java
new file mode 100644 (file)
index 0000000..7814977
--- /dev/null
@@ -0,0 +1,57 @@
+package javajs.util;
+
+import java.io.IOException;
+
+
+
+
+
+/**
+ * 
+ * VectorDataReader subclasses BufferedReader and overrides its
+ * read, readLine, mark, and reset methods so that JmolAdapter 
+ * works with Vector<String> arrays without any further adaptation. 
+ * 
+ */
+
+public class ListDataReader extends DataReader {
+  private Lst<String> data;
+  private int pt;
+  private int len;
+
+  public ListDataReader() {
+    super();
+  }
+  
+  @SuppressWarnings("unchecked")
+  @Override
+  public DataReader setData(Object data) {
+    this.data = (Lst<String>) data;
+    len = this.data.size();
+    return this;
+  }
+
+  @Override
+  public int read(char[] buf, int off, int len) throws IOException {
+    return readBuf(buf, off, len);
+  }
+
+  @Override
+  public String readLine() {
+    return (pt < len ? data.get(pt++) : null);
+  }
+
+  /**
+   * 
+   * @param ptr
+   */
+  public void mark(long ptr) {
+    //ignore ptr.
+    ptMark = pt;
+  }
+
+  @Override
+  public void reset() {
+    pt = ptMark;
+  }
+}
\ No newline at end of file
diff --git a/src2/javajs/util/Lst.java b/src2/javajs/util/Lst.java
new file mode 100644 (file)
index 0000000..e7fdda5
--- /dev/null
@@ -0,0 +1,56 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2007-04-26 16:57:51 -0500 (Thu, 26 Apr 2007) $
+ * $Revision: 7502 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package javajs.util;
+
+import java.util.ArrayList;
+
+/**
+ * created to remove ambiguities in add and remove
+ * 
+ * @param <V>
+ */
+@SuppressWarnings("serial")
+public class Lst<V> extends ArrayList<V> {
+
+  public Lst() {
+    super();  
+  }
+  
+  public boolean addLast(V v) {
+      return super.add(v);
+  }
+  
+  public V removeItemAt(int location) {
+      return super.remove(location);
+  }
+
+  public boolean removeObj(Object v) {
+      return super.remove(v);
+  }
+  
+}
diff --git a/src2/javajs/util/M3.java b/src2/javajs/util/M3.java
new file mode 100644 (file)
index 0000000..88f6f4e
--- /dev/null
@@ -0,0 +1,637 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+import java.io.Serializable;
+
+
+
+/**
+ * A single precision floating point 3 by 3 matrix.
+ * 
+ * @author Kenji hiranabe
+ * 
+ *         additions by Bob Hanson hansonr@stolaf.edu 9/30/2012 for unique
+ *         constructor and method names for the optimization of compiled
+ *         JavaScript using Java2Script
+ *         
+ *         
+ */
+public class M3 extends M34 implements Serializable {
+
+  /**
+   * Constructs and initializes a Matrix3f to all zeros.
+   */
+  public M3() {
+  }
+
+  /**
+   * Constructs and initializes a Matrix3f from the specified 9 element array.
+   * this.m00 =v[0], this.m01=v[1], etc.
+   * 
+   * @param v
+   *        the array of length 9 containing in order
+   * @return m
+   */
+  public static M3 newA9(float[] v) {
+    M3 m = new M3();
+    m.setA(v);
+    return m;
+  }
+  
+  /**
+   * Constructs a new matrix with the same values as the Matrix3f parameter.
+   * 
+   * @param m1
+   *        The source matrix.
+   * @return m
+   */
+  public static M3 newM3(M3 m1) {
+    M3 m = new M3();
+    if (m1 == null) {
+      m.setScale(1);
+      return m;
+    }
+    m.m00 = m1.m00;
+    m.m01 = m1.m01;
+    m.m02 = m1.m02;
+
+    m.m10 = m1.m10;
+    m.m11 = m1.m11;
+    m.m12 = m1.m12;
+
+    m.m20 = m1.m20;
+    m.m21 = m1.m21;
+    m.m22 = m1.m22;
+    return m;
+  }
+
+  /**
+   * Sets this Matrix3f to a scalar * Identity.
+   * @param scale 
+   */
+  public void setScale(float scale) {
+    clear33();
+    m00 = m11 = m22 = scale;
+  }
+
+  /**
+   * Sets the value of this matrix to the double value of the Matrix3f argument.
+   * 
+   * @param m1
+   *        the matrix3f
+   */
+  public void setM3(M34 m1) {
+    setM33(m1);
+  }
+  /**
+   * Sets the values in this Matrix3f equal to the row-major array parameter
+   * (ie, the first four elements of the array will be copied into the first row
+   * of this matrix, etc.).
+   * 
+   * @param m
+   */
+  public void setA(float m[]) {
+    m00 = m[0];
+    m01 = m[1];
+    m02 = m[2];
+    m10 = m[3];
+    m11 = m[4];
+    m12 = m[5];
+    m20 = m[6];
+    m21 = m[7];
+    m22 = m[8];
+  }
+
+  /**
+   * Sets the specified element of this matrix3d to the value provided.
+   * 
+   * @param row
+   *        the row number to be modified (zero indexed)
+   * @param col
+   *        the column number to be modified (zero indexed)
+   * @param v
+   *        the new value
+   */
+  public void setElement(int row, int col, float v) {
+    set33(row, col, v);
+  }
+
+  /**
+   * Retrieves the value at the specified row and column of this matrix.
+   * 
+   * @param row
+   *        the row number to be retrieved (zero indexed)
+   * @param col
+   *        the column number to be retrieved (zero indexed)
+   * @return the value at the indexed element
+   */
+  public float getElement(int row, int col) {
+    return get33(row, col);
+  }
+
+  /**
+   * Sets the specified row of this matrix3d to the three values provided.
+   * 
+   * @param row
+   *        the row number to be modified (zero indexed)
+   * @param x
+   *        the first column element
+   * @param y
+   *        the second column element
+   * @param z
+   *        the third column element
+   */
+  public void setRow(int row, float x, float y, float z) {
+    switch (row) {
+    case 0:
+      m00 = x;
+      m01 = y;
+      m02 = z;
+      return;
+    case 1:
+      m10 = x;
+      m11 = y;
+      m12 = z;
+      return;
+    case 2:
+      m20 = x;
+      m21 = y;
+      m22 = z;
+      return;
+    default:
+      err();
+    }
+  }
+
+  /**
+   * Sets the specified row of this matrix3d to the Vector provided.
+   * 
+   * @param row
+   *        the row number to be modified (zero indexed)
+   * @param v
+   *        the replacement row
+   */
+  public void setRowV(int row, T3 v) {
+    switch (row) {
+    case 0:
+      m00 = v.x;
+      m01 = v.y;
+      m02 = v.z;
+      return;
+    case 1:
+      m10 = v.x;
+      m11 = v.y;
+      m12 = v.z;
+      return;
+    case 2:
+      m20 = v.x;
+      m21 = v.y;
+      m22 = v.z;
+      return;
+    default:
+      err();
+    }
+  }
+
+  /**
+   * Sets the specified row of this matrix3d to the four values provided.
+   * 
+   * @param row
+   *        the row number to be modified (zero indexed)
+   * @param v
+   *        the replacement row
+   */
+  public void setRowA(int row, float v[]) {
+    setRow33(row, v);
+  }
+
+  /**
+   * Copies the matrix values in the specified row into the array parameter.
+   * 
+   * @param row
+   *        the matrix row
+   * @param v
+   *        The array into which the matrix row values will be copied
+   */
+  @Override
+  public void getRow(int row, float v[]) {
+    getRow33(row, v);
+  }
+
+  /**
+   * Sets the specified column of this matrix3d to the three values provided.
+   * 
+   * @param column
+   *        the column number to be modified (zero indexed)
+   * @param x
+   *        the first row element
+   * @param y
+   *        the second row element
+   * @param z
+   *        the third row element
+   */
+  public void setColumn3(int column, float x, float y, float z) {
+    switch (column) {
+    case 0:
+      m00 = x;
+      m10 = y;
+      m20 = z;
+      break;
+    case 1:
+      m01 = x;
+      m11 = y;
+      m21 = z;
+      break;
+    case 2:
+      m02 = x;
+      m12 = y;
+      m22 = z;
+      break;
+    default:
+      err();
+    }
+  }
+
+  /**
+   * Sets the specified column of this matrix3d to the vector provided.
+   * 
+   * @param column
+   *        the column number to be modified (zero indexed)
+   * @param v
+   *        the replacement column
+   */
+  public void setColumnV(int column, T3 v) {
+    switch (column) {
+    case 0:
+      m00 = v.x;
+      m10 = v.y;
+      m20 = v.z;
+      break;
+    case 1:
+      m01 = v.x;
+      m11 = v.y;
+      m21 = v.z;
+      break;
+    case 2:
+      m02 = v.x;
+      m12 = v.y;
+      m22 = v.z;
+      break;
+    default:
+      err();
+    }
+  }
+
+  /**
+   * Copies the matrix values in the specified column into the vector parameter.
+   * 
+   * @param column
+   *        the matrix column
+   * @param v
+   *        The vector into which the matrix row values will be copied
+   */
+  public void getColumnV(int column, T3 v) {
+    switch (column) {
+    case 0:
+      v.x = m00;
+      v.y = m10;
+      v.z = m20;
+      break;
+    case 1:
+      v.x = m01;
+      v.y = m11;
+      v.z = m21;
+      break;
+    case 2:
+      v.x = m02;
+      v.y = m12;
+      v.z = m22;
+      break;
+    default:
+      err();
+    }
+  }
+
+  /**
+   * Sets the specified column of this matrix3d to the four values provided.
+   * 
+   * @param column
+   *        the column number to be modified (zero indexed)
+   * @param v
+   *        the replacement column
+   */
+  public void setColumnA(int column, float v[]) {
+    setColumn33(column, v);
+  }
+
+  /**
+   * Copies the matrix values in the specified column into the array parameter.
+   * 
+   * @param column
+   *        the matrix column
+   * @param v
+   *        The array into which the matrix row values will be copied
+   */
+  public void getColumn(int column, float v[]) {
+    getColumn33(column, v);
+  }
+
+  /**
+   * Sets the value of this matrix to sum of itself and matrix m1.
+   * 
+   * @param m1
+   *        the other matrix
+   */
+  public void add(M3 m1) {
+    add33(m1);
+  }
+
+  /**
+   * Sets the value of this matrix to the matrix difference of itself and matrix
+   * m1 (this = this - m1).
+   * 
+   * @param m1
+   *        the other matrix
+   */
+  public void sub(M3 m1) {
+    sub33(m1);
+  }
+
+  /**
+   * Sets the value of this matrix to its transpose.
+   */
+  public void transpose() {
+    transpose33();
+  }
+
+  /**
+   * Sets the value of this matrix to the transpose of the argument matrix
+   * 
+   * @param m1
+   *        the matrix to be transposed
+   */
+  public void transposeM(M3 m1) {
+    // alias-safe
+    setM33(m1);
+    transpose33();
+  }
+
+  /**
+   * Sets the value of this matrix to the matrix inverse of the passed matrix
+   * m1.
+   * 
+   * @param m1
+   *        the matrix to be inverted
+   */
+  public void invertM(M3 m1) {
+    setM33(m1);
+    invert();
+  }
+
+  /**
+   * Sets the value of this matrix to its inverse.
+   */
+  public void invert() {
+    double s = determinant3();
+    if (s == 0.0)
+      return;
+    s = 1 / s;
+    // alias-safe way.
+    set9(m11 * m22 - m12 * m21, m02 * m21 - m01 * m22, m01 * m12 - m02 * m11,
+        m12 * m20 - m10 * m22, m00 * m22 - m02 * m20, m02 * m10 - m00 * m12,
+        m10 * m21 - m11 * m20, m01 * m20 - m00 * m21, m00 * m11 - m01 * m10);
+    scale((float) s);
+  }
+
+  /**
+   * Sets the value of this matrix to a rotation matrix about the x axis by the
+   * passed angle.
+   * 
+   * @param angle
+   *        the angle to rotate about the X axis in radians
+   * @return this
+   */
+  public M3 setAsXRotation(float angle) {
+    setXRot(angle);
+    return this;
+  }
+  
+  /**
+   * Sets the value of this matrix to a rotation matrix about the y axis by the
+   * passed angle.
+   * 
+   * @param angle
+   *        the angle to rotate about the Y axis in radians
+   * @return this
+   */
+  public M3 setAsYRotation(float angle) {
+    setYRot(angle);
+    return this;
+  }
+
+  /**
+   * Sets the value of this matrix to a rotation matrix about the z axis by the
+   * passed angle.
+   * 
+   * @param angle
+   *        the angle to rotate about the Z axis in radians
+   * @return this
+   */
+  public M3 setAsZRotation(float angle) {
+    setZRot(angle);
+    return this;
+  }
+
+  /**
+   * Multiplies each element of this matrix by a scalar.
+   * 
+   * @param scalar
+   *        The scalar multiplier.
+   */
+  public void scale(float scalar) {
+    mul33(scalar);
+  }
+
+  /**
+   * Sets the value of this matrix to the result of multiplying itself with
+   * matrix m1.
+   * 
+   * @param m1
+   *        the other matrix
+   */
+  public void mul(M3 m1) {
+    mul2(this, m1);
+  }
+
+  /**
+   * Sets the value of this matrix to the result of multiplying the two argument
+   * matrices together.
+   * 
+   * @param m1
+   *        the first matrix
+   * @param m2
+   *        the second matrix
+   */
+  public void mul2(M3 m1, M3 m2) {
+    // alias-safe way.
+    set9(m1.m00 * m2.m00 + m1.m01 * m2.m10 + m1.m02 * m2.m20, m1.m00 * m2.m01
+        + m1.m01 * m2.m11 + m1.m02 * m2.m21, m1.m00 * m2.m02 + m1.m01 * m2.m12
+        + m1.m02 * m2.m22,
+
+    m1.m10 * m2.m00 + m1.m11 * m2.m10 + m1.m12 * m2.m20, m1.m10 * m2.m01
+        + m1.m11 * m2.m11 + m1.m12 * m2.m21, m1.m10 * m2.m02 + m1.m11 * m2.m12
+        + m1.m12 * m2.m22,
+
+    m1.m20 * m2.m00 + m1.m21 * m2.m10 + m1.m22 * m2.m20, m1.m20 * m2.m01
+        + m1.m21 * m2.m11 + m1.m22 * m2.m21, m1.m20 * m2.m02 + m1.m21 * m2.m12
+        + m1.m22 * m2.m22);
+  }
+
+  /**
+   * Returns true if the Object o is of type Matrix3f and all of the data
+   * members of t1 are equal to the corresponding data members in this Matrix3f.
+   * 
+   * @param o
+   *        the object with which the comparison is made.
+   */
+  @Override
+  public boolean equals(Object o) {
+    if (!(o instanceof M3))
+      return false;
+    M3 m = (M3) o;
+    return m00 == m.m00 && m01 == m.m01 && m02 == m.m02 && m10 == m.m10
+        && m11 == m.m11 && m12 == m.m12 && m20 == m.m20 && m21 == m.m21
+        && m22 == m.m22;
+  }
+
+  /**
+   * Returns a hash number based on the data values in this object. Two
+   * different Matrix3f objects with identical data values (ie, returns true for
+   * equals(Matrix3f) ) will return the same hash number. Two objects with
+   * different data members may return the same hash value, although this is not
+   * likely.
+   * 
+   * @return the integer hash value
+   */
+  @Override
+  public int hashCode() {
+    return T3.floatToIntBits(m00) ^ T3.floatToIntBits(m01)
+        ^ T3.floatToIntBits(m02) ^ T3.floatToIntBits(m10)
+        ^ T3.floatToIntBits(m11) ^ T3.floatToIntBits(m12)
+        ^ T3.floatToIntBits(m20) ^ T3.floatToIntBits(m21)
+        ^ T3.floatToIntBits(m22);
+  }
+
+  /**
+   * Sets this matrix to all zeros.
+   */
+  public void setZero() {
+    clear33();
+  }
+
+  /**
+   * Sets 9 values
+   * 
+   * @param m00
+   * @param m01
+   * @param m02
+   * @param m10
+   * @param m11
+   * @param m12
+   * @param m20
+   * @param m21
+   * @param m22
+   */
+  private void set9(float m00, float m01, float m02, float m10, float m11,
+                   float m12, float m20, float m21, float m22) {
+    this.m00 = m00;
+    this.m01 = m01;
+    this.m02 = m02;
+    this.m10 = m10;
+    this.m11 = m11;
+    this.m12 = m12;
+    this.m20 = m20;
+    this.m21 = m21;
+    this.m22 = m22;
+  }
+
+  /**
+   * Returns a string that contains the values of this Matrix3f.
+   * 
+   * @return the String representation
+   */
+  @Override
+  public String toString() {
+    return "[\n  [" + m00 + "\t" + m01 + "\t" + m02 + "]" + "\n  [" + m10
+        + "\t" + m11 + "\t" + m12 + "]" + "\n  [" + m20 + "\t" + m21 + "\t"
+        + m22 + "] ]";
+  }
+
+  /**
+   * Sets the value of this matrix to the matrix conversion of the single
+   * precision axis and angle argument.
+   * 
+   * @param a
+   *        the axis and angle to be converted
+   * @return this
+   */
+  public M3 setAA(A4 a) {
+    setAA33(a);
+    return this;
+  }
+
+  /**
+   * 3D ball rotation from dx dy in-plane mouse motion
+   * adapted from Andrew Hanson
+   * Computer Graphics beyond the Third Dimension:
+   * Geometry, Orientation Control, and Rendering for
+   * Graphics in Dimensions Greater than Three
+   * Course Notes for SIGGRAPH â€™98
+   * http://www.cse.ohio-state.edu/~hwshen/888_su02/hanson_note.pdf
+   * 
+   * @param responseFactor Jmol uses 0.02 here
+   * @param dx
+   * @param dy
+   * @return true if successful; false if not;
+   */
+  public boolean setAsBallRotation(float responseFactor, float dx, float dy) {
+    float r = (float) Math.sqrt(dx * dx + dy * dy);
+    float th =  r * responseFactor;
+    if (th == 0) {
+      setScale(1);
+      return false;
+    }
+    float c = (float) Math.cos(th);
+    float s = (float) Math.sin(th);
+    float nx = -dy / r;
+    float ny = dx / r;
+    float c1 = c - 1;
+    m00 = 1 + c1 * nx * nx;
+    m01 = m10 = c1 * nx * ny;
+    m20 = -(m02 = s * nx);
+    m11 = 1 + c1 * ny * ny;
+    m21 = -(m12 = s * ny);
+    m22 = c;
+    return true;
+  }
+
+  public boolean isRotation() {
+    return (Math.abs(determinant3() - 1) < 0.001f);
+  }
+
+}
diff --git a/src2/javajs/util/M34.java b/src2/javajs/util/M34.java
new file mode 100644 (file)
index 0000000..260a82c
--- /dev/null
@@ -0,0 +1,416 @@
+package javajs.util;
+
+/**
+ * A base class for both M3 and M4 to conserve code size.
+ * 
+ * @author Kenji hiranabe
+ * 
+ *         additions by Bob Hanson hansonr@stolaf.edu 9/30/2012 for unique
+ *         constructor and method names for the optimization of compiled
+ *         JavaScript using Java2Script and for subclassing to M3 and M4
+ * 
+ */
+public abstract class M34 {
+
+  /**
+   * The first element of the first row
+   */
+  public float m00;
+
+  /**
+   * The second element of the first row.
+   */
+  public float m01;
+
+  /**
+   * third element of the first row.
+   */
+  public float m02;
+
+  /**
+   * The first element of the second row.
+   */
+  public float m10;
+
+  /**
+   * The second element of the second row.
+   */
+  public float m11;
+
+  /**
+   * The third element of the second row.
+   */
+  public float m12;
+
+  /**
+   * The first element of the third row.
+   */
+  public float m20;
+
+  /**
+   * The second element of the third row.
+   */
+  public float m21;
+
+  /**
+   * The third element of the third row.
+   */
+  public float m22;
+
+  protected void setAA33(A4 a) {
+    double x = a.x;
+    double y = a.y;
+    double z = a.z;
+    double angle = a.angle;
+    // Taken from Rick's which is taken from Wertz. pg. 412
+    // Bug Fixed and changed into right-handed by hiranabe
+    double n = Math.sqrt(x * x + y * y + z * z);
+    // zero-div may occur
+    n = 1 / n;
+    x *= n;
+    y *= n;
+    z *= n;
+    double c = Math.cos(angle);
+    double s = Math.sin(angle);
+    double omc = 1.0 - c;
+    m00 = (float) (c + x * x * omc);
+    m11 = (float) (c + y * y * omc);
+    m22 = (float) (c + z * z * omc);
+
+    double tmp1 = x * y * omc;
+    double tmp2 = z * s;
+    m01 = (float) (tmp1 - tmp2);
+    m10 = (float) (tmp1 + tmp2);
+
+    tmp1 = x * z * omc;
+    tmp2 = y * s;
+    m02 = (float) (tmp1 + tmp2);
+    m20 = (float) (tmp1 - tmp2);
+
+    tmp1 = y * z * omc;
+    tmp2 = x * s;
+    m12 = (float) (tmp1 - tmp2);
+    m21 = (float) (tmp1 + tmp2);
+  }
+
+  public void rotate(T3 t) {
+    // alias-safe
+    rotate2(t, t);
+  }
+
+  /**
+   * Transform the vector vec using this Matrix3f and place the result into
+   * vecOut.
+   * 
+   * @param t
+   *        the single precision vector to be transformed
+   * @param result
+   *        the vector into which the transformed values are placed
+   */
+  public void rotate2(T3 t, T3 result) {
+    // alias-safe
+    result.set(m00 * t.x + m01 * t.y + m02 * t.z, m10 * t.x + m11 * t.y + m12
+        * t.z, m20 * t.x + m21 * t.y + m22 * t.z);
+  }
+
+
+  /**
+   * Sets the value of this matrix to the double value of the Matrix3f argument.
+   * 
+   * @param m1
+   *        the matrix3f
+   */
+  protected void setM33(M34 m1) {
+    m00 = m1.m00;
+    m01 = m1.m01;
+    m02 = m1.m02;
+    m10 = m1.m10;
+    m11 = m1.m11;
+    m12 = m1.m12;
+    m20 = m1.m20;
+    m21 = m1.m21;
+    m22 = m1.m22;
+  }
+
+  protected void clear33() {
+    m00 = m01 = m02 = m10 = m11 = m12 = m20 = m21 = m22 = 0.0f;
+  }
+
+  protected void set33(int row, int col, float v) {
+    switch (row) {
+    case 0:
+      switch (col) {
+      case 0:
+        m00 = v;
+        return;
+      case 1:
+        m01 = v;
+        return;
+      case 2: 
+        m02 = v;
+        return;
+      }
+      break;
+    case 1:
+      switch (col) {
+      case 0:
+        m10 = v;
+        return;
+      case 1:
+        m11 = v;
+        return;
+      case 2: 
+        m12 = v;
+        return;
+      }
+      break;
+    case 2: 
+      switch (col) {
+      case 0:
+        m20 = v;
+        return;
+      case 1:
+        m21 = v;
+        return;
+      case 2: 
+        m22 = v;
+        return;
+      }
+      break;
+    }
+    err();
+  }
+
+  protected float get33(int row, int col) {
+    switch (row) {
+    case 0:
+      switch (col) {
+      case 0:
+        return m00;
+      case 1:
+        return m01;
+      case 2:
+        return m02;
+      }
+      break;
+    case 1:
+      switch (col) {
+      case 0:
+        return m10;
+      case 1:
+        return m11;
+      case 2:
+        return m12;
+      }
+      break;
+    case 2:
+      switch (col) {
+      case 0:
+        return m20;
+      case 1:
+        return m21;
+      case 2:
+        return m22;
+      }
+      break;
+    }
+    err();
+    return 0;
+  }
+
+  protected void setRow33(int row, float v[]) {
+    switch (row) {
+    case 0:
+      m00 = v[0];
+      m01 = v[1];
+      m02 = v[2];
+      return;
+    case 1:
+      m10 = v[0];
+      m11 = v[1];
+      m12 = v[2];
+      return;
+    case 2:
+      m20 = v[0];
+      m21 = v[1];
+      m22 = v[2];
+      return;
+    default:
+      err();
+    }
+  }
+  
+  public abstract void getRow(int row, float v[]);
+
+  protected void getRow33(int row, float v[]) {
+    switch (row) {
+    case 0:
+      v[0] = m00;
+      v[1] = m01;
+      v[2] = m02;
+      return;
+    case 1:
+      v[0] = m10;
+      v[1] = m11;
+      v[2] = m12;
+      return;
+    case 2:
+      v[0] = m20;
+      v[1] = m21;
+      v[2] = m22;
+      return;
+    }
+    err();
+  }
+
+  protected void setColumn33(int column, float v[]) {
+    switch(column) {
+    case 0:
+      m00 = v[0];
+      m10 = v[1];
+      m20 = v[2];
+      break;
+    case 1:
+      m01 = v[0];
+      m11 = v[1];
+      m21 = v[2];
+      break;
+    case 2:
+      m02 = v[0];
+      m12 = v[1];
+      m22 = v[2];
+      break;
+     default:
+      err();
+    }
+  }
+
+  protected void getColumn33(int column, float v[]) {
+    switch(column) {
+    case 0:
+      v[0] = m00;
+      v[1] = m10;
+      v[2] = m20;
+      break;
+    case 1:
+      v[0] = m01;
+      v[1] = m11;
+      v[2] = m21;
+      break;
+    case 2:
+      v[0] = m02;
+      v[1] = m12;
+      v[2] = m22;
+      break;
+    default:
+      err();
+    }
+  }
+
+  protected void add33(M34 m1) {
+    m00 += m1.m00;
+    m01 += m1.m01;
+    m02 += m1.m02;
+    m10 += m1.m10;
+    m11 += m1.m11;
+    m12 += m1.m12;
+    m20 += m1.m20;
+    m21 += m1.m21;
+    m22 += m1.m22;
+  }
+
+  protected void sub33(M34 m1) {
+    m00 -= m1.m00;
+    m01 -= m1.m01;
+    m02 -= m1.m02;
+    m10 -= m1.m10;
+    m11 -= m1.m11;
+    m12 -= m1.m12;
+    m20 -= m1.m20;
+    m21 -= m1.m21;
+    m22 -= m1.m22;
+  }
+
+  protected void mul33(float x) {
+    m00 *= x;
+    m01 *= x;
+    m02 *= x;
+    m10 *= x;
+    m11 *= x;
+    m12 *= x;
+    m20 *= x;
+    m21 *= x;
+    m22 *= x;
+  }
+
+  protected void transpose33() {
+    float tmp = m01;
+    m01 = m10;
+    m10 = tmp;
+
+    tmp = m02;
+    m02 = m20;
+    m20 = tmp;
+
+    tmp = m12;
+    m12 = m21;
+    m21 = tmp;
+  }
+
+  protected void setXRot(float angle) {
+    double c = Math.cos(angle);
+    double s = Math.sin(angle);
+    m00 = 1.0f;
+    m01 = 0.0f;
+    m02 = 0.0f;
+    m10 = 0.0f;
+    m11 = (float) c;
+    m12 = (float) -s;
+    m20 = 0.0f;
+    m21 = (float) s;
+    m22 = (float) c;
+  }
+
+  protected void setYRot(float angle) {
+    double c = Math.cos(angle);
+    double s = Math.sin(angle);
+    m00 = (float) c;
+    m01 = 0.0f;
+    m02 = (float) s;
+    m10 = 0.0f;
+    m11 = 1.0f;
+    m12 = 0.0f;
+    m20 = (float) -s;
+    m21 = 0.0f;
+    m22 = (float) c;
+  }
+  
+  protected void setZRot(float angle) {
+    double c = Math.cos(angle);
+    double s = Math.sin(angle);
+    m00 = (float) c;
+    m01 = (float) -s;
+    m02 = 0.0f;
+    m10 = (float) s;
+    m11 = (float) c;
+    m12 = 0.0f;
+    m20 = 0.0f;
+    m21 = 0.0f;
+    m22 = 1.0f;
+  }
+  
+  /**
+   * @return 3x3 determinant
+   */
+  public float determinant3() {
+    return m00 * (m11 * m22 - m21 * m12) - m01 * (m10 * m22 - m20 * m12) + m02
+        * (m10 * m21 - m20 * m11);
+  }
+  
+  protected void err() {
+    throw new ArrayIndexOutOfBoundsException(
+        "matrix column/row out of bounds");
+  }
+
+
+}
diff --git a/src2/javajs/util/M4.java b/src2/javajs/util/M4.java
new file mode 100644 (file)
index 0000000..58bd355
--- /dev/null
@@ -0,0 +1,942 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+/**
+ * A single precision floating point 4 by 4 matrix.
+ * 
+ * @author Kenji hiranabe
+ * 
+ *         additions by Bob Hanson hansonr@stolaf.edu 9/30/2012 for unique
+ *         constructor and method names for the optimization of compiled
+ *         JavaScript using Java2Script
+ */
+public class M4 extends M34 {
+
+  /**
+   * The fourth element of the first row.
+   */
+  public float m03;
+
+  /**
+   * The fourth element of the second row.
+   */
+  public float m13;
+
+  /**
+   * The fourth element of the third row.
+   */
+  public float m23;
+
+  /**
+   * The first element of the fourth row.
+   */
+  public float m30;
+
+  /**
+   * The second element of the fourth row.
+   */
+  public float m31;
+
+  /**
+   * The third element of the fourth row.
+   */
+  public float m32;
+
+  /**
+   * The fourth element of the fourth row.
+   */
+  public float m33 = 0;
+
+  /**
+   * all zeros
+   */
+  public M4() {
+  }
+  /**
+   * Constructs and initializes a Matrix4f from the specified 16 element array.
+   * this.m00 =v[0], this.m01=v[1], etc.
+   * 
+   * @param v
+   *        the array of length 16 containing in order
+   * @return m
+   */
+  public static M4 newA16(float[] v) {
+    M4 m = new M4();
+    m.m00 = v[0];
+    m.m01 = v[1];
+    m.m02 = v[2];
+    m.m03 = v[3];
+
+    m.m10 = v[4];
+    m.m11 = v[5];
+    m.m12 = v[6];
+    m.m13 = v[7];
+
+    m.m20 = v[8];
+    m.m21 = v[9];
+    m.m22 = v[10];
+    m.m23 = v[11];
+
+    m.m30 = v[12];
+    m.m31 = v[13];
+    m.m32 = v[14];
+    m.m33 = v[15];
+
+    return m;
+  }
+
+  /**
+   * Constructs a new matrix with the same values as the Matrix4f parameter.
+   * 
+   * @param m1
+   *        the source matrix
+   * @return m
+   */
+  public static M4 newM4(M4 m1) {
+    M4 m = new M4();
+    if (m1 == null) {
+      m.setIdentity();
+      return m;
+    }
+    m.setToM3(m1);
+    m.m03 = m1.m03;
+    m.m13 = m1.m13;
+    m.m23 = m1.m23;
+    m.m30 = m1.m30;
+    m.m31 = m1.m31;
+    m.m32 = m1.m32;
+    m.m33 = m1.m33;
+    return m;
+  }
+
+  /**
+   * Constructs and initializes a Matrix4f from the rotation matrix and
+   * translation.
+   * 
+   * @param m1
+   *        The rotation matrix representing the rotational components
+   * @param t
+   *        The translational components of the matrix
+   * @return m
+   */
+  public static M4 newMV(M3 m1, T3 t) {
+    M4 m = new M4();
+    m.setMV(m1, t);
+    return m;
+  }
+
+  /**
+   * Sets this matrix to all zeros.
+   */
+  public void setZero() {
+    clear33();
+    m03 = m13 = m23 = m30 = m31 = m32 = m33 = 0.0f;
+  }
+
+  /**
+   * Sets this Matrix4f to identity.
+   */
+  public void setIdentity() {
+    setZero();
+    m00 = m11 = m22 = m33 = 1.0f;
+  }
+
+  /**
+   * Sets the value of this matrix to a copy of the passed matrix m1.
+   * 
+   * @param m1
+   *        the matrix to be copied
+   * @return this
+   */
+  public M4 setM4(M4 m1) {
+    setM33(m1);
+    m03 = m1.m03;
+    m13 = m1.m13;
+    m23 = m1.m23;
+    m30 = m1.m30;
+    m31 = m1.m31;
+    m32 = m1.m32;
+    m33 = m1.m33;
+    return this;
+  }
+
+  /**
+   * Initializes a Matrix4f from the rotation matrix and translation.
+   * 
+   * @param m1
+   *        The rotation matrix representing the rotational components
+   * @param t
+   *        The translational components of the matrix
+   */
+  public void setMV(M3 m1, T3 t) {
+    setM33(m1);
+    setTranslation(t);
+    m33 = 1;
+  }
+
+  /**
+   * Sets the rotational component (upper 3x3) of this matrix to the matrix
+   * values in the single precision Matrix3f argument; the other elements of
+   * this matrix are initialized as if this were an identity matrix (ie, affine
+   * matrix with no translational component).
+   * 
+   * @param m1
+   *        the 3x3 matrix
+   */
+  public void setToM3(M34 m1) {
+    setM33(m1);
+    m03 = m13 = m23 = m30 = m31 = m32 = 0.0f;
+    m33 = 1.0f;
+  }
+
+  /**
+   * Sets the rotational component (upper 3x3) of this matrix 
+   * to a rotation given by an axis angle
+   * 
+   * @param a
+   *        the axis and angle to be converted
+   */
+  public void setToAA(A4 a) {
+    setIdentity();
+    setAA33(a);
+  }
+
+  /**
+   * Sets the values in this Matrix4f equal to the row-major array parameter
+   * (ie, the first four elements of the array will be copied into the first row
+   * of this matrix, etc.).
+   * 
+   * @param m
+   */
+  public void setA(float m[]) {
+    m00 = m[0];
+    m01 = m[1];
+    m02 = m[2];
+    m03 = m[3];
+    m10 = m[4];
+    m11 = m[5];
+    m12 = m[6];
+    m13 = m[7];
+    m20 = m[8];
+    m21 = m[9];
+    m22 = m[10];
+    m23 = m[11];
+    m30 = m[12];
+    m31 = m[13];
+    m32 = m[14];
+    m33 = m[15];
+  }
+
+  /**
+   * Modifies the translational components of this matrix to the values of the
+   * Vector3f argument; the other values of this matrix are not modified.
+   * 
+   * @param trans
+   *        the translational component
+   */
+  public void setTranslation(T3 trans) {
+    m03 = trans.x;
+    m13 = trans.y;
+    m23 = trans.z;
+  }
+
+  /**
+   * Sets the specified element of this matrix4f to the value provided.
+   * 
+   * @param row
+   *        the row number to be modified (zero indexed)
+   * @param col
+   *        the column number to be modified (zero indexed)
+   * @param v
+   *        the new value
+   */
+  public void setElement(int row, int col, float v) {
+    if (row < 3 && col < 3) {
+      set33(row, col, v);
+      return;
+    }
+    if (row > 3 || col > 3)
+      err();
+    switch (row) {
+    case 0:
+      m03 = v;
+      return;
+    case 1:
+      m13 = v;
+      return;
+    case 2:
+      m23 = v;
+      return;
+    }
+    switch (col) {
+    case 0:
+      m30 = v;
+      return;
+    case 1:
+      m31 = v;
+      return;
+    case 2:
+      m32 = v;
+      return;
+    case 3:
+      m33 = v;
+      return;
+    }
+  }
+
+  /**
+   * Retrieves the value at the specified row and column of this matrix.
+   * 
+   * @param row
+   *        the row number to be retrieved (zero indexed)
+   * @param col
+   *        the column number to be retrieved (zero indexed)
+   * @return the value at the indexed element
+   */
+  public float getElement(int row, int col) {
+    if (row < 3 && col < 3)
+      return get33(row, col);
+    if (row > 3 || col > 3) {
+      err();
+      return 0;
+    }
+    switch (row) {
+    case 0:
+      return m03;
+    case 1:
+      return m13;
+    case 2:
+      return m23;
+    default:
+      switch (col) {
+      case 0:
+        return m30;
+      case 1:
+        return m31;
+      case 2:
+        return m32;
+      default:
+        return m33;
+      }
+    }
+  }
+
+  /**
+   * Retrieves the translational components of this matrix.
+   * 
+   * @param trans
+   *        the vector that will receive the translational component
+   */
+  public void getTranslation(T3 trans) {
+    trans.x = m03;
+    trans.y = m13;
+    trans.z = m23;
+  }
+
+  /**
+   * Gets the upper 3x3 values of this matrix and places them into the matrix
+   * m1.
+   * 
+   * @param m1
+   *        The matrix that will hold the values
+   */
+  public void getRotationScale(M3 m1) {
+    m1.m00 = m00;
+    m1.m01 = m01;
+    m1.m02 = m02;
+    m1.m10 = m10;
+    m1.m11 = m11;
+    m1.m12 = m12;
+    m1.m20 = m20;
+    m1.m21 = m21;
+    m1.m22 = m22;
+  }
+
+  /**
+   * Replaces the upper 3x3 matrix values of this matrix with the values in the
+   * matrix m1.
+   * 
+   * @param m1
+   *        The matrix that will be the new upper 3x3
+   */
+  public void setRotationScale(M3 m1) {
+    m00 = m1.m00;
+    m01 = m1.m01;
+    m02 = m1.m02;
+    m10 = m1.m10;
+    m11 = m1.m11;
+    m12 = m1.m12;
+    m20 = m1.m20;
+    m21 = m1.m21;
+    m22 = m1.m22;
+  }
+
+  /**
+   * Sets the specified row of this matrix4f to the four values provided.
+   * 
+   * @param row
+   *        the row number to be modified (zero indexed)
+   * @param v
+   *        the replacement row
+   */
+  public void setRowA(int row, float v[]) {
+    if (row < 3)
+      setRow33(row, v);
+    switch (row) {
+    case 0:
+      m03 = v[3];
+      return;
+    case 1:
+      m13 = v[3];
+      return;
+    case 2:
+      m23 = v[3];
+      return;
+    case 3:
+      m30 = v[0];
+      m31 = v[1];
+      m32 = v[2];
+      m33 = v[3];
+      return;
+    }
+    err();
+  }
+
+  /**
+   * Copies the matrix values in the specified row into the array parameter.
+   * 
+   * @param row
+   *        the matrix row
+   * @param v
+   *        The array into which the matrix row values will be copied
+   */
+  @Override
+  public void getRow(int row, float v[]) {
+    if (row < 3)
+      getRow33(row, v);
+    switch (row) {
+    case 0:
+      v[3] = m03;
+      return;
+    case 1:
+      v[3] = m13;
+      return;
+    case 2:
+      v[3] = m23;
+      return;
+    case 3:
+      v[0] = m30;
+      v[1] = m31;
+      v[2] = m32;
+      v[3] = m33;
+      return;
+    }
+    err();
+  }
+
+  /**
+   * Sets the specified column of this matrix4f to the four values provided.
+   * 
+   * @param column
+   *        the column number to be modified (zero indexed)
+   * @param x
+   *        the first row element
+   * @param y
+   *        the second row element
+   * @param z
+   *        the third row element
+   * @param w
+   *        the fourth row element
+   */
+  public void setColumn4(int column, float x, float y, float z, float w) {
+    if (column == 0) {
+      m00 = x;
+      m10 = y;
+      m20 = z;
+      m30 = w;
+    } else if (column == 1) {
+      m01 = x;
+      m11 = y;
+      m21 = z;
+      m31 = w;
+    } else if (column == 2) {
+      m02 = x;
+      m12 = y;
+      m22 = z;
+      m32 = w;
+    } else if (column == 3) {
+      m03 = x;
+      m13 = y;
+      m23 = z;
+      m33 = w;
+    } else {
+      err();
+    }
+  }
+
+  /**
+   * Sets the specified column of this matrix4f to the four values provided.
+   * 
+   * @param column
+   *        the column number to be modified (zero indexed)
+   * @param v
+   *        the replacement column
+   */
+  public void setColumnA(int column, float v[]) {
+    if (column < 3)
+      setColumn33(column, v);
+    switch (column) {
+    case 0:
+      m30 = v[3];
+      return;
+    case 1:
+      m31 = v[3];
+      return;
+    case 2:
+      m32 = v[3];
+      return;
+    case 3:
+      m03 = v[0];
+      m13 = v[1];
+      m23 = v[2];
+      m33 = v[3];
+      return;
+    default:
+      err();
+    }
+  }
+
+  /**
+   * Copies the matrix values in the specified column into the array parameter.
+   * 
+   * @param column
+   *        the matrix column
+   * @param v
+   *        The array into which the matrix column values will be copied
+   */
+  public void getColumn(int column, float v[]) {
+    if (column < 3)
+      getColumn33(column, v);
+    switch (column) {
+    case 0:
+      v[3] = m30;
+      return;
+    case 1:
+      v[3] = m31;
+      return;
+    case 2:
+      v[3] = m32;
+      return;
+    case 3:
+      v[0] = m03;
+      v[1] = m13;
+      v[2] = m23;
+      v[3] = m33;
+      return;
+    default:
+      err();
+    }
+  }
+
+  /**
+   * Sets the value of this matrix to the matrix difference of itself and matrix
+   * m1 (this = this - m1).
+   * 
+   * @param m1
+   *        the other matrix
+   */
+  public void sub(M4 m1) {
+    sub33(m1);
+    m03 -= m1.m03;
+    m13 -= m1.m13;
+    m23 -= m1.m23;
+    m30 -= m1.m30;
+    m31 -= m1.m31;
+    m32 -= m1.m32;
+    m33 -= m1.m33;
+  }
+
+  /**
+   * Sets the value of this matrix to its transpose.
+   */
+  public void transpose() {
+    transpose33();
+    float tmp = m03;
+    m03 = m30;
+    m30 = tmp;
+
+    tmp = m13;
+    m13 = m31;
+    m31 = tmp;
+
+    tmp = m23;
+    m23 = m32;
+    m32 = tmp;
+  }
+
+  /**
+   * Sets the value of this matrix to its inverse.
+   * @return this
+   */
+  public M4 invert() {
+    float s = determinant4();
+    if (s == 0.0)
+      return this;
+    s = 1 / s;
+    // alias-safe way.
+    // less *,+,- calculation than expanded expression.
+    set(m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13
+        * (m21 * m32 - m22 * m31), m21 * (m02 * m33 - m03 * m32) + m22
+        * (m03 * m31 - m01 * m33) + m23 * (m01 * m32 - m02 * m31), m31
+        * (m02 * m13 - m03 * m12) + m32 * (m03 * m11 - m01 * m13) + m33
+        * (m01 * m12 - m02 * m11), m01 * (m13 * m22 - m12 * m23) + m02
+        * (m11 * m23 - m13 * m21) + m03 * (m12 * m21 - m11 * m22),
+
+    m12 * (m20 * m33 - m23 * m30) + m13 * (m22 * m30 - m20 * m32) + m10
+        * (m23 * m32 - m22 * m33), m22 * (m00 * m33 - m03 * m30) + m23
+        * (m02 * m30 - m00 * m32) + m20 * (m03 * m32 - m02 * m33), m32
+        * (m00 * m13 - m03 * m10) + m33 * (m02 * m10 - m00 * m12) + m30
+        * (m03 * m12 - m02 * m13), m02 * (m13 * m20 - m10 * m23) + m03
+        * (m10 * m22 - m12 * m20) + m00 * (m12 * m23 - m13 * m22),
+
+    m13 * (m20 * m31 - m21 * m30) + m10 * (m21 * m33 - m23 * m31) + m11
+        * (m23 * m30 - m20 * m33), m23 * (m00 * m31 - m01 * m30) + m20
+        * (m01 * m33 - m03 * m31) + m21 * (m03 * m30 - m00 * m33), m33
+        * (m00 * m11 - m01 * m10) + m30 * (m01 * m13 - m03 * m11) + m31
+        * (m03 * m10 - m00 * m13), m03 * (m11 * m20 - m10 * m21) + m00
+        * (m13 * m21 - m11 * m23) + m01 * (m10 * m23 - m13 * m20),
+
+    m10 * (m22 * m31 - m21 * m32) + m11 * (m20 * m32 - m22 * m30) + m12
+        * (m21 * m30 - m20 * m31), m20 * (m02 * m31 - m01 * m32) + m21
+        * (m00 * m32 - m02 * m30) + m22 * (m01 * m30 - m00 * m31), m30
+        * (m02 * m11 - m01 * m12) + m31 * (m00 * m12 - m02 * m10) + m32
+        * (m01 * m10 - m00 * m11), m00 * (m11 * m22 - m12 * m21) + m01
+        * (m12 * m20 - m10 * m22) + m02 * (m10 * m21 - m11 * m20));
+    scale(s);
+    return this;
+  }
+
+  /**
+   * Sets 16 values
+   * 
+   * @param m00
+   * @param m01
+   * @param m02
+   * @param m03
+   * @param m10
+   * @param m11
+   * @param m12
+   * @param m13
+   * @param m20
+   * @param m21
+   * @param m22
+   * @param m23
+   * @param m30
+   * @param m31
+   * @param m32
+   * @param m33
+   */
+  private void set(float m00, float m01, float m02, float m03, float m10,
+                   float m11, float m12, float m13, float m20, float m21,
+                   float m22, float m23, float m30, float m31, float m32,
+                   float m33) {
+    this.m00 = m00;
+    this.m01 = m01;
+    this.m02 = m02;
+    this.m03 = m03;
+    this.m10 = m10;
+    this.m11 = m11;
+    this.m12 = m12;
+    this.m13 = m13;
+    this.m20 = m20;
+    this.m21 = m21;
+    this.m22 = m22;
+    this.m23 = m23;
+    this.m30 = m30;
+    this.m31 = m31;
+    this.m32 = m32;
+    this.m33 = m33;
+  }
+  /**
+   * Computes the determinant of this matrix.
+   * 
+   * @return the determinant of the matrix
+   */
+  public float determinant4() {
+    // less *,+,- calculation than expanded expression.
+    return (m00 * m11 - m01 * m10) * (m22 * m33 - m23 * m32)
+        - (m00 * m12 - m02 * m10) * (m21 * m33 - m23 * m31)
+        + (m00 * m13 - m03 * m10) * (m21 * m32 - m22 * m31)
+        + (m01 * m12 - m02 * m11) * (m20 * m33 - m23 * m30)
+        - (m01 * m13 - m03 * m11) * (m20 * m32 - m22 * m30)
+        + (m02 * m13 - m03 * m12) * (m20 * m31 - m21 * m30);
+
+  }
+
+  /**
+   * Multiplies each element of this matrix by a scalar.
+   * 
+   * @param scalar
+   *        The scalar multiplier.
+   */
+  public void scale(float scalar) {
+    mul33(scalar);
+    m03 *= scalar;
+    m13 *= scalar;
+    m23 *= scalar;
+    m30 *= scalar;
+    m31 *= scalar;
+    m32 *= scalar;
+    m33 *= scalar;
+  }
+
+  /**
+   * Sets the value of this matrix to the result of multiplying itself with
+   * matrix m1.
+   * 
+   * @param m1
+   *        the other matrix
+   */
+  public void mul(M4 m1) {
+    mul2(this, m1);
+  }
+
+  /**
+   * Sets the value of this matrix to the result of multiplying the two argument
+   * matrices together.
+   * 
+   * @param m1
+   *        the first matrix
+   * @param m2
+   *        the second matrix
+   */
+  public void mul2(M4 m1, M4 m2) {
+    // alias-safe way.
+    set(m1.m00 * m2.m00 + m1.m01 * m2.m10 + m1.m02 * m2.m20 + m1.m03 * m2.m30,
+        m1.m00 * m2.m01 + m1.m01 * m2.m11 + m1.m02 * m2.m21 + m1.m03 * m2.m31,
+        m1.m00 * m2.m02 + m1.m01 * m2.m12 + m1.m02 * m2.m22 + m1.m03 * m2.m32,
+        m1.m00 * m2.m03 + m1.m01 * m2.m13 + m1.m02 * m2.m23 + m1.m03 * m2.m33,
+
+        m1.m10 * m2.m00 + m1.m11 * m2.m10 + m1.m12 * m2.m20 + m1.m13 * m2.m30,
+        m1.m10 * m2.m01 + m1.m11 * m2.m11 + m1.m12 * m2.m21 + m1.m13 * m2.m31,
+        m1.m10 * m2.m02 + m1.m11 * m2.m12 + m1.m12 * m2.m22 + m1.m13 * m2.m32,
+        m1.m10 * m2.m03 + m1.m11 * m2.m13 + m1.m12 * m2.m23 + m1.m13 * m2.m33,
+
+        m1.m20 * m2.m00 + m1.m21 * m2.m10 + m1.m22 * m2.m20 + m1.m23 * m2.m30,
+        m1.m20 * m2.m01 + m1.m21 * m2.m11 + m1.m22 * m2.m21 + m1.m23 * m2.m31,
+        m1.m20 * m2.m02 + m1.m21 * m2.m12 + m1.m22 * m2.m22 + m1.m23 * m2.m32,
+        m1.m20 * m2.m03 + m1.m21 * m2.m13 + m1.m22 * m2.m23 + m1.m23 * m2.m33,
+
+        m1.m30 * m2.m00 + m1.m31 * m2.m10 + m1.m32 * m2.m20 + m1.m33 * m2.m30,
+        m1.m30 * m2.m01 + m1.m31 * m2.m11 + m1.m32 * m2.m21 + m1.m33 * m2.m31,
+        m1.m30 * m2.m02 + m1.m31 * m2.m12 + m1.m32 * m2.m22 + m1.m33 * m2.m32,
+        m1.m30 * m2.m03 + m1.m31 * m2.m13 + m1.m32 * m2.m23 + m1.m33 * m2.m33);
+  }
+
+  /**
+   * Transform the vector vec using this Matrix4f and place the result back into
+   * vec.
+   * 
+   * @param vec
+   *        the single precision vector to be transformed
+   */
+  public void transform(T4 vec) {
+    transform2(vec, vec);
+  }
+
+  /**
+   * Transform the vector vec using this Matrix4f and place the result into
+   * vecOut.
+   * 
+   * @param vec
+   *        the single precision vector to be transformed
+   * @param vecOut
+   *        the vector into which the transformed values are placed
+   */
+  public void transform2(T4 vec, T4 vecOut) {
+    // alias-safe
+    vecOut.set4(m00 * vec.x + m01 * vec.y + m02 * vec.z + m03 * vec.w, m10
+        * vec.x + m11 * vec.y + m12 * vec.z + m13 * vec.w, m20 * vec.x + m21
+        * vec.y + m22 * vec.z + m23 * vec.w, m30 * vec.x + m31 * vec.y + m32
+        * vec.z + m33 * vec.w);
+  }
+
+  /**
+   * Transforms the point parameter with this Matrix4f and places the result
+   * back into point. The fourth element of the point input parameter is assumed
+   * to be one.
+   * 
+   * @param point
+   *        the input point to be transformed.
+   */
+  public void rotTrans(T3 point) {
+    rotTrans2(point, point);
+  }
+
+  /**
+   * Transforms the point parameter with this Matrix4f and places the result
+   * into pointOut. The fourth element of the point input parameter is assumed to
+   * be one. point may be pointOut
+   * 
+   * @param point
+   *        the input point to be transformed.
+   * @param pointOut
+   *        the transformed point
+   * @return pointOut
+   */
+  public T3 rotTrans2(T3 point, T3 pointOut) {
+      pointOut.set(
+          m00 * point.x + m01 * point.y + m02 * point.z + m03, 
+          m10 * point.x + m11 * point.y + m12 * point.z + m13, 
+          m20 * point.x + m21 * point.y + m22 * point.z + m23);
+      return pointOut;
+  }
+
+  /**
+   * Sets the value of this matrix to a rotation matrix about the w axis by the
+   * passed angle.
+   * 
+   * @param angle
+   *        the angle to rotate about the W axis in radians
+   * @return this
+   */
+  public M4 setAsXYRotation(float angle) {
+    setIdentity();
+    double c = Math.cos(angle);
+    double s = Math.sin(angle);
+    m22 = (float) c;
+    m23 = (float) -s;
+    m32 = (float) s;
+    m33 = (float) c;
+    return this;
+  }
+
+  /**
+   * Sets the value of this matrix to a rotation matrix about the w axis by the
+   * passed angle.
+   * 
+   * @param angle
+   *        the angle to rotate about the W axis in radians
+   * @return this
+   */
+  public M4 setAsYZRotation(float angle) {
+    setIdentity();
+    double c = Math.cos(angle);
+    double s = Math.sin(angle);
+    m00 = (float) c;
+    m03 = (float) -s;
+    m30 = (float) s;
+    m33 = (float) c;
+    return this;
+  }
+
+  /**
+   * Sets the value of this matrix to a rotation matrix about the w axis by the
+   * passed angle.
+   * 
+   * @param angle
+   *        the angle to rotate about the W axis in radians
+   * @return this
+   */
+  public M4 setAsXZRotation(float angle) {
+    setIdentity();
+    double c = Math.cos(angle);
+    double s = Math.sin(angle);
+    m11 = (float) c;
+    m13 = (float) -s;
+    m31 = (float) s;
+    m33 = (float) c;
+    return this;
+  }
+
+  /**
+   * Returns true if the Object o is of type Matrix4f and all of the data
+   * members of t1 are equal to the corresponding data members in this Matrix4f.
+   * 
+   * @param o
+   *        the object with which the comparison is made.
+   */
+  @Override
+  public boolean equals(Object o) {
+    if (!(o instanceof M4))
+      return false;
+    M4 m = (M4) o;
+    return (this.m00 == m.m00 && this.m01 == m.m01 && this.m02 == m.m02
+        && this.m03 == m.m03 && this.m10 == m.m10 && this.m11 == m.m11
+        && this.m12 == m.m12 && this.m13 == m.m13 && this.m20 == m.m20
+        && this.m21 == m.m21 && this.m22 == m.m22 && this.m23 == m.m23
+        && this.m30 == m.m30 && this.m31 == m.m31 && this.m32 == m.m32 && this.m33 == m.m33);
+  }
+
+  /**
+   * Returns a hash number based on the data values in this object. Two
+   * different Matrix4f objects with identical data values (ie, returns true for
+   * equals(Matrix4f) ) will return the same hash number. Two objects with
+   * different data members may return the same hash value, although this is not
+   * likely.
+   * 
+   * @return the integer hash value
+   */
+  @Override
+  public int hashCode() {
+    return T3.floatToIntBits(m00) ^ T3.floatToIntBits(m01)
+        ^ T3.floatToIntBits(m02) ^ T3.floatToIntBits(m03)
+        ^ T3.floatToIntBits(m10) ^ T3.floatToIntBits(m11)
+        ^ T3.floatToIntBits(m12) ^ T3.floatToIntBits(m13)
+        ^ T3.floatToIntBits(m20) ^ T3.floatToIntBits(m21)
+        ^ T3.floatToIntBits(m22) ^ T3.floatToIntBits(m23)
+        ^ T3.floatToIntBits(m30) ^ T3.floatToIntBits(m31)
+        ^ T3.floatToIntBits(m32) ^ T3.floatToIntBits(m33);
+  }
+
+  /**
+   * Returns a string that contains the values of this Matrix4f.
+   * 
+   * @return the String representation
+   */
+  @Override
+  public String toString() {
+    return "[\n  [" + m00 + "\t" + m01 + "\t" + m02 + "\t" + m03 + "]"
+        + "\n  [" + m10 + "\t" + m11 + "\t" + m12 + "\t" + m13 + "]" + "\n  ["
+        + m20 + "\t" + m21 + "\t" + m22 + "\t" + m23 + "]" + "\n  [" + m30
+        + "\t" + m31 + "\t" + m32 + "\t" + m33 + "] ]";
+  }
+  public M4 round(float f) {
+    m00 = rnd(m00, f);
+    m01 = rnd(m01, f);
+    m02 = rnd(m02, f);
+    m03 = rnd(m03, f);
+    m10 = rnd(m10, f);
+    m11 = rnd(m11, f);
+    m12 = rnd(m12, f);
+    m13 = rnd(m13, f);
+    m20 = rnd(m20, f);
+    m21 = rnd(m21, f);
+    m22 = rnd(m22, f);
+    m23 = rnd(m23, f);
+    m30 = rnd(m30, f);
+    m31 = rnd(m31, f);
+    m32 = rnd(m32, f);
+    m33 = rnd(m33, f);
+    return this;
+  }
+
+  private float rnd(float n, float f) {
+    return (Math.abs(n) < f ? 0 : n);
+  }
+}
diff --git a/src2/javajs/util/Matrix.java b/src2/javajs/util/Matrix.java
new file mode 100644 (file)
index 0000000..cea5a04
--- /dev/null
@@ -0,0 +1,457 @@
+package javajs.util;
+
+/**
+ * 
+ * streamlined and refined for Jmol by Bob Hanson
+ * 
+ * from http://math.nist.gov/javanumerics/jama/
+ * 
+ * Jama = Java Matrix class.
+ * 
+ * @author The MathWorks, Inc. and the National Institute of Standards and
+ *         Technology.
+ * @version 5 August 1998
+ */
+
+public class Matrix implements Cloneable {
+
+  public double[][] a;
+  protected int m, n;
+
+  /**
+   * Construct a matrix quickly without checking arguments.
+   * 
+   * @param a
+   *        Two-dimensional array of doubles or null
+   * @param m
+   *        Number of rows.
+   * @param n
+   *        Number of colums.
+   */
+
+  public Matrix(double[][] a, int m, int n) {
+    this.a = (a == null ? new double[m][n] : a);
+    this.m = m;
+    this.n = n;
+  }
+
+  /**
+   * Get row dimension.
+   * 
+   * @return m, the number of rows.
+   */
+
+  public int getRowDimension() {
+    return m;
+  }
+
+  /**
+   * Get column dimension.
+   * 
+   * @return n, the number of columns.
+   */
+
+  public int getColumnDimension() {
+    return n;
+  }
+
+  /**
+   * Access the internal two-dimensional array.
+   * 
+   * @return Pointer to the two-dimensional array of matrix elements.
+   */
+
+  public double[][] getArray() {
+    return a;
+  }
+
+  /**
+   * Copy the internal two-dimensional array.
+   * 
+   * @return Two-dimensional array copy of matrix elements.
+   */
+
+  public double[][] getArrayCopy() {
+    double[][] x = new double[m][n];
+    for (int i = m; --i >= 0;)
+      for (int j = n; --j >= 0;)
+        x[i][j] = a[i][j];
+    return x;
+  }
+
+  /**
+   * Make a deep copy of a matrix
+   * 
+   * @return copy
+   */
+
+  public Matrix copy() {
+    Matrix x = new Matrix(null, m, n);
+    double[][] c = x.a;
+    for (int i = m; --i >= 0;)
+      for (int j = n; --j >= 0;)
+        c[i][j] = a[i][j];
+    return x;
+  }
+
+  /**
+   * Clone the Matrix object.
+   */
+
+  @Override
+  public Object clone() {
+    return copy();
+  }
+
+  /**
+   * Get a submatrix.
+   * 
+   * @param i0
+   *        Initial row index
+   * @param j0
+   *        Initial column index
+   * @param nrows
+   *        Number of rows
+   * @param ncols
+   *        Number of columns
+   * @return submatrix
+   * 
+   */
+
+  public Matrix getSubmatrix(int i0, int j0, int nrows, int ncols) {
+    Matrix x = new Matrix(null, nrows, ncols);
+    double[][] xa = x.a;
+    for (int i = nrows; --i >= 0;)
+      for (int j = ncols; --j >= 0;)
+        xa[i][j] = a[i0 + i][j0 + j];
+    return x;
+  }
+
+  /**
+   * Get a submatrix for a give number of columns and selected row set.
+   * 
+   * @param r
+   *        Array of row indices.
+   * @param n
+   *        number of rows 
+   * @return submatrix
+   */
+
+  public Matrix getMatrixSelected(int[] r, int n) {
+    Matrix x = new Matrix(null, r.length, n);
+    double[][] xa = x.a;
+    for (int i = r.length; --i >= 0;) {
+      double[] b = a[r[i]];
+      for (int j = n; --j >= 0;)
+        xa[i][j] = b[j];
+    }
+    return x;
+  }
+
+  /**
+   * Matrix transpose.
+   * 
+   * @return A'
+   */
+
+  public Matrix transpose() {
+    Matrix x = new Matrix(null, n, m);
+    double[][] c = x.a;
+    for (int i = m; --i >= 0;)
+      for (int j = n; --j >= 0;)
+        c[j][i] = a[i][j];
+    return x;
+  }
+
+  /**
+   * add two matrices
+   * @param b
+   * @return new Matrix this + b
+   */
+  public Matrix add(Matrix b) {
+    return scaleAdd(b, 1);
+  }
+
+  /**
+   * subtract two matrices
+   * @param b
+   * @return new Matrix this - b
+   */
+  public Matrix sub(Matrix b) {
+    return scaleAdd(b, -1);
+  }
+  
+  /**
+   * X = A + B*scale
+   * @param b 
+   * @param scale 
+   * @return X
+   * 
+   */
+  public Matrix scaleAdd(Matrix b, double scale) {
+    Matrix x = new Matrix(null, m, n);
+    double[][] xa = x.a;
+    double[][] ba = b.a;
+    for (int i = m; --i >= 0;)
+      for (int j = n; --j >= 0;)
+        xa[i][j] = ba[i][j] * scale + a[i][j];
+    return x;
+  }
+
+  /**
+   * Linear algebraic matrix multiplication, A * B
+   * 
+   * @param b
+   *        another matrix
+   * @return Matrix product, A * B or null for wrong dimension
+   */
+
+  public Matrix mul(Matrix b) {
+    if (b.m != n)
+      return null;
+    Matrix x = new Matrix(null, m, b.n);
+    double[][] xa = x.a;
+    double[][] ba = b.a;
+    for (int j = b.n; --j >= 0;)
+      for (int i = m; --i >= 0;) {
+        double[] arowi = a[i];
+        double s = 0;
+        for (int k = n; --k >= 0;)
+          s += arowi[k] * ba[k][j];
+        xa[i][j] = s;
+      }
+    return x;
+  }
+
+  /**
+   * Matrix inverse or pseudoinverse
+   * 
+   * @return inverse (m == n) or pseudoinverse (m != n)
+   */
+
+  public Matrix inverse() {
+    return new LUDecomp(m, n).solve(identity(m, m), n);
+  }
+
+  /**
+   * Matrix trace.
+   * 
+   * @return sum of the diagonal elements.
+   */
+
+  public double trace() {
+    double t = 0;
+    for (int i = Math.min(m, n); --i >= 0;)
+      t += a[i][i];
+    return t;
+  }
+
+  /**
+   * Generate identity matrix
+   * 
+   * @param m
+   *        Number of rows.
+   * @param n
+   *        Number of columns.
+   * @return An m-by-n matrix with ones on the diagonal and zeros elsewhere.
+   */
+
+  public static Matrix identity(int m, int n) {
+    Matrix x = new Matrix(null, m, n);
+    double[][] xa = x.a;
+    for (int i = Math.min(m, n); --i >= 0;)
+      xa[i][i] = 1;
+    return x;
+  }
+
+  /**
+   * similarly to M3/M4 standard rotation/translation matrix
+   * we set a rotationTranslation matrix to be:
+   * 
+   * [   nxn rot    nx1 trans
+   * 
+   *     1xn  0     1x1 1      ]
+   * 
+   * 
+   * @return rotation matrix
+   */
+  public Matrix getRotation() {
+    return getSubmatrix(0, 0, m - 1, n - 1);
+  }
+
+  public Matrix getTranslation() {
+    return getSubmatrix(0, n - 1, m - 1, 1);
+  }
+
+  public static Matrix newT(T3 r, boolean asColumn) {
+    return (asColumn ? new Matrix(new double[][] { new double[] { r.x },
+        new double[] { r.y }, new double[] { r.z } }, 3, 1) : new Matrix(
+        new double[][] { new double[] { r.x, r.y, r.z } }, 1, 3));
+  }
+
+  @Override
+  public String toString() {
+    String s = "[\n";
+    for (int i = 0; i < m; i++) {
+      s += "  [";
+      for (int j = 0; j < n; j++)
+        s += " " + a[i][j];
+      s += "]\n";
+    }
+    s += "]";
+    return s;
+  }
+
+  /**
+   * 
+   * Edited down by Bob Hanson for minimum needed by Jmol -- just constructor
+   * and solve
+   * 
+   * LU Decomposition.
+   * <P>
+   * For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n unit
+   * lower triangular matrix L, an n-by-n upper triangular matrix U, and a
+   * permutation vector piv of length m so that A(piv,:) = L*U. If m < n, then L
+   * is m-by-m and U is m-by-n.
+   * <P>
+   * The LU decompostion with pivoting always exists, even if the matrix is
+   * singular, so the constructor will never fail. The primary use of the LU
+   * decomposition is in the solution of square systems of simultaneous linear
+   * equations. This will fail if isNonsingular() returns false.
+   */
+
+  private class LUDecomp {
+
+    /* ------------------------
+       Class variables
+     * ------------------------ */
+
+    /**
+     * Array for internal storage of decomposition.
+     * 
+     */
+    private double[][] LU;
+
+    /**
+     * Internal storage of pivot vector.
+     * 
+     */
+    private int[] piv;
+
+    private int pivsign;
+
+    /* ------------------------
+       Constructor
+     * ------------------------ */
+
+    /**
+     * LU Decomposition Structure to access L, U and piv.
+     * @param m 
+     * @param n 
+     * 
+     */
+
+    protected LUDecomp(int m, int n) {
+      
+      // Use a "left-looking", dot-product, Crout/Doolittle algorithm.
+
+      LU = getArrayCopy();
+      piv = new int[m];
+      for (int i = m; --i >= 0;)
+        piv[i] = i;
+      pivsign = 1;
+      double[] LUrowi;
+      double[] LUcolj = new double[m];
+
+      // Outer loop.
+
+      for (int j = 0; j < n; j++) {
+
+        // Make a copy of the j-th column to localize references.
+
+        for (int i = m; --i >= 0;)
+          LUcolj[i] = LU[i][j];
+
+        // Apply previous transformations.
+
+        for (int i = m; --i >= 0;) {
+          LUrowi = LU[i];
+
+          // Most of the time is spent in the following dot product.
+
+          int kmax = Math.min(i, j);
+          double s = 0.0;
+          for (int k = kmax; --k >= 0;)
+            s += LUrowi[k] * LUcolj[k];
+
+          LUrowi[j] = LUcolj[i] -= s;
+        }
+
+        // Find pivot and exchange if necessary.
+
+        int p = j;
+        for (int i = m; --i > j;)
+          if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p]))
+            p = i;
+        if (p != j) {
+          for (int k = n; --k >= 0;) {
+            double t = LU[p][k];
+            LU[p][k] = LU[j][k];
+            LU[j][k] = t;
+          }
+          int k = piv[p];
+          piv[p] = piv[j];
+          piv[j] = k;
+          pivsign = -pivsign;
+        }
+
+        // Compute multipliers.
+
+        if (j < m & LU[j][j] != 0.0)
+          for (int i = m; --i > j;)
+            LU[i][j] /= LU[j][j];
+      }
+    }
+
+    /* ------------------------
+       default Methods
+     * ------------------------ */
+
+    /**
+     * Solve A*X = B
+     * 
+     * @param b
+     *        A Matrix with as many rows as A and any number of columns.
+     * @param n 
+     * @return X so that L*U*X = B(piv,:) or null for wrong size or singular matrix
+     */
+
+    protected Matrix solve(Matrix b, int n) {
+      for (int j = 0; j < n; j++)
+        if (LU[j][j] == 0)
+          return null; // matrix is singular
+
+      // Copy right hand side with pivoting
+      int nx = b.n;
+      Matrix x = b.getMatrixSelected(piv, nx);
+      double[][] a = x.a;
+
+      // Solve L*Y = B(piv,:)
+      for (int k = 0; k < n; k++)
+        for (int i = k + 1; i < n; i++)
+          for (int j = 0; j < nx; j++)
+            a[i][j] -= a[k][j] * LU[i][k];
+
+      // Solve U*X = Y;
+      for (int k = n; --k >= 0;) {
+        for (int j = nx; --j >= 0;)
+          a[k][j] /= LU[k][k];
+        for (int i = k; --i >= 0;)
+          for (int j = nx; --j >= 0;)
+            a[i][j] -= a[k][j] * LU[i][k];
+      }
+      return x;
+    }
+  }
+
+}
diff --git a/src2/javajs/util/Measure.java b/src2/javajs/util/Measure.java
new file mode 100644 (file)
index 0000000..8b21cfe
--- /dev/null
@@ -0,0 +1,728 @@
+/* $RCSfile$
+ * $Author: egonw $
+ * $Date: 2005-11-10 09:52:44 -0600 (Thu, 10 Nov 2005) $
+ * $Revision: 4255 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2003-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.util;
+
+import javajs.api.EigenInterface;
+
+import javajs.api.Interface;
+
+
+
+
+//import org.jmol.script.T;
+
+final public class Measure {
+
+  public final static float radiansPerDegree = (float) (2 * Math.PI / 360);
+  
+  public static float computeAngle(T3 pointA, T3 pointB, T3 pointC, V3 vectorBA, V3 vectorBC, boolean asDegrees) {
+    vectorBA.sub2(pointA, pointB);
+    vectorBC.sub2(pointC, pointB);
+    float angle = vectorBA.angle(vectorBC);
+    return (asDegrees ? angle / radiansPerDegree : angle);
+  }
+
+  public static float computeAngleABC(T3 pointA, T3 pointB, T3 pointC, boolean asDegrees) {
+    V3 vectorBA = new V3();
+    V3 vectorBC = new V3();        
+    return computeAngle(pointA, pointB, pointC, vectorBA, vectorBC, asDegrees);
+  }
+
+  public static float computeTorsion(T3 p1, T3 p2, T3 p3, T3 p4, boolean asDegrees) {
+  
+    float ijx = p1.x - p2.x;
+    float ijy = p1.y - p2.y;
+    float ijz = p1.z - p2.z;
+  
+    float kjx = p3.x - p2.x;
+    float kjy = p3.y - p2.y;
+    float kjz = p3.z - p2.z;
+  
+    float klx = p3.x - p4.x;
+    float kly = p3.y - p4.y;
+    float klz = p3.z - p4.z;
+  
+    float ax = ijy * kjz - ijz * kjy;
+    float ay = ijz * kjx - ijx * kjz;
+    float az = ijx * kjy - ijy * kjx;
+    float cx = kjy * klz - kjz * kly;
+    float cy = kjz * klx - kjx * klz;
+    float cz = kjx * kly - kjy * klx;
+  
+    float ai2 = 1f / (ax * ax + ay * ay + az * az);
+    float ci2 = 1f / (cx * cx + cy * cy + cz * cz);
+  
+    float ai = (float) Math.sqrt(ai2);
+    float ci = (float) Math.sqrt(ci2);
+    float denom = ai * ci;
+    float cross = ax * cx + ay * cy + az * cz;
+    float cosang = cross * denom;
+    if (cosang > 1) {
+      cosang = 1;
+    }
+    if (cosang < -1) {
+      cosang = -1;
+    }
+  
+    float torsion = (float) Math.acos(cosang);
+    float dot = ijx * cx + ijy * cy + ijz * cz;
+    float absDot = Math.abs(dot);
+    torsion = (dot / absDot > 0) ? torsion : -torsion;
+    return (asDegrees ? torsion / radiansPerDegree : torsion);
+  }
+
+  /**
+   * This method calculates measures relating to two points in space 
+   * with related quaternion frame difference. It is used in Jmol for
+   * calculating straightness and many other helical quantities.
+   * 
+   * @param a
+   * @param b
+   * @param dq
+   * @return  new T3[] { pt_a_prime, n, r, P3.new3(theta, pitch, residuesPerTurn), pt_b_prime };
+   */
+  public static T3[] computeHelicalAxis(P3 a, P3 b, Quat dq) {
+    
+    //                b
+    //           |   /|
+    //           |  / |
+    //           | /  |
+    //           |/   c
+    //         b'+   / \
+    //           |  /   \      Vcb = Vab . n
+    //         n | /     \d    Vda = (Vcb - Vab) / 2
+    //           |/theta  \
+    //         a'+---------a
+    //                r 
+
+    V3 vab = new V3();
+    vab.sub2(b, a);
+    /*
+     * testing here to see if directing the normal makes any difference -- oddly
+     * enough, it does not. When n = -n and theta = -theta vab.n is reversed,
+     * and that magnitude is multiplied by n in generating the A'-B' vector.
+     * 
+     * a negative angle implies a left-handed axis (sheets)
+     */
+    float theta = dq.getTheta();
+    V3 n = dq.getNormal();
+    float v_dot_n = vab.dot(n);
+    if (Math.abs(v_dot_n) < 0.0001f)
+      v_dot_n = 0;
+    V3 va_prime_d = new V3();
+    va_prime_d.cross(vab, n);
+    if (va_prime_d.dot(va_prime_d) != 0)
+      va_prime_d.normalize();
+    V3 vda = new V3();
+    V3 vcb = V3.newV(n);
+    if (v_dot_n == 0)
+      v_dot_n = PT.FLOAT_MIN_SAFE; // allow for perpendicular axis to vab
+    vcb.scale(v_dot_n);
+    vda.sub2(vcb, vab);
+    vda.scale(0.5f);
+    va_prime_d.scale(theta == 0 ? 0 : (float) (vda.length() / Math.tan(theta
+        / 2 / 180 * Math.PI)));
+    V3 r = V3.newV(va_prime_d);
+    if (theta != 0)
+      r.add(vda);
+    P3 pt_a_prime = P3.newP(a);
+    pt_a_prime.sub(r);
+    // already done this. ??
+    if (v_dot_n != PT.FLOAT_MIN_SAFE)
+      n.scale(v_dot_n);
+    // must calculate directed angle:
+    P3 pt_b_prime = P3.newP(pt_a_prime);
+    pt_b_prime.add(n);
+    theta = computeTorsion(a, pt_a_prime, pt_b_prime, b, true);
+    if (Float.isNaN(theta) || r.length() < 0.0001f)
+      theta = dq.getThetaDirectedV(n); // allow for r = 0
+    // anything else is an array
+    float residuesPerTurn = Math.abs(theta == 0 ? 0 : 360f / theta);
+    float pitch = Math.abs(v_dot_n == PT.FLOAT_MIN_SAFE ? 0 : n.length()
+        * (theta == 0 ? 1 : 360f / theta));
+    return new T3[] { pt_a_prime, n, r, P3.new3(theta, pitch, residuesPerTurn), pt_b_prime };
+  }
+
+  public static P4 getPlaneThroughPoints(T3 pointA,
+                                              T3 pointB,
+                                              T3 pointC, V3 vNorm,
+                                              V3 vAB, P4 plane) {
+    float w = getNormalThroughPoints(pointA, pointB, pointC, vNorm, vAB);
+    plane.set4(vNorm.x, vNorm.y, vNorm.z, w);
+    return plane;
+  }
+  
+  public static void getPlaneThroughPoint(T3 pt, V3 normal, P4 plane) {
+    plane.set4(normal.x, normal.y, normal.z, -normal.dot(pt));
+  }
+  
+  public static float distanceToPlane(P4 plane, T3 pt) {
+    return (plane == null ? Float.NaN 
+        : (plane.dot(pt) + plane.w) / (float) Math.sqrt(plane.dot(plane)));
+  }
+
+  public static float directedDistanceToPlane(P3 pt, P4 plane, P3 ptref) {
+    float f = plane.dot(pt) + plane.w;
+    float f1 = plane.dot(ptref) + plane.w;
+    return Math.signum(f1) * f /  (float) Math.sqrt(plane.dot(plane));
+  }
+
+  public static float distanceToPlaneD(P4 plane, float d, P3 pt) {
+    return (plane == null ? Float.NaN : (plane.dot(pt) + plane.w) / d);
+  }
+
+  public static float distanceToPlaneV(V3 norm, float w, P3 pt) {
+    return (norm == null ? Float.NaN 
+        : (norm.dot(pt) + w)  / (float) Math.sqrt(norm.dot(norm)));
+  }
+
+  /**
+   * note that if vAB or vAC is dispensible, vNormNorm can be one of them
+   * @param pointA
+   * @param pointB
+   * @param pointC
+   * @param vNormNorm
+   * @param vAB
+   */
+  public static void calcNormalizedNormal(T3 pointA, T3 pointB,
+         T3 pointC, T3 vNormNorm, T3 vAB) {
+    vAB.sub2(pointB, pointA);
+    vNormNorm.sub2(pointC, pointA);
+    vNormNorm.cross(vAB, vNormNorm);
+    vNormNorm.normalize();
+  }
+
+  public static float getDirectedNormalThroughPoints(T3 pointA, 
+         T3 pointB, T3 pointC, T3 ptRef, V3 vNorm, 
+         V3 vAB) {
+    // for x = plane({atomno=1}, {atomno=2}, {atomno=3}, {atomno=4})
+    float nd = getNormalThroughPoints(pointA, pointB, pointC, vNorm, vAB);
+    if (ptRef != null) {
+      P3 pt0 = P3.newP(pointA);
+      pt0.add(vNorm);
+      float d = pt0.distance(ptRef);
+      pt0.sub2(pointA, vNorm);
+      if (d > pt0.distance(ptRef)) {
+        vNorm.scale(-1);
+        nd = -nd;
+      }
+    }
+    return nd;
+  }
+  
+  /**
+   * @param pointA
+   * @param pointB
+   * @param pointC
+   * @param vNorm
+   * @param vTemp
+   * @return w
+   */
+  public static float getNormalThroughPoints(T3 pointA, T3 pointB,
+                                   T3 pointC, T3 vNorm, T3 vTemp) {
+    // for Polyhedra
+    calcNormalizedNormal(pointA, pointB, pointC, vNorm, vTemp);
+    // ax + by + cz + d = 0
+    // so if a point is in the plane, then N dot X = -d
+    vTemp.setT(pointA);
+    return -vTemp.dot(vNorm);
+  }
+
+  public static void getPlaneProjection(P3 pt, P4 plane, P3 ptProj, V3 vNorm) {
+    float dist = distanceToPlane(plane, pt);
+    vNorm.set(plane.x, plane.y, plane.z);
+    vNorm.normalize();
+    vNorm.scale(-dist);
+    ptProj.add2(pt, vNorm);
+  }
+
+  /**
+   * 
+   * @param ptCenter
+   * @param ptA
+   * @param ptB
+   * @param ptC
+   * @param isOutward
+   * @param normal set to be opposite to direction of ptCenter from ABC
+   * @param vTemp
+   * @return true if winding is CCW; false if CW
+   */
+  public static boolean getNormalFromCenter(P3 ptCenter, P3 ptA, P3 ptB, P3 ptC,
+                                      boolean isOutward, V3 normal, V3 vTemp) {
+    float d = getNormalThroughPoints(ptA, ptB, ptC, normal, vTemp);
+    boolean isReversed = (distanceToPlaneV(normal, d, ptCenter) > 0);
+    if (isReversed == isOutward)
+      normal.scale(-1f);
+    return !isReversed;
+  }
+
+  public final static V3 axisY = V3.new3(0, 1, 0);
+  
+  public static void getNormalToLine(P3 pointA, P3 pointB,
+                                   V3 vNormNorm) {
+    // vector in xy plane perpendicular to a line between two points RMH
+    vNormNorm.sub2(pointA, pointB);
+    vNormNorm.cross(vNormNorm, axisY);
+    vNormNorm.normalize();
+    if (Float.isNaN(vNormNorm.x))
+      vNormNorm.set(1, 0, 0);
+  }
+  
+  public static void getBisectingPlane(P3 pointA, V3 vAB,
+                                                 T3 ptTemp, V3 vTemp, P4 plane) {
+    ptTemp.scaleAdd2(0.5f, vAB, pointA);
+    vTemp.setT(vAB);
+    vTemp.normalize();
+    getPlaneThroughPoint(ptTemp, vTemp, plane);
+    }
+    
+  public static void projectOntoAxis(P3 point, P3 axisA,
+                                     V3 axisUnitVector,
+                                     V3 vectorProjection) {
+    vectorProjection.sub2(point, axisA);
+    float projectedLength = vectorProjection.dot(axisUnitVector);
+    point.scaleAdd2(projectedLength, axisUnitVector, axisA);
+    vectorProjection.sub2(point, axisA);
+  }
+  
+  public static void calcBestAxisThroughPoints(P3[] points, P3 axisA,
+                                               V3 axisUnitVector,
+                                               V3 vectorProjection,
+                                               int nTriesMax) {
+    // just a crude starting point.
+
+    int nPoints = points.length;
+    axisA.setT(points[0]);
+    axisUnitVector.sub2(points[nPoints - 1], axisA);
+    axisUnitVector.normalize();
+
+    /*
+     * We now calculate the least-squares 3D axis
+     * through the helix alpha carbons starting with Vo
+     * as a first approximation.
+     * 
+     * This uses the simple 0-centered least squares fit:
+     * 
+     * Y = M cross Xi
+     * 
+     * minimizing R^2 = SUM(|Y - Yi|^2) 
+     * 
+     * where Yi is the vector PERPENDICULAR of the point onto axis Vo
+     * and Xi is the vector PROJECTION of the point onto axis Vo
+     * and M is a vector adjustment 
+     * 
+     * M = SUM_(Xi cross Yi) / sum(|Xi|^2)
+     * 
+     * from which we arrive at:
+     * 
+     * V = Vo + (M cross Vo)
+     * 
+     * Basically, this is just a 3D version of a 
+     * standard 2D least squares fit to a line, where we would say:
+     * 
+     * y = m xi + b
+     * 
+     * D = n (sum xi^2) - (sum xi)^2
+     * 
+     * m = [(n sum xiyi) - (sum xi)(sum yi)] / D
+     * b = [(sum yi) (sum xi^2) - (sum xi)(sum xiyi)] / D
+     * 
+     * but here we demand that the line go through the center, so we
+     * require (sum xi) = (sum yi) = 0, so b = 0 and
+     * 
+     * m = (sum xiyi) / (sum xi^2)
+     * 
+     * In 3D we do the same but 
+     * instead of x we have Vo,
+     * instead of multiplication we use cross products
+     * 
+     * A bit of iteration is necessary.
+     * 
+     * Bob Hanson 11/2006
+     * 
+     */
+
+    calcAveragePointN(points, nPoints, axisA);
+
+    int nTries = 0;
+    while (nTries++ < nTriesMax
+        && findAxis(points, nPoints, axisA, axisUnitVector, vectorProjection) > 0.001) {
+    }
+
+    /*
+     * Iteration here gets the job done.
+     * We now find the projections of the endpoints onto the axis
+     * 
+     */
+
+    P3 tempA = P3.newP(points[0]);
+    projectOntoAxis(tempA, axisA, axisUnitVector, vectorProjection);
+    axisA.setT(tempA);
+  }
+
+  public static float findAxis(P3[] points, int nPoints, P3 axisA,
+                        V3 axisUnitVector, V3 vectorProjection) {
+    V3 sumXiYi = new V3();
+    V3 vTemp = new V3();
+    P3 pt = new P3();
+    P3 ptProj = new P3();
+    V3 a = V3.newV(axisUnitVector);
+
+    float sum_Xi2 = 0;
+    for (int i = nPoints; --i >= 0;) {
+      pt.setT(points[i]);
+      ptProj.setT(pt);
+      projectOntoAxis(ptProj, axisA, axisUnitVector,
+          vectorProjection);
+      vTemp.sub2(pt, ptProj);
+      //sum_Yi2 += vTemp.lengthSquared();
+      vTemp.cross(vectorProjection, vTemp);
+      sumXiYi.add(vTemp);
+      sum_Xi2 += vectorProjection.lengthSquared();
+    }
+    V3 m = V3.newV(sumXiYi);
+    m.scale(1 / sum_Xi2);
+    vTemp.cross(m, axisUnitVector);
+    axisUnitVector.add(vTemp);
+    axisUnitVector.normalize();  
+    //check for change in direction by measuring vector difference length
+    vTemp.sub2(axisUnitVector, a);
+    return vTemp.length();
+  }
+  
+  
+  public static void calcAveragePoint(P3 pointA, P3 pointB,
+                                      P3 pointC) {
+    pointC.set((pointA.x + pointB.x) / 2, (pointA.y + pointB.y) / 2,
+        (pointA.z + pointB.z) / 2);
+  }
+  
+  public static void calcAveragePointN(P3[] points, int nPoints,
+                                P3 averagePoint) {
+    averagePoint.setT(points[0]);
+    for (int i = 1; i < nPoints; i++)
+      averagePoint.add(points[i]);
+    averagePoint.scale(1f / nPoints);
+  }
+
+  public static Lst<P3> transformPoints(Lst<P3> vPts, M4 m4, P3 center) {
+    Lst<P3> v = new  Lst<P3>();
+    for (int i = 0; i < vPts.size(); i++) {
+      P3 pt = P3.newP(vPts.get(i));
+      pt.sub(center);
+      m4.rotTrans(pt);
+      pt.add(center);
+      v.addLast(pt);
+    }
+    return v;
+  }
+
+  public static boolean isInTetrahedron(P3 pt, P3 ptA, P3 ptB,
+                                        P3 ptC, P3 ptD,
+                                        P4 plane, V3 vTemp,
+                                        V3 vTemp2, boolean fullyEnclosed) {
+    boolean b = (distanceToPlane(getPlaneThroughPoints(ptC, ptD, ptA, vTemp, vTemp2, plane), pt) >= 0);
+    if (b != (distanceToPlane(getPlaneThroughPoints(ptA, ptD, ptB, vTemp, vTemp2, plane), pt) >= 0))
+      return false;
+    if (b != (distanceToPlane(getPlaneThroughPoints(ptB, ptD, ptC, vTemp, vTemp2, plane), pt) >= 0))
+      return false;
+    float d = distanceToPlane(getPlaneThroughPoints(ptA, ptB, ptC, vTemp, vTemp2, plane), pt);
+    if (fullyEnclosed)
+      return (b == (d >= 0));
+    float d1 = distanceToPlane(plane, ptD);
+    return d1 * d <= 0 || Math.abs(d1) > Math.abs(d);
+  }
+
+
+  /**
+   * 
+   * @param plane1
+   * @param plane2
+   * @return       [ point, vector ] or []
+   */
+  public static Lst<Object> getIntersectionPP(P4 plane1, P4 plane2) {
+    float a1 = plane1.x;
+    float b1 = plane1.y;
+    float c1 = plane1.z;
+    float d1 = plane1.w;
+    float a2 = plane2.x;
+    float b2 = plane2.y;
+    float c2 = plane2.z;
+    float d2 = plane2.w;
+    V3 norm1 = V3.new3(a1, b1, c1);
+    V3 norm2 = V3.new3(a2, b2, c2);
+    V3 nxn = new V3();
+    nxn.cross(norm1, norm2);
+    float ax = Math.abs(nxn.x);
+    float ay = Math.abs(nxn.y);
+    float az = Math.abs(nxn.z);
+    float x, y, z, diff;
+    int type = (ax > ay ? (ax > az ? 1 : 3) : ay > az ? 2 : 3);
+    switch(type) {
+    case 1:
+      x = 0;
+      diff = (b1 * c2 - b2 * c1);
+      if (Math.abs(diff) < 0.01) return null;
+      y = (c1 * d2 - c2 * d1) / diff;
+      z = (b2 * d1 - d2 * b1) / diff;
+      break;
+    case 2:
+      diff = (a1 * c2 - a2 * c1);
+      if (Math.abs(diff) < 0.01) return null;
+      x = (c1 * d2 - c2 * d1) / diff;
+      y = 0;
+      z = (a2 * d1 - d2 * a1) / diff;
+      break;
+    case 3:
+    default:
+      diff = (a1 * b2 - a2 * b1);
+      if (Math.abs(diff) < 0.01) return null;
+      x = (b1 * d2 - b2 * d1) / diff;
+      y = (a2 * d1 - d2 * a1) / diff;
+      z = 0;
+    }
+    Lst<Object>list = new  Lst<Object>();
+    list.addLast(P3.new3(x, y, z));
+    nxn.normalize();
+    list.addLast(nxn);
+    return list;
+  }
+
+  /**
+   * 
+   * @param pt1  point on line
+   * @param v    unit vector of line
+   * @param plane 
+   * @param ptRet  point of intersection of line with plane
+   * @param tempNorm 
+   * @param vTemp 
+   * @return       ptRtet
+   */
+  public static P3 getIntersection(P3 pt1, V3 v,
+                                               P4 plane, P3 ptRet, V3 tempNorm, V3 vTemp) {
+    getPlaneProjection(pt1, plane, ptRet, tempNorm);
+    tempNorm.set(plane.x, plane.y, plane.z);
+    tempNorm.normalize();
+    if (v == null)
+      v = V3.newV(tempNorm);
+    float l_dot_n = v.dot(tempNorm);
+    if (Math.abs(l_dot_n) < 0.01) return null;
+    vTemp.sub2(ptRet, pt1);
+    ptRet.scaleAdd2(vTemp.dot(tempNorm) / l_dot_n, v, pt1);
+    return ptRet;
+  }
+
+       /*
+        * public static Point3f getTriangleIntersection(Point3f a1, Point3f a2,
+        * Point3f a3, Point4f plane, Point3f b1, Point3f b2, Point3f b3, Vector3f
+        * vNorm, Vector3f vTemp, Point3f ptRet, Point3f ptTemp, Vector3f vTemp2,
+        * Point4f pTemp, Vector3f vTemp3) {
+        * 
+        * if (getTriangleIntersection(b1, b2, a1, a2, a3, vTemp, plane, vNorm,
+        * vTemp2, vTemp3, ptRet, ptTemp)) return ptRet; if
+        * (getTriangleIntersection(b2, b3, a1, a2, a3, vTemp, plane, vNorm, vTemp2,
+        * vTemp3, ptRet, ptTemp)) return ptRet; if (getTriangleIntersection(b3, b1,
+        * a1, a2, a3, vTemp, plane, vNorm, vTemp2, vTemp3, ptRet, ptTemp)) return
+        * ptRet; return null; }
+        */
+       /*
+        * public static boolean getTriangleIntersection(Point3f b1, Point3f b2,
+        * Point3f a1, Point3f a2, Point3f a3, Vector3f vTemp, Point4f plane, Vector3f
+        * vNorm, Vector3f vTemp2, Vector3f vTemp3, Point3f ptRet, Point3f ptTemp) {
+        * if (distanceToPlane(plane, b1) * distanceToPlane(plane, b2) >= 0) return
+        * false; vTemp.sub(b2, b1); vTemp.normalize(); if (getIntersection(b1, vTemp,
+        * plane, ptRet, vNorm, vTemp2) != null) { if (isInTriangle(ptRet, a1, a2, a3,
+        * vTemp, vTemp2, vTemp3)) return true; } return false; } private static
+        * boolean isInTriangle(Point3f p, Point3f a, Point3f b, Point3f c, Vector3f
+        * v0, Vector3f v1, Vector3f v2) { // from
+        * http://www.blackpawn.com/texts/pointinpoly/default.html // Compute
+        * barycentric coordinates v0.sub(c, a); v1.sub(b, a); v2.sub(p, a); float
+        * dot00 = v0.dot(v0); float dot01 = v0.dot(v1); float dot02 = v0.dot(v2);
+        * float dot11 = v1.dot(v1); float dot12 = v1.dot(v2); float invDenom = 1 /
+        * (dot00 * dot11 - dot01 * dot01); float u = (dot11 * dot02 - dot01 * dot12)
+        * * invDenom; float v = (dot00 * dot12 - dot01 * dot02) * invDenom; return (u
+        * > 0 && v > 0 && u + v < 1); }
+        */
+
+       /**
+        * Closed-form solution of absolute orientation requiring 1:1 mapping of
+        * positions.
+        * 
+        * @param centerAndPoints
+        * @param retStddev
+        * @return unit quaternion representation rotation
+        * 
+        * @author hansonr Bob Hanson
+        * 
+        */
+       public static Quat calculateQuaternionRotation(P3[][] centerAndPoints,
+                       float[] retStddev) {
+               /*
+                * see Berthold K. P. Horn,
+                * "Closed-form solution of absolute orientation using unit quaternions" J.
+                * Opt. Soc. Amer. A, 1987, Vol. 4, pp. 629-642
+                * http://www.opticsinfobase.org/viewmedia.cfm?uri=josaa-4-4-629&seq=0
+                * 
+                * 
+                * A similar treatment was developed independently (and later!) by G.
+                * Kramer, in G. R. Kramer,
+                * "Superposition of Molecular Structures Using Quaternions" Molecular
+                * Simulation, 1991, Vol. 7, pp. 113-119.
+                * 
+                * In that treatment there is a lot of unnecessary calculation along the
+                * trace of matrix M (eqn 20). I'm not sure why the extra x^2 + y^2 + z^2 +
+                * x'^2 + y'^2 + z'^2 is in there, but they are unnecessary and only
+                * contribute to larger numerical averaging errors and additional processing
+                * time, as far as I can tell. Adding aI, where a is a scalar and I is the
+                * 4x4 identity just offsets the eigenvalues but doesn't change the
+                * eigenvectors.
+                * 
+                * and Lydia E. Kavraki, "Molecular Distance Measures"
+                * http://cnx.org/content/m11608/latest/
+                */
+
+
+               retStddev[1] = Float.NaN;
+               Quat q = new Quat();
+               P3[] ptsA = centerAndPoints[0];
+               P3[] ptsB = centerAndPoints[1];
+               int nPts = ptsA.length - 1;
+               if (nPts < 2 || ptsA.length != ptsB.length)
+                       return q;
+               double Sxx = 0, Sxy = 0, Sxz = 0, Syx = 0, Syy = 0, Syz = 0, Szx = 0, Szy = 0, Szz = 0;
+               P3 ptA = new P3();
+               P3 ptB = new P3();
+               P3 ptA0 = ptsA[0];
+               P3 ptB0 = ptsB[0];
+               for (int i = nPts + 1; --i >= 1;) {
+                       ptA.sub2(ptsA[i], ptA0);
+                       ptB.sub2(ptsB[i], ptB0);
+                       Sxx += (double) ptA.x * (double) ptB.x;
+                       Sxy += (double) ptA.x * (double) ptB.y;
+                       Sxz += (double) ptA.x * (double) ptB.z;
+                       Syx += (double) ptA.y * (double) ptB.x;
+                       Syy += (double) ptA.y * (double) ptB.y;
+                       Syz += (double) ptA.y * (double) ptB.z;
+                       Szx += (double) ptA.z * (double) ptB.x;
+                       Szy += (double) ptA.z * (double) ptB.y;
+                       Szz += (double) ptA.z * (double) ptB.z;
+               }
+               retStddev[0] = getRmsd(centerAndPoints, q);
+               double[][] N = new double[4][4];
+               N[0][0] = Sxx + Syy + Szz;
+               N[0][1] = N[1][0] = Syz - Szy;
+               N[0][2] = N[2][0] = Szx - Sxz;
+               N[0][3] = N[3][0] = Sxy - Syx;
+
+               N[1][1] = Sxx - Syy - Szz;
+               N[1][2] = N[2][1] = Sxy + Syx;
+               N[1][3] = N[3][1] = Szx + Sxz;
+
+               N[2][2] = -Sxx + Syy - Szz;
+               N[2][3] = N[3][2] = Syz + Szy;
+
+               N[3][3] = -Sxx - Syy + Szz;
+
+               // this construction prevents JavaScript from requiring preloading of Eigen
+
+               float[] v = ((EigenInterface) Interface.getInterface("javajs.util.Eigen"))
+                               .setM(N).getEigenvectorsFloatTransposed()[3];
+               q = Quat.newP4(P4.new4(v[1], v[2], v[3], v[0]));
+               retStddev[1] = getRmsd(centerAndPoints, q);
+               return q;
+       }
+
+  /**
+   * Fills a 4x4 matrix with rotation-translation of mapped points A to B.
+   * If centerA is null, this is a standard 4x4 rotation-translation matrix;
+   * otherwise, this 4x4 matrix is a rotation around a vector through the center of ptsA,
+   * and centerA is filled with that center; 
+   * Prior to Jmol 14.3.12_2014.02.14, when used from the JmolScript compare() function,
+   * this method returned the second of these options instead of the first.
+   * 
+   * @param ptsA
+   * @param ptsB
+   * @param m  4x4 matrix to be returned 
+   * @param centerA return center of rotation; if null, then standard 4x4 matrix is returned
+   * @return stdDev
+   */
+  public static float getTransformMatrix4(Lst<P3> ptsA, Lst<P3> ptsB, M4 m,
+                                          P3 centerA) {
+    P3[] cptsA = getCenterAndPoints(ptsA);
+    P3[] cptsB = getCenterAndPoints(ptsB);
+    float[] retStddev = new float[2];
+    Quat q = calculateQuaternionRotation(new P3[][] { cptsA, cptsB },
+        retStddev);
+    M3 r = q.getMatrix();
+    if (centerA == null)
+      r.rotate(cptsA[0]);
+    else
+      centerA.setT(cptsA[0]);
+    V3 t = V3.newVsub(cptsB[0], cptsA[0]);
+    m.setMV(r, t);
+    return retStddev[1];
+  }
+
+  /**
+   * from a list of points, create an array that includes the center
+   * point as the first point. This array is used as a starting point for
+   * a quaternion analysis of superposition.
+   * 
+   * @param vPts
+   * @return  array of points with first point center
+   */
+       public static P3[] getCenterAndPoints(Lst<P3> vPts) {
+         int n = vPts.size();
+         P3[] pts = new P3[n + 1];
+         pts[0] = new P3();
+         if (n > 0) {
+           for (int i = 0; i < n; i++) {
+             pts[0].add(pts[i + 1] = vPts.get(i));
+           }
+           pts[0].scale(1f / n);
+         }
+         return pts;
+       }
+
+  public static float getRmsd(P3[][] centerAndPoints, Quat q) {
+    double sum2 = 0;
+    P3[] ptsA = centerAndPoints[0];
+    P3[] ptsB = centerAndPoints[1];
+    P3 cA = ptsA[0];
+    P3 cB = ptsB[0];
+    int n = ptsA.length - 1;
+    P3 ptAnew = new P3();
+    
+    for (int i = n + 1; --i >= 1;) {
+      ptAnew.sub2(ptsA[i], cA);
+      q.transform2(ptAnew, ptAnew).add(cB);
+      sum2 += ptAnew.distanceSquared(ptsB[i]);
+    }
+    return (float) Math.sqrt(sum2 / n);
+  }
+
+}
diff --git a/src2/javajs/util/MessagePackReader.java b/src2/javajs/util/MessagePackReader.java
new file mode 100644 (file)
index 0000000..a0e6b8b
--- /dev/null
@@ -0,0 +1,716 @@
+package javajs.util;
+
+import java.io.BufferedInputStream;
+import java.io.InputStream;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javajs.api.GenericBinaryDocumentReader;
+
+/**
+ * A simple MessagePack reader. See https://github.com/msgpack/msgpack/blob/master/spec.md
+ * with very few dependencies.
+ * 
+ * Nuances: 
+ * 
+ *  Does not implement unsigned int32 or int64 (delivers simple integers in all cases).
+ *  Does not use doubles; just floats
+ *  
+ * Note: 
+ * 
+ *  homogeneousArrays == true will deliver null for empty array.
+ * 
+ * 
+ * Use in MMTF:
+ * 
+ * 
+ *     BufferedInputStream bs = [whatever]
+ *     
+ *      GenericBinaryDocument binaryDoc =  new javajs.util.BinaryDocument();
+ *   
+ *      binaryDoc.setStream(bs, true);
+ * 
+ * 
+ *     map = (new MessagePackReader(binaryDoc, true)).readMap();
+ * 
+ *     entities = (Object[]) map.get("entityList");
+ *
+ *     float[] x = (float[]) decode((byte[]) map.get("xCoordList"))
+ *     
+ * 
+ * @author Bob Hanson hansonr@stolaf.edu
+ */
+
+public class MessagePackReader {
+
+  private GenericBinaryDocumentReader doc;
+
+  private boolean isHomo;// homogeneous arrays -- use int[] not Integer
+
+  // these maps must be checked for the specific number of bits, in the following order:
+  private final static int POSITIVEFIXINT_x80 = 0x80; //0xxxxxxx
+  private final static int FIXMAP_xF0         = 0x80; //1000xxxx
+//  private final static int FIXARRAY_xF0       = 0x90; //1001xxxx
+  private final static int FIXSTR_xE0         = 0xa0; //101xxxxx
+  private final static int NEGATIVEFIXINT_xE0 = 0xe0; //111xxxxx
+  private final static int DEFINITE_xE0       = 0xc0; //110xxxxx
+  
+  private final static int NIL          = 0xc0;
+//  private final static int (NEVERUSED)        = 0xc1;
+  private final static int FALSE        = 0xc2;
+  private final static int TRUE         = 0xc3;
+  private final static int BIN8         = 0xc4;
+  private final static int BIN16        = 0xc5;
+  private final static int BIN32        = 0xc6;
+  private final static int EXT8         = 0xc7;
+  private final static int EXT16        = 0xc8;
+  private final static int EXT32        = 0xc9;
+  private final static int FLOAT32      = 0xca;
+  private final static int FLOAT64      = 0xcb;
+  private final static int UINT8        = 0xcc;
+  private final static int UINT16       = 0xcd;
+  private final static int UINT32       = 0xce;
+  private final static int UINT64       = 0xcf;
+  private final static int INT8         = 0xd0;
+  private final static int INT16        = 0xd1;
+  private final static int INT32        = 0xd2;
+  private final static int INT64        = 0xd3;
+  private final static int FIXEXT1      = 0xd4;
+  private final static int FIXEXT2      = 0xd5;
+  private final static int FIXEXT4      = 0xd6;
+  private final static int FIXEXT8      = 0xd7;
+  private final static int FIXEXT16     = 0xd8;
+  private final static int STR8         = 0xd9;
+  private final static int STR16        = 0xda;
+  private final static int STR32        = 0xdb;
+  private final static int ARRAY16      = 0xdc;
+  private final static int ARRAY32      = 0xdd;
+  private final static int MAP16        = 0xde;
+  private final static int MAP32        = 0xdf;
+
+  public MessagePackReader(GenericBinaryDocumentReader binaryDoc, boolean isHomogeneousArrays) {
+    isHomo = isHomogeneousArrays;
+    doc = binaryDoc;
+  }
+
+  public MessagePackReader() {
+    // for reflection
+  }
+  
+  public Map<String, Object> getMapForStream(BufferedInputStream is) throws Exception {
+    doc = new BinaryDocument().setStream(is, true);
+    Map<String, Object> map = readMap();
+    is.close();
+    return map;
+  }
+  
+  @SuppressWarnings("unchecked")
+  public Map<String, Object> readMap() throws Exception {
+    return (Map<String, Object>) getNext(null, 0);
+  }
+  
+  public Object getNext(Object array, int pt) throws Exception {
+    int b = doc.readByte() & 0xFF;
+    int be0 = b & 0xE0;
+    if ((b & POSITIVEFIXINT_x80) == 0) {
+      if (array != null) {
+        ((int[]) array)[pt] = b;
+        return null;
+      }
+      return Integer.valueOf(b);
+    }
+    switch (be0) {
+    case NEGATIVEFIXINT_xE0:
+      b = BC.intToSignedInt(b | 0xFFFFFF00);
+      if (array != null) {
+        ((int[]) array)[pt] = b;
+        return null;
+      }
+      return Integer.valueOf(b);
+    case FIXSTR_xE0: {
+      String s = doc.readString(b & 0x1F);
+      if (array != null) {
+        ((String[]) array)[pt] = s; 
+        return null;
+      } 
+      return s;
+    }
+    case FIXMAP_xF0:
+      return ((b & 0xF0) == FIXMAP_xF0 ? getMap(b & 0x0F) : getArray(b & 0x0F));
+    case DEFINITE_xE0:
+      switch (b) {
+      case NIL:
+        return null;
+      case FALSE:
+        return Boolean.FALSE;
+      case TRUE:
+        return Boolean.TRUE;
+      case EXT8:
+        return getObject(doc.readUInt8());
+      case EXT16:
+        return getObject(doc.readUnsignedShort());
+      case EXT32:
+        return getObject(doc.readInt()); // should be unsigned int
+      case FIXEXT1:
+        return getObject(1);
+      case FIXEXT2:
+        return getObject(2);
+      case FIXEXT4:
+        return getObject(4);
+      case FIXEXT8:
+        return getObject(8);
+      case FIXEXT16:
+        return getObject(16);
+      case ARRAY16:
+        return getArray(doc.readUnsignedShort());
+      case ARRAY32:
+        return getArray(doc.readInt());
+      case MAP16:
+        return getMap(doc.readUnsignedShort());
+      case MAP32:
+        return getMap(doc.readInt());
+
+        // binary arrays:
+
+      case BIN8:
+        return doc.readBytes(doc.readUInt8());
+      case BIN16:
+        return doc.readBytes(doc.readUnsignedShort());
+      case BIN32:
+        return doc.readBytes(doc.readInt());
+      }
+      if (array == null) {
+        switch (b) {
+        case FLOAT32:
+          return Float.valueOf(doc.readFloat());
+        case FLOAT64:
+          return Float.valueOf((float) doc.readDouble());
+        case UINT8:
+          return Integer.valueOf(doc.readUInt8());
+        case UINT16:
+          return Integer.valueOf(doc.readUnsignedShort());
+        case UINT32:
+          return Integer.valueOf(doc.readInt()); // technically should be UInt32
+        case UINT64:
+          return Long.valueOf(doc.readLong()); // should be unsigned long; incompatible with JavaScript!
+        case INT8:
+          return Integer.valueOf(doc.readByte());
+        case INT16:
+          return Integer.valueOf(doc.readShort());
+        case INT32:
+          return Integer.valueOf(doc.readInt()); // should be Unsigned Int here
+        case INT64:
+          return Long.valueOf(doc.readLong());
+        case STR8:
+          return doc.readString(doc.readUInt8());
+        case STR16:
+          return doc.readString(doc.readShort());
+        case STR32:
+          return doc.readString(doc.readInt());
+        }
+      } else {
+        switch (b) {
+        case FLOAT32:
+          ((float[]) array)[pt] = doc.readFloat();
+          break;
+        case FLOAT64:
+          ((float[]) array)[pt] = (float) doc.readDouble();
+          break;
+        case UINT8:
+          ((int[]) array)[pt] = doc.readUInt8();
+          break;
+        case UINT16:
+          ((int[]) array)[pt] = doc.readUnsignedShort();
+          break;
+        case UINT32:
+          ((int[]) array)[pt] =  doc.readInt(); // should be unsigned int
+          break;
+        case UINT64:
+          ((int[]) array)[pt] =  (int) doc.readLong(); // should be unsigned long; incompatible with JavaScript!
+          break;
+        case INT8:
+          ((int[]) array)[pt] =  doc.readByte();
+          break;
+        case INT16:
+          ((int[]) array)[pt] = doc.readShort();
+          break;
+        case INT32:
+          ((int[]) array)[pt] =  doc.readInt(); // should be Unsigned Int here
+          break;
+        case INT64:
+          ((int[]) array)[pt] =  (int) doc.readLong();
+          break;
+        case STR8:
+          ((String[]) array)[pt] = doc.readString(doc.readUInt8());
+          break;
+        case STR16:
+          ((String[]) array)[pt] = doc.readString(doc.readShort());
+          break;
+        case STR32:
+          ((String[]) array)[pt] = doc.readString(doc.readInt());
+          break;
+        }
+      }
+    }
+    return null;
+  }
+
+  private Object getObject(int n) throws Exception {
+    return new Object[] { Integer.valueOf(doc.readUInt8()), doc.readBytes(n) };
+  }
+
+  private Object getArray(int n) throws Exception {
+    if (isHomo) {
+      if (n == 0)
+        return null;
+      Object v = getNext(null, 0);
+      if (v instanceof Integer) {
+        int[] a = new int[n];
+        a[0] = ((Integer) v).intValue();
+        v = a;
+      } else if (v instanceof Float) {
+        float[] a = new float[n];
+        a[0] = ((Float) v).floatValue();
+        v = a;
+      } else if (v instanceof String) {
+        String[] a = new String[n];
+        a[0] = (String) v;
+        v = a;
+      } else {
+        Object[] o = new Object[n];
+        o[0] = v;
+        for (int i = 1; i < n; i++)
+          o[i] = getNext(null, 0);
+        return o;
+      }
+      for (int i = 1; i < n; i++)
+        getNext(v, i);
+      return v;
+    }
+    Object[] o = new Object[n];
+    for (int i = 0; i < n; i++)
+      o[i] = getNext(null, 0);
+    return o;
+  }
+
+  private Object getMap(int n) throws Exception {
+    Map<String, Object> map = new Hashtable<String, Object>();
+    for (int i = 0; i < n; i++) {
+      String key = getNext(null, 0).toString();
+      //Logger.info(key);
+
+      Object value = getNext(null, 0);
+      if (value == null) {
+        //Logger.info("null value for " + key);
+      } else {
+        map.put(key, value);
+      }
+    }
+    return map;
+  }
+
+  /////////////// MMTF MessagePack decoding ///////////////
+
+  /**
+   * This single method takes care of all MMTF needs.
+   * 
+   * See https://github.com/rcsb/mmtf/blob/master/spec.md
+   * 
+   * @param b
+   * 
+   * @return array of int, char, or float, depending upon the type
+   */
+  public static Object decode(byte[] b) {
+    int type = BC.bytesToInt(b, 0, true);
+    int n = BC.bytesToInt(b, 4, true);
+    int param = BC.bytesToInt(b, 8, true);
+    switch (type) {
+    case 1:
+      return getFloats(b, n, 1);
+    case 2: // 1-byte
+    case 3: // 2-byte
+    case 4: // 4-byte
+      return getInts(b, n);
+    case 5:
+      return rldecode32ToStr(b);
+    case 6:
+      return rldecode32ToChar(b, n);
+    case 7:
+      return rldecode32(b, n);
+    case 8:
+      return rldecode32Delta(b, n);
+    case 9:
+      return rldecodef(b, n, param);
+    case 10:
+      return unpack16Deltaf(b, n, param);
+    case 11:
+      return getFloats(b, n, param);
+    case 12: // two-byte
+    case 13: // one-byte
+      return unpackf(b, 14 - type, n, param);
+    case 14: // two-byte
+    case 15: // one-byte
+      return unpack(b, 16 - type, n);
+    default:
+      System.out.println("MMTF type " + type + " not found!");
+      return null;
+   }
+  }
+
+  /**
+   * mmtf type 1 and 11
+   * 
+   * byte[4] to float32
+   * 
+   * @param b
+   * @param n
+   * @param divisor
+   * @return array of floats
+   */
+  public static float[] getFloats(byte[] b, int n, float divisor) {
+    if (b == null)
+      return null;
+    float[] a = new float[n];
+    try {
+      switch ((b.length - 12) / n) {  
+      case 2:
+        for (int i = 0, j = 12; i < n; i++, j += 2)
+          a[i] = BC.bytesToShort(b, j, false) / divisor;
+        break;
+      case 4:
+        for (int i = 0, j = 12; i < n; i++, j += 4)
+          a[i] = BC.bytesToFloat(b, j, false);
+        break;
+      }
+    } catch (Exception e) {
+    }
+    return a;
+  }
+
+  /**
+   * mmtf types 2-4
+   * 
+   * Decode a byte array into a byte, short, or int array.
+   * 
+   * @param b
+   * @param n
+   *        
+   * @return array of integers
+   */
+  public static int[] getInts(byte[] b, int n) {
+    if (b == null)
+      return null;
+    int[] a = new int[n];
+    switch ((b.length - 12) / n) {
+    case 1:
+      for (int i = 0, j = 12; i < n; i++, j++)
+        a[i] = b[j];
+      break;
+    case 2:
+      for (int i = 0, j = 12; i < n; i++, j += 2)
+        a[i] = BC.bytesToShort(b, j, true);
+      break;
+    case 4:
+      for (int i = 0, j = 12; i < n; i++, j += 4)
+        a[i] = BC.bytesToInt(b, j, true);
+      break;
+    }
+    return a;
+  }
+
+  /**
+   * mmtf type 5
+   * 
+   * Decode each four bytes as a 1- to 4-character string label where a 0 byte
+   * indicates end-of-string.
+   * 
+   * @param b
+   *        a byte array
+   * @return String[]
+   */
+  public static String[] rldecode32ToStr(byte[] b) {
+    String[] id = new String[(b.length - 12) / 4];
+    out: for (int i = 0, len = id.length, pt = 12; i < len; i++) {
+      SB sb = new SB();
+      for (int j = 0; j < 4; j++) {
+        switch (b[pt]) {
+        case 0:
+          id[i] = sb.toString();
+          pt += 4 - j;
+          continue out;
+        default:
+          sb.appendC((char) b[pt++]);
+          if (j == 3)
+            id[i] = sb.toString();
+          continue;
+        }
+      }
+    }
+    return id;
+  }
+
+  /**
+   * mmtf type 6
+   * 
+   * Decode an array of int32 using run-length decoding to one char per int.
+   * 
+   * @param b
+   * @param n
+   * @return array of characters
+   */
+  public static char[] rldecode32ToChar(byte[] b, int n) {
+    if (b == null)
+      return null;
+    char[] ret = new char[n];
+    for (int i = 0, pt = 3; i < n;) {
+      char val = (char) b[((pt++) << 2) + 3];
+      for (int j = BC.bytesToInt(b, (pt++) << 2, true); --j >= 0;)
+        ret[i++] = val;
+    }
+    return ret;
+  }
+
+  /**
+   * mmtf type 7
+   * 
+   * Decode an array of int32 using run-length decoding.
+   * 
+   * @param b
+   * @param n
+   * @return array of integers
+   */
+  public static int[] rldecode32(byte[] b, int n) {
+    if (b == null)
+      return null;
+    int[] ret = new int[n];
+    for (int i = 0, pt = 3; i < n;) {
+      int val = BC.bytesToInt(b, (pt++) << 2, true);
+      for (int j = BC.bytesToInt(b, (pt++) << 2, true); --j >= 0;)
+        ret[i++] = val;
+    }
+    return ret;
+  }
+
+  /**
+   * mmtf type 8
+   * 
+   * Decode an array of int32 using run-length decoding of a difference array.
+   * 
+   * @param b
+   * @param n
+   * @return array of integers
+   */
+  public static int[] rldecode32Delta(byte[] b, int n) {
+    if (b == null)
+      return null;
+    int[] ret = new int[n];
+    for (int i = 0, pt = 3, val = 0; i < n;) {
+      int diff = BC.bytesToInt(b, (pt++) << 2, true);
+      for (int j = BC.bytesToInt(b, (pt++) << 2, true); --j >= 0;)
+        ret[i++] = (val = val + diff);
+    }
+    return ret;
+  }
+
+  /**
+   * mmtf type 9
+   * 
+   * Decode an array of int32 using run-length decoding and divide by a divisor
+   * to give a float32.
+   * 
+   * @param b
+   * @param n
+   * @param divisor
+   * @return array of floats
+   */
+  public static float[] rldecodef(byte[] b, int n, float divisor) {
+    if (b == null)
+      return null;
+    float[] ret = new float[n];
+    for (int i = 0, pt = 3; i < n;) {
+      int val = BC.bytesToInt(b, (pt++) << 2, true);
+      for (int j = BC.bytesToInt(b, (pt++) << 2, true); --j >= 0;)
+        ret[i++] = val / divisor;
+    }
+    return ret;
+  }
+
+  /**
+   * 
+   * mmtf type 10
+   * 
+   * Decode an array of int16 using run-length decoding of a difference array.
+   * 
+   * @param b
+   * @param n
+   * @param divisor
+   * @return array of floats
+   */
+  public static float[] unpack16Deltaf(byte[] b, int n, float divisor) {
+    if (b == null)
+      return null;
+    float[] ret = new float[n];
+    for (int i = 0, pt = 6, val = 0, buf = 0; i < n;) {
+      int diff = BC.bytesToShort(b, (pt++) << 1, true);
+      if (diff == Short.MAX_VALUE || diff == Short.MIN_VALUE) {
+        buf += diff;
+      } else {
+        ret[i++] = (val = val + diff + buf) / divisor;
+        buf = 0;
+      }
+    }
+    return ret;
+  }
+
+  /**
+   * 
+   * mmtf type 12 and 13
+   * 
+   * Unpack an array of int8 or int16 to int32 and divide to give a float32.
+   * 
+   * untested
+   * 
+   * @param b
+   * @param nBytes 
+   * @param n
+   * @param divisor 
+   * @return array of floats
+   */
+  public static float[] unpackf(byte[] b, int nBytes, int n, float divisor) {
+    if (b == null)
+      return null;
+    float[] ret = new float[n];
+    switch (nBytes) {
+    case 1:
+      for (int i = 0, pt = 12, offset = 0; i < n;) {
+        int val = b[pt++];
+        if (val == Byte.MAX_VALUE || val == Byte.MIN_VALUE) {
+          offset += val;
+        } else {
+          ret[i++] = (val + offset) / divisor;
+          offset = 0;
+        }
+      }
+      break;
+    case 2:
+      for (int i = 0, pt = 6, offset = 0; i < n;) {
+        int val = BC.bytesToShort(b, (pt++) << 1, true);
+        if (val == Short.MAX_VALUE || val == Short.MIN_VALUE) {
+          offset += val;
+        } else {
+          ret[i++] = (val + offset) / divisor;
+          offset = 0;
+        }
+      }
+      break;
+    }
+    return ret;
+  }
+
+  /**
+   * 
+   * mmtf type 14 and 15
+   * 
+   * Unpack an array of int8 or int16 to int32.
+   * 
+   * untested
+   * 
+   * @param b
+   * @param nBytes 
+   * @param n
+   * @return array of integers
+   */
+  public static int[] unpack(byte[] b, int nBytes, int n) {
+    if (b == null)
+      return null;
+    int[] ret = new int[n];
+    switch (nBytes) {
+    case 1:
+      for (int i = 0, pt = 12, offset = 0; i < n;) {
+        int val = b[pt++];
+        if (val == Byte.MAX_VALUE || val == Byte.MIN_VALUE) {
+          offset += val;
+        } else {
+          ret[i++] = val + offset;
+          offset = 0;
+        }
+      }
+      break;
+    case 2:
+      for (int i = 0, pt = 6, offset = 0; i < n;) {
+        int val = BC.bytesToShort(b, (pt++) << 1, true);
+        if (val == Short.MAX_VALUE || val == Short.MIN_VALUE) {
+          offset += val;
+        } else {
+          ret[i++] = val + offset;
+          offset = 0;
+        }
+      }
+      break;
+    }
+    return ret;
+  }
+
+  ///**
+  //* Decode an array of int16 using run-length decoding
+  //* of a difference array.
+  //* 
+  //* @param b
+  //* @param n
+  //* @param i0 
+  //* @return array of integers
+  //*/
+  //public static int[] rldecode16Delta(byte[] b, int n, int i0) {
+  //if (b == null)
+  //return null;
+  //int[] ret = new int[n];
+  //for (int i = 0, pt = i0 / 2, val = 0; i < n;) {
+  //int diff = BC.bytesToShort(b, (pt++) << 1, true);
+  //for (int j = BC.bytesToShort(b, (pt++) << 1, true); --j >= 0;)
+  //ret[i++] = (val = val + diff);
+  //}
+  //return ret;
+  //}
+
+  ///**
+  //* Do a split delta to a float[] array
+  //* @param xyz label "x", "y", "z", or "bFactor"
+  //* @param factor for dividing in the end -- 1000f or 100f 
+  //* @return float[]
+  //* 
+  //*/ 
+  //public static float[] getFloatsSplit(String xyz, float factor) {
+  //byte[] big = (byte[]) map.get(xyz + "Big");
+  //return (big == null ? null : splitDelta(big,
+  //(byte[]) map.get(xyz + "Small"), fileAtomCount, factor));
+  //}
+
+  ///**
+  //* Do a split delta to a float[] array
+  //* 
+  //* @param big
+  //*        [n m n m n m...] where n is a "big delta" and m is a number of
+  //*        "small deltas
+  //* @param small
+  //*        array containing the small deltas
+  //* @param n
+  //*        the size of the final array
+  //* @param factor
+  //*        to divide the final result by -- 1000f or 100f here
+  //* @return float[]
+  //*/
+  //public static float[] splitDelta(byte[] big, byte[] small, int n, float factor) {
+  //float[] ret = new float[n];
+  //for (int i = 0, smallpt = 0, val = 0, datapt = 0, len = big.length >> 2; i < len; i++) {
+  //ret[datapt++] = (val = val + BC.bytesToInt(big, i << 2, true)) / factor;
+  //if (++i < len)
+  //for (int j = BC.bytesToInt(big, i << 2, true); --j >= 0; smallpt++)
+  //ret[datapt++] = (val = val + BC.bytesToShort(small, smallpt << 1, true))
+  //  / factor;
+  //}
+  //return ret;
+  //}
+  //
+
+
+}
diff --git a/src2/javajs/util/OC.java b/src2/javajs/util/OC.java
new file mode 100644 (file)
index 0000000..98151d1
--- /dev/null
@@ -0,0 +1,416 @@
+package javajs.util;
+
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import javajs.api.BytePoster;
+import javajs.api.GenericOutputChannel;
+import javajs.api.js.J2SObjectInterface;
+
+/**
+ * 
+ * A generic output method. JmolOutputChannel can be used to:
+ * 
+ * add characters to a StringBuffer 
+ *   using fileName==null, append() and toString()
+ *   
+ * add bytes utilizing ByteArrayOutputStream 
+ *   using writeBytes(), writeByteAsInt(), append()*, and bytesAsArray()
+ *       *append() can be used as long as os==ByteArrayOutputStream
+ *        or it is not used before one of the writeByte methods. 
+ * 
+ * output characters to a FileOutputStream 
+ *  using os==FileOutputStream, asWriter==true, append(), and closeChannel()
+ *  
+ * output bytes to a FileOutputStream 
+ *  using os==FileOutputStream, writeBytes(), writeByteAsInt(), append(), and closeChannel()
+ * 
+ * post characters or bytes to a remote server
+ *  using fileName=="http://..." or "https://...",
+ *    writeBytes(), writeByteAsInt(), append(), and closeChannel()
+ *    
+ * send characters or bytes to a JavaScript function
+ *  when JavaScript and (typeof fileName == "function")
+ *  
+ * if fileName equals ";base64,", then the data are base64-encoded
+ * prior to writing, and closeChannel() returns the data.
+ * 
+ *  @author hansonr  Bob Hanson hansonr@stolaf.edu  9/2013
+ *  
+ *  
+ */
+
+public class OC extends OutputStream implements GenericOutputChannel {
+  private BytePoster bytePoster; // only necessary for writing to http:// or https://
+  private String fileName;
+  private BufferedWriter bw;
+  private boolean isLocalFile;
+  private int byteCount;
+  private boolean isCanceled;
+  private boolean closed;
+  private OutputStream os;
+  private SB sb;
+  private String type;
+       private boolean isBase64;
+       private OutputStream os0;
+       private byte[] bytes; // preset bytes; output only
+  
+       public boolean bigEndian = true;
+  
+  @Override
+  public boolean isBigEndian() {
+    return bigEndian;
+  }
+
+  public void setBigEndian(boolean TF) {
+       bigEndian = TF;
+  }
+
+  public OC setParams(BytePoster bytePoster, String fileName,
+                                     boolean asWriter, OutputStream os) {
+    this.bytePoster = bytePoster;
+    isBase64 = ";base64,".equals(fileName);
+    if (isBase64) {
+       fileName = null;
+       os0 = os;
+       os = null;
+    }
+    this.fileName = fileName;
+    this.os = os;
+    isLocalFile = (fileName != null && !isRemote(fileName));
+    if (asWriter && !isBase64 && os != null) 
+       bw = Rdr.getBufferedWriter(os, null);
+    return this;
+  }
+
+  public OC setBytes(byte[] b) {
+       bytes = b;
+       return this;
+  }
+  
+  public String getFileName() {
+    return fileName;
+  }
+  
+  public String getName() {
+    return (fileName == null ? null : fileName.substring(fileName.lastIndexOf("/") + 1));
+  }
+
+  public int getByteCount() {
+    return byteCount;
+  }
+
+  /**
+   * 
+   * @param type  user-identified type (PNG, JPG, etc)
+   */
+  public void setType(String type) {
+    this.type = type;
+  }
+  
+  public String getType() {
+    return type;
+  }
+
+  /**
+   * will go to string buffer if bw == null and os == null
+   * 
+   * @param s
+   * @return this, for chaining like a standard StringBuffer
+   * 
+   */
+  public OC append(String s) {
+    try {
+      if (bw != null) {
+        bw.write(s);
+      } else if (os == null) {
+        if (sb == null)
+          sb = new SB();
+        sb.append(s);
+      } else {
+        byte[] b = s.getBytes();
+        os.write(b, 0, b.length);
+        byteCount += b.length;
+        return this;
+      }
+    } catch (IOException e) {
+      // ignore
+    }
+    byteCount += s.length(); // not necessarily exactly correct if unicode
+    return this;
+  }
+
+  @Override
+  public void reset() {
+    sb = null;
+    initOS();
+  }
+
+
+  private void initOS() {
+    if (sb != null) {
+      String s = sb.toString();
+      reset();
+      append(s);
+      return;
+    }
+    try {
+      /**
+       * @j2sNative
+       * 
+       *            this.os = null;
+       */
+      {
+        if (os instanceof FileOutputStream) {
+          os.close();
+          os = new FileOutputStream(fileName);
+        } else {
+          os = null;
+        }
+      }
+      if (os == null)
+        os = new ByteArrayOutputStream();
+      if (bw != null) {
+        bw.close();
+        bw = Rdr.getBufferedWriter(os, null);
+      }
+    } catch (Exception e) {
+      // not perfect here.
+      System.out.println(e.toString());
+    }
+    byteCount = 0;
+  }
+
+  /**
+   * @param b  
+   */
+  @Override
+  public void writeByteAsInt(int b) {
+    if (os == null)
+      initOS();
+    {
+      try {
+        os.write(b);
+      } catch (IOException e) {
+      }
+    }
+    byteCount++;
+  }
+  
+  @Override
+  public void write(byte[] buf, int i, int len) {
+    if (os == null)
+      initOS();
+    try {
+      os.write(buf, i, len);
+    } catch (IOException e) {
+    }
+    byteCount += len;
+  }
+  
+  @Override
+  public void writeShort(short i) {
+    if (isBigEndian()) {
+      writeByteAsInt(i >> 8);
+      writeByteAsInt(i);
+    } else {
+      writeByteAsInt(i);
+      writeByteAsInt(i >> 8);
+    }
+  }
+
+  @Override
+  public void writeLong(long b) {
+    if (isBigEndian()) {
+      writeInt((int) ((b >> 32) & 0xFFFFFFFFl));
+      writeInt((int) (b & 0xFFFFFFFFl));
+    } else {
+      writeByteAsInt((int) (b >> 56));
+      writeByteAsInt((int) (b >> 48));
+      writeByteAsInt((int) (b >> 40));
+      writeByteAsInt((int) (b >> 32));
+      writeByteAsInt((int) (b >> 24));
+      writeByteAsInt((int) (b >> 16));
+      writeByteAsInt((int) (b >> 8));
+      writeByteAsInt((int) b);
+    }
+  }
+
+  public void write(int b) {
+    // required by standard ZipOutputStream -- do not use, as it will break JavaScript methods
+    if (os == null)
+      initOS();
+    try {
+      os.write(b);
+    } catch (IOException e) {
+    }
+    byteCount++;
+  }
+
+  public void write(byte[] b) {
+    // not used in JavaScript due to overloading problem there
+    write(b, 0, b.length);
+  }
+
+  public void cancel() {
+    isCanceled = true;
+    closeChannel();
+  }
+
+  @Override
+  @SuppressWarnings({ "unused" })
+  public String closeChannel() {
+    if (closed)
+      return null;
+    // can't cancel file writers
+    try {
+      if (bw != null) {
+        bw.flush();
+        bw.close();
+      } else if (os != null) {
+        os.flush();
+        os.close();
+      }
+      if (os0 != null && isCanceled) {
+        os0.flush();
+        os0.close();
+      }
+    } catch (Exception e) {
+      // ignore closing issues
+    }
+    if (isCanceled) {
+      closed = true;
+      return null;
+    }
+    if (fileName == null) {
+      if (isBase64) {
+        String s = getBase64();
+        if (os0 != null) {
+          os = os0;
+          append(s);
+        }
+        sb = new SB();
+        sb.append(s);
+        isBase64 = false;
+        return closeChannel();
+      }
+      return (sb == null ? null : sb.toString());
+    }
+    closed = true;
+    J2SObjectInterface jmol = null;
+    Object _function = null;
+    /**
+     * @j2sNative
+     * 
+     *            jmol = self.J2S || Jmol; _function = (typeof this.fileName == "function" ?
+     *            this.fileName : null);
+     * 
+     */
+    {
+      if (!isLocalFile) {
+        String ret = postByteArray(); // unsigned applet could do this
+        if (ret.startsWith("java.net"))
+          byteCount = -1;
+        return ret;
+      }
+    }
+    if (jmol != null) {
+      Object data = (sb == null ? toByteArray() : sb.toString());
+      if (_function == null)
+        jmol._doAjax(fileName, null, data, sb == null);
+      else
+        jmol._apply(_function, data);
+    }
+    return null;
+  }
+
+       public boolean isBase64() {
+               return isBase64;
+       }
+
+       public String getBase64() {
+    return Base64.getBase64(toByteArray()).toString();
+       }
+       
+  public byte[] toByteArray() {
+    return (bytes != null ? bytes : os instanceof ByteArrayOutputStream ? ((ByteArrayOutputStream)os).toByteArray() : null);
+  }
+
+  @Override
+  @Deprecated
+  public void close() {
+    closeChannel();
+  }
+
+  @Override
+  public String toString() {
+    if (bw != null)
+      try {
+        bw.flush();
+      } catch (IOException e) {
+        // TODO
+      }
+    if (sb != null)
+      return closeChannel();
+    return byteCount + " bytes";
+  }
+
+  private String postByteArray() {
+    byte[] bytes = (sb == null ? toByteArray() : sb.toString().getBytes());
+    return bytePoster.postByteArray(fileName, bytes);
+  }
+
+  public final static String[] urlPrefixes = { "http:", "https:", "sftp:", "ftp:",
+  "file:" };
+  // note that SFTP is not supported
+  public final static int URL_LOCAL = 4;
+
+  public static boolean isRemote(String fileName) {
+    if (fileName == null)
+      return false;
+    int itype = urlTypeIndex(fileName);
+    return (itype >= 0 && itype != URL_LOCAL);
+  }
+
+  public static boolean isLocal(String fileName) {
+    if (fileName == null)
+      return false;
+    int itype = urlTypeIndex(fileName);
+    return (itype < 0 || itype == URL_LOCAL);
+  }
+
+  public static int urlTypeIndex(String name) {
+    if (name == null)
+      return -2; // local unsigned applet
+    for (int i = 0; i < urlPrefixes.length; ++i) {
+      if (name.startsWith(urlPrefixes[i])) {
+        return i;
+      }
+    }
+    return -1;
+  }
+
+  @Override
+  public void writeInt(int i) {
+    if (bigEndian) {
+      writeByteAsInt(i >> 24);
+      writeByteAsInt(i >> 16);
+      writeByteAsInt(i >> 8);
+      writeByteAsInt(i);
+    } else {
+      writeByteAsInt(i);
+      writeByteAsInt(i >> 8);
+      writeByteAsInt(i >> 16);
+      writeByteAsInt(i >> 24);
+    }
+  }
+
+  public void writeFloat(float x) {
+    writeInt(x == 0 ? 0 : Float.floatToIntBits(x));
+  }
+
+}
diff --git a/src2/javajs/util/P3.java b/src2/javajs/util/P3.java
new file mode 100644 (file)
index 0000000..1e1dfdb
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+
+
+/**
+ * A 3 element point that is represented by single precision floating point
+ * x,y,z coordinates.
+ * 
+ * @version specification 1.1, implementation $Revision: 1.10 $, $Date:
+ *          2006/09/08 20:20:20 $
+ * @author Kenji hiranabe
+ * 
+ * additions by Bob Hanson hansonr@stolaf.edu 9/30/2012
+ * for unique constructor and method names
+ * for the optimization of compiled JavaScript using Java2Script
+ * 
+ */
+public class P3 extends T3 {
+
+  public P3() {
+    // ignore T3
+  }
+  
+  public static P3 newP(T3 t) {
+    P3 p = new P3();
+    p.x = t.x;
+    p.y = t.y;
+    p.z = t.z;
+    return p;
+  }
+
+  private static P3 unlikely;
+  
+  public static P3 getUnlikely() {
+    return (unlikely == null ? unlikely = new3((float) Math.PI, (float) Math.E, (float) (Math.PI * Math.E)) : unlikely);
+  }
+  
+  public static P3 new3(float x, float y, float z) {
+    P3 p = new P3();
+    p.x = x;
+    p.y = y;
+    p.z = z;
+    return p;
+  }
+
+}
diff --git a/src2/javajs/util/P3i.java b/src2/javajs/util/P3i.java
new file mode 100644 (file)
index 0000000..8f39550
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+
+
+/**
+ * A 3 element point that is represented by signed integer x,y,z coordinates.
+ * 
+ * @since Java 3D 1.2
+ * @version specification 1.2, implementation $Revision: 1.9 $, $Date:
+ *          2006/07/28 17:01:33 $
+ * @author Kenji hiranabe
+ * 
+ * 
+ *         additions by Bob Hanson hansonr@stolaf.edu 9/30/2012 for unique
+ *         constructor and method names for the optimization of compiled
+ *         JavaScript using Java2Script
+ */
+public class P3i extends T3i {
+
+  public static P3i new3(int x, int y, int z) {
+    P3i pt = new P3i();
+    pt.x = x;
+    pt.y = y;
+    pt.z = z;
+    return pt;
+  }
+}
diff --git a/src2/javajs/util/P4.java b/src2/javajs/util/P4.java
new file mode 100644 (file)
index 0000000..6478602
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+
+
+/**
+ * A 4 element point that is represented by single precision floating point
+ * x,y,z,w coordinates.
+ * 
+ * @version specification 1.1, implementation $Revision: 1.9 $, $Date:
+ *          2006/07/28 17:01:32 $
+ * @author Kenji hiranabe
+ * 
+ * additions by Bob Hanson hansonr@stolaf.edu 9/30/2012
+ * for unique constructor and method names
+ * for the optimization of compiled JavaScript using Java2Script
+ */
+public class P4 extends T4 {
+
+  public P4() {
+    // skip T4() constructor
+  }
+  
+  public static P4 new4(float x, float y, float z, float w) {
+    P4 pt = new P4();
+    pt.set4(x, y, z, w);
+    return pt;
+  }
+
+  public static P4 newPt(P4 value) {
+    P4 pt = new P4();
+    pt.set4(value.x, value.y, value.z, value.w);    
+    return pt;
+  }
+
+  /**
+   * Returns the distance between this point and point p1.
+   * 
+   * @param p1
+   *        the other point
+   * @return the distance between these two points
+   */
+  public final float distance4(P4 p1) {
+    double dx = x - p1.x;
+    double dy = y - p1.y;
+    double dz = z - p1.z;
+    double dw = w - p1.w;
+    return (float) Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw);
+  }
+
+}
diff --git a/src2/javajs/util/PT.java b/src2/javajs/util/PT.java
new file mode 100644 (file)
index 0000000..81653cf
--- /dev/null
@@ -0,0 +1,1570 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2007-04-26 16:57:51 -0500 (Thu, 26 Apr 2007) $
+ * $Revision: 7502 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package javajs.util;
+
+import java.lang.reflect.Array;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javajs.api.JSONEncodable;
+
+/**
+ * a combination of Parsing and Text-related utility classes
+ * 
+ * @author hansonr
+ * 
+ */
+
+public class PT {
+
+  public static int parseInt(String str) {
+    return parseIntNext(str, new int[] {0});
+  }
+
+  public static int parseIntNext(String str, int[] next) {
+    int cch = str.length();
+    if (next[0] < 0 || next[0] >= cch)
+      return Integer.MIN_VALUE;
+    return parseIntChecked(str, cch, next);
+  }
+
+  public static int parseIntChecked(String str, int ichMax, int[] next) {
+    boolean digitSeen = false;
+    int value = 0;
+    int ich = next[0];
+    if (ich < 0)
+      return Integer.MIN_VALUE;
+    int ch;
+    while (ich < ichMax && isWhiteSpace(str, ich))
+      ++ich;
+    boolean negative = false;
+    if (ich < ichMax && str.charAt(ich) == 45) { //"-"
+      negative = true;
+      ++ich;
+    }
+    while (ich < ichMax && (ch = str.charAt(ich)) >= 48 && ch <= 57) {
+      value = value * 10 + (ch - 48);
+      digitSeen = true;
+      ++ich;
+    }
+    if (!digitSeen)// || !checkTrailingText(str, ich, ichMax))
+      value = Integer.MIN_VALUE;
+    else if (negative)
+      value = -value;
+    next[0] = ich;
+    return value;
+  }
+
+  public static boolean isWhiteSpace(String str, int ich) {
+    char ch;
+    return (ich >= 0 && ((ch = str.charAt(ich)) == ' ' || ch == '\t' || ch == '\n'));
+  }
+
+  /**
+   * A float parser that is 30% faster than Float.parseFloat(x) and also accepts
+   * x.yD+-n
+   * 
+   * @param str
+   * @param ichMax
+   * @param next
+   *        pointer; incremented
+   * @param isStrict
+   * @return value or Float.NaN
+   */
+  public static float parseFloatChecked(String str, int ichMax, int[] next,
+                                         boolean isStrict) {
+    boolean digitSeen = false;
+    int ich = next[0];
+    if (isStrict && str.indexOf('\n') != str.lastIndexOf('\n'))
+      return Float.NaN;
+    while (ich < ichMax && isWhiteSpace(str, ich))
+      ++ich;
+    boolean negative = false;
+    if (ich < ichMax && str.charAt(ich) == '-') {
+      ++ich;
+      negative = true;
+    }
+    // looks crazy, but if we don't do this, Google Closure Compiler will 
+    // write code that Safari will misinterpret in a VERY nasty way -- 
+    // getting totally confused as to long integers and double values
+    
+    // This is Safari figuring out the values of the numbers on the line (x, y, then z):
+  
+    //  ATOM 1241 CD1 LEU A 64 -2.206 36.532 31.576 1.00 60.60 C
+    //  e=1408749273
+    //  -e =-1408749273
+    //  ATOM 1241 CD1 LEU A 64 -2.206 36.532 31.576 1.00 60.60 C
+    //  e=-1821066134
+    //  e=36.532
+    //  ATOM 1241 CD1 LEU A 64 -2.206 36.532 31.576 1.00 60.60 C
+    //  e=-1133871366
+    //  e=31.576
+    //
+    //  "e" values are just before and after the "value = -value" statement.
+    
+    int ch = 0;
+    float ival = 0f;
+    float ival2 = 0f;
+    while (ich < ichMax && (ch = str.charAt(ich)) >= 48 && ch <= 57) {
+      ival = (ival * 10f) + (ch - 48)*1f;
+      ++ich;
+      digitSeen = true;
+    }
+    boolean isDecimal = false;
+    int iscale = 0;
+    int nzero = (ival == 0 ? -1 : 0);
+    if (ch == '.') {
+      isDecimal = true;
+      while (++ich < ichMax && (ch = str.charAt(ich)) >= 48 && ch <= 57) {
+        digitSeen = true;
+        if (nzero < 0) {
+          if (ch == 48) { 
+            nzero--;
+            continue;
+          }
+          nzero = -nzero;
+        } 
+        if (iscale  < decimalScale.length) {
+          ival2 = (ival2 * 10f) + (ch - 48)*1f;
+          iscale++;
+        }
+      }
+    }
+    float value;
+    
+    // Safari breaks here intermittently converting integers to floats 
+    
+    if (!digitSeen) {
+      value = Float.NaN;
+    } else if (ival2 > 0) {
+      value = ival2 * decimalScale[iscale - 1];
+      if (nzero > 1) {
+        if (nzero - 2 < decimalScale.length) {
+          value *= decimalScale[nzero - 2];
+        } else {
+          value *= Math.pow(10, 1 - nzero);
+        }
+      } else {
+        value += ival;
+      }
+    } else {
+      value = ival;
+    }
+    boolean isExponent = false;
+    if (ich < ichMax && (ch == 69 || ch == 101 || ch == 68)) { // E e D
+      isExponent = true;
+      if (++ich >= ichMax)
+        return Float.NaN;
+      ch = str.charAt(ich);
+      if ((ch == '+') && (++ich >= ichMax))
+        return Float.NaN;
+      next[0] = ich;
+      int exponent = parseIntChecked(str, ichMax, next);
+      if (exponent == Integer.MIN_VALUE)
+        return Float.NaN;
+      if (exponent > 0 && exponent <= tensScale.length)
+        value *= tensScale[exponent - 1];
+      else if (exponent < 0 && -exponent <= decimalScale.length)
+        value *= decimalScale[-exponent - 1];
+      else if (exponent != 0)
+        value *= Math.pow(10, exponent);
+    } else {
+      next[0] = ich; // the exponent code finds its own ichNextParse
+    }
+    // believe it or not, Safari reports the long-equivalent of the 
+    // float value here, then later the float value, after no operation!
+    if (negative)
+      value = -value;
+    if (value == Float.POSITIVE_INFINITY)
+      value = Float.MAX_VALUE;
+    return (!isStrict || (!isExponent || isDecimal)
+        && checkTrailingText(str, next[0], ichMax) ? value : Float.NaN);
+  }
+
+  public final static float[] tensScale = { 10f, 100f, 1000f, 10000f, 100000f, 1000000f };
+  public final static float[] decimalScale = { 
+  0.1f, 
+  0.01f, 
+  0.001f, 
+  0.0001f, 
+  0.00001f,
+  0.000001f, 
+  0.0000001f, 
+  0.00000001f, 
+  0.000000001f
+  };
+  public static boolean checkTrailingText(String str, int ich, int ichMax) {
+    //number must be pure -- no additional characters other than white space or ;
+    char ch;
+    while (ich < ichMax && (isWhitespace(ch = str.charAt(ich)) || ch == ';'))
+      ++ich;
+    return (ich == ichMax);
+  }
+
+  public static float[] parseFloatArray(String str) {
+    return parseFloatArrayNext(str, new int[1], null, null, null);
+  }
+
+  public static int parseFloatArrayInfested(String[] tokens, float[] data) {
+    int len = data.length;
+    int nTokens = tokens.length;
+    int n = 0;
+    int max = 0;
+    for (int i = 0; i >= 0 && i < len && n < nTokens; i++) {
+      float f;
+      while (Float.isNaN(f = parseFloat(tokens[n++])) 
+          && n < nTokens) {
+      }
+      if (!Float.isNaN(f))
+        data[(max = i)] = f;
+      if (n == nTokens)
+        break;
+    }
+    return max + 1;
+  }
+
+  /**
+   * @param str
+   * @param next
+   * @param f
+   * @param strStart or null
+   * @param strEnd   or null
+   * @return array of float values
+   * 
+   */
+  public static float[] parseFloatArrayNext(String str, int[] next, float[] f,
+                                            String strStart, String strEnd) {
+    int n = 0;
+    int pt = next[0];
+    if (pt >= 0) {
+      if (strStart != null) {
+        int p = str.indexOf(strStart, pt);
+        if (p >= 0)
+          next[0] = p + strStart.length();
+      }
+      str = str.substring(next[0]);
+      pt = (strEnd == null ? -1 : str.indexOf(strEnd));
+      if (pt < 0)
+        pt = str.length();
+      else
+        str = str.substring(0, pt);
+      next[0] += pt + 1;
+      String[] tokens = getTokens(str);
+      if (f == null)
+        f = new float[tokens.length];
+      n = parseFloatArrayInfested(tokens, f);
+    }
+    if (f == null)
+      return new float[0];
+    for (int i = n; i < f.length; i++)
+      f[i] = Float.NaN;
+    return f;
+  }
+
+  public static float parseFloatRange(String str, int ichMax, int[] next) {
+    int cch = str.length();
+    if (ichMax > cch)
+      ichMax = cch;
+    if (next[0] < 0 || next[0] >= ichMax)
+      return Float.NaN;
+    return parseFloatChecked(str, ichMax, next, false);
+  }
+
+  public static float parseFloatNext(String str, int[] next) {
+    int cch = (str == null ? -1 : str.length());
+    return (next[0] < 0 || next[0] >= cch ? Float.NaN : parseFloatChecked(str, cch, next, false));
+  }
+
+  public static float parseFloatStrict(String str) {
+    // checks trailing characters and does not allow "1E35" to be float
+    int cch = str.length();
+    if (cch == 0)
+      return Float.NaN;
+    return parseFloatChecked(str, cch, new int[] {0}, true);
+  }
+
+  public static float parseFloat(String str) {
+    return parseFloatNext(str, new int[] {0});
+  }
+
+  public static int parseIntRadix(String s, int i) throws NumberFormatException {
+    /**
+     * 
+     * JavaScript uses parseIntRadix
+     * 
+     * @j2sNative
+     * 
+     *    return Integer.parseIntRadix(s, i);
+     *    
+     */
+    {
+      return Integer.parseInt(s, i);
+    }
+  }
+
+  public static String[] getTokens(String line) {
+    return getTokensAt(line, 0);
+  }
+
+  public static String parseToken(String str) {
+    return parseTokenNext(str, new int[] {0});
+  }
+
+  public static String parseTrimmed(String str) {
+    return parseTrimmedRange(str, 0, str.length());
+  }
+
+  public static String parseTrimmedAt(String str, int ichStart) {
+    return parseTrimmedRange(str, ichStart, str.length());
+  }
+
+  public static String parseTrimmedRange(String str, int ichStart, int ichMax) {
+    int cch = str.length();
+    if (ichMax < cch)
+      cch = ichMax;
+    if (cch < ichStart)
+      return "";
+    return parseTrimmedChecked(str, ichStart, cch);
+  }
+
+  public static String[] getTokensAt(String line, int ich) {
+    if (line == null)
+      return null;
+    int cchLine = line.length();
+    if (ich < 0 || ich > cchLine)
+      return null;
+    int tokenCount = countTokens(line, ich);
+    String[] tokens = new String[tokenCount];
+    int[] next = new int[1];
+    next[0] = ich;
+    for (int i = 0; i < tokenCount; ++i)
+      tokens[i] = parseTokenChecked(line, cchLine, next);
+    return tokens;
+  }
+
+  public static int countChar(String line, char c) {
+    int n = 0;
+    for (int i = line.lastIndexOf(c) + 1; --i >= 0;)
+      if (line.charAt(i) == c)
+        n++;
+    return n;
+  }
+  
+  public static int countTokens(String line, int ich) {
+    int tokenCount = 0;
+    if (line != null) {
+      int ichMax = line.length();
+      while (true) {
+        while (ich < ichMax && isWhiteSpace(line, ich))
+          ++ich;
+        if (ich == ichMax)
+          break;
+        ++tokenCount;
+        do {
+          ++ich;
+        } while (ich < ichMax && !isWhiteSpace(line, ich));
+      }
+    }
+    return tokenCount;
+  }
+
+  public static String parseTokenNext(String str, int[] next) {
+    int cch = str.length();
+    return (next[0] < 0 || next[0] >= cch ? null : parseTokenChecked(str, cch, next));
+  }
+
+  public static String parseTokenRange(String str, int ichMax, int[] next) {
+    int cch = str.length();
+    if (ichMax > cch)
+      ichMax = cch;
+    return (next[0] < 0 || next[0] >= ichMax ? null : parseTokenChecked(str, ichMax, next));
+  }
+
+  public static String parseTokenChecked(String str, int ichMax, int[] next) {
+    int ich = next[0];
+    while (ich < ichMax && isWhiteSpace(str, ich))
+      ++ich;
+    int ichNonWhite = ich;
+    while (ich < ichMax && !isWhiteSpace(str, ich))
+      ++ich;
+    next[0] = ich;
+    return (ichNonWhite == ich ? null : str.substring(ichNonWhite, ich));
+  }
+
+  public static String parseTrimmedChecked(String str, int ich, int ichMax) {
+    while (ich < ichMax && isWhiteSpace(str, ich))
+      ++ich;
+    int ichLast = ichMax - 1;
+    while (ichLast >= ich && isWhiteSpace(str, ichLast))
+      --ichLast;
+    return (ichLast < ich ? "" : str.substring(ich, ichLast + 1));
+  }
+
+//  public static double dVal(String s) throws NumberFormatException {
+//    /**
+//     * @j2sNative
+//     * 
+//     * if(s==null)
+//     *   throw new NumberFormatException("null");
+//     * var d=parseFloat(s);
+//     * if(isNaN(d))
+//     *  throw new NumberFormatException("Not a Number : "+s);
+//     * return d 
+//     * 
+//     */
+//    {
+//      return Double.valueOf(s).doubleValue();
+//    }
+//  }
+//
+//  public static float fVal(String s) throws NumberFormatException {
+//    /**
+//     * @j2sNative
+//     * 
+//     * return this.dVal(s);
+//     */
+//    {
+//      
+//      return Float.parseFloat(s);
+//    }
+//  }
+
+  public static int parseIntRange(String str, int ichMax, int[] next) {
+    int cch = str.length();
+    if (ichMax > cch)
+      ichMax = cch;
+    return (next[0] < 0 || next[0] >= ichMax ? Integer.MIN_VALUE : parseIntChecked(str, ichMax, next));
+  }
+
+  /**
+   * parses a string array for floats. Returns NaN for nonfloats.
+   * 
+   *  @param tokens  the strings to parse
+   *  @param data    the array to fill
+   */
+  public static void parseFloatArrayData(String[] tokens, float[] data) {
+    parseFloatArrayDataN(tokens, data, data.length);
+  }
+
+  /**
+   * parses a string array for floats. Returns NaN for nonfloats or missing data.
+   * 
+   *  @param tokens  the strings to parse
+   *  @param data    the array to fill
+   *  @param nData   the number of elements
+   */
+  public static void parseFloatArrayDataN(String[] tokens, float[] data, int nData) {
+    for (int i = nData; --i >= 0;)
+      data[i] = (i >= tokens.length ? Float.NaN : parseFloat(tokens[i]));
+  }
+
+  /**
+   * 
+   *  proper splitting, even for Java 1.3 -- if the text ends in the run,
+   *  no new line is appended.
+   * 
+   * @param text
+   * @param run
+   * @return  String array
+   */
+  public static String[] split(String text, String run) {
+    if (text.length() == 0)
+      return new String[0];
+    int n = 1;
+    int i = text.indexOf(run);
+    String[] lines;
+    int runLen = run.length();
+    if (i < 0 || runLen == 0) {
+      lines = new String[1];
+      lines[0] = text;
+      return lines;
+    }
+    int len = text.length() - runLen;
+    for (; i >= 0 && i < len; n++)
+      i = text.indexOf(run, i + runLen);
+    lines = new String[n];
+    i = 0;
+    int ipt = 0;
+    int pt = 0;
+    for (; (ipt = text.indexOf(run, i)) >= 0 && pt + 1 < n;) {
+      lines[pt++] = text.substring(i, ipt);
+      i = ipt + runLen;
+    }
+    if (text.indexOf(run, len) != len)
+      len += runLen;
+    lines[pt] = text.substring(i, len);
+    return lines;
+  }
+
+  public final static float FLOAT_MIN_SAFE = 2E-45f; 
+  // Float.MIN_VALUE (1.45E-45) is not reliable with JavaScript because of the float/double difference there
+  
+  /// general static string-parsing class ///
+
+  // next[0] tracks the pointer within the string so these can all be static.
+  // but the methods parseFloat, parseInt, parseToken, parseTrimmed, and getTokens do not require this.
+
+//  public static String concatTokens(String[] tokens, int iFirst, int iEnd) {
+//    String str = "";
+//    String sep = "";
+//    for (int i = iFirst; i < iEnd; i++) {
+//      if (i < tokens.length) {
+//        str += sep + tokens[i];
+//        sep = " ";
+//      }
+//    }
+//    return str;
+//  }
+  
+  public static String getQuotedStringAt(String line, int ipt0) {
+    int[] next = new int[] { ipt0 };
+    return getQuotedStringNext(line, next);
+  }
+  
+  /**
+   * 
+   * @param line
+   * @param next passes [current pointer]
+   * @return quoted string -- does NOT unescape characters
+   */
+  public static String getQuotedStringNext(String line, int[] next) {
+    int i = next[0];
+    if (i < 0 || (i = line.indexOf("\"", i)) < 0)
+      return "";
+    int pt = i + 1;
+    int len = line.length();
+    while (++i < len && line.charAt(i) != '"')
+      if (line.charAt(i) == '\\')
+        i++;
+    next[0] = i + 1;
+    return line.substring(pt, i);
+  }
+  
+  /**
+   * single- or double-quoted string or up to the first space -- like HTML5
+   * not case-sensitive
+   * 
+   * @param line
+   * @param key
+   * @return attribute
+   */
+  public static String getQuotedOrUnquotedAttribute(String line, String key) {
+    if (line == null || key == null)
+      return null;
+    int pt = line.toLowerCase().indexOf(key.toLowerCase() + "=");
+    if (pt < 0 || (pt = pt + key.length() + 1) >= line.length())
+      return "";
+    char c = line.charAt(pt);
+    switch (c) {
+    case '\'':
+    case '"':
+      pt++;
+      break;
+    default:
+      c = ' ';
+      line += " ";
+    }
+    int pt1 = line.indexOf(c, pt);
+    return (pt1 < 0 ? null : line.substring(pt, pt1));
+  }
+  
+  /**
+   * CSV format -- escaped quote is "" WITHIN "..."
+   *
+   * 
+   * @param line
+   * @param next int[2] filled with [ptrQuote1, ptrAfterQuote2]
+   *            next[1] will be -1 if unmatched quotes are found (continuation on next line)
+   * @return unescaped string or null
+   */
+  public static String getCSVString(String line, int[] next) {
+    int i = next[1];
+    if (i < 0 || (i = line.indexOf("\"", i)) < 0)
+      return null;
+    int pt = next[0] = i;
+    int len = line.length();
+    boolean escaped = false;
+    boolean haveEscape = false;
+    while (++i < len 
+        && (line.charAt(i) != '"' || (escaped = (i + 1 < len && line.charAt(i + 1) == '"'))))
+      if (escaped) {
+        escaped = false;
+        haveEscape = true;
+        i++;
+      }
+    if (i >= len) {
+      next[1] = -1;
+      return null; // unmatched
+    }
+    next[1] = i + 1;
+    String s = line.substring(pt + 1, i);
+    return (haveEscape ? rep(rep(s, "\"\"", "\0"), "\0","\"") : s);
+  }
+  
+  public static boolean isOneOf(String key, String semiList) {
+    if (semiList.length() == 0)
+      return false;
+    if (semiList.charAt(0) != ';')
+      semiList = ";" + semiList + ";";
+    return key.indexOf(";") < 0  && semiList.indexOf(';' + key + ';') >= 0;
+  }
+
+  public static String getQuotedAttribute(String info, String name) {
+    int i = info.indexOf(name + "=");
+    return (i < 0 ? null : getQuotedStringAt(info, i));
+  }
+
+  public static float approx(float f, float n) {
+    return Math.round (f * n) / n;
+  }
+
+  /**
+   * Does a clean ITERATIVE replace of strFrom in str with strTo. 
+   * Thus, rep("Testttt", "tt","t") becomes "Test".
+   * 
+   * @param str
+   * @param strFrom
+   * @param strTo
+   * @return replaced string
+   */
+  public static String rep(String str, String strFrom, String strTo) {
+    if (str == null || strFrom.length() == 0 || str.indexOf(strFrom) < 0)
+      return str;
+    boolean isOnce = (strTo.indexOf(strFrom) >= 0);
+    do {
+      str = str.replace(strFrom, strTo);
+    } while (!isOnce && str.indexOf(strFrom) >= 0);
+    return str;
+  }
+
+  public static String formatF(float value, int width, int precision,
+                              boolean alignLeft, boolean zeroPad) {
+    return formatS(DF.formatDecimal(value, precision), width, 0, alignLeft, zeroPad);
+  }
+
+  /**
+   * 
+   * @param value
+   * @param width
+   * @param precision
+   * @param alignLeft
+   * @param zeroPad
+   * @param allowOverflow IGNORED
+   * @return formatted string
+   */
+  public static String formatD(double value, int width, int precision,
+                              boolean alignLeft, boolean zeroPad, boolean allowOverflow) {
+    return formatS(DF.formatDecimal((float)value, -1 - precision), width, 0, alignLeft, zeroPad);
+  }
+
+  /**
+   * 
+   * @param value       
+   * @param width       number of columns
+   * @param precision   precision > 0 ==> precision = number of characters max from left
+   *                    precision < 0 ==> -1 - precision = number of char. max from right
+   * @param alignLeft
+   * @param zeroPad     generally for numbers turned strings
+   * @return            formatted string
+   */
+  public static String formatS(String value, int width, int precision,
+                              boolean alignLeft, boolean zeroPad) {
+    if (value == null)
+      return "";
+    int len = value.length();
+    if (precision != Integer.MAX_VALUE && precision > 0
+        && precision < len)
+      value = value.substring(0, precision);
+    else if (precision < 0 && len + precision >= 0)
+      value = value.substring(len + precision + 1);
+  
+    int padLength = width - value.length();
+    if (padLength <= 0)
+      return value;
+    boolean isNeg = (zeroPad && !alignLeft && value.charAt(0) == '-');
+    char padChar = (zeroPad ? '0' : ' ');
+    char padChar0 = (isNeg ? '-' : padChar);
+  
+    SB sb = new SB();
+    if (alignLeft)
+      sb.append(value);
+    sb.appendC(padChar0);
+    for (int i = padLength; --i > 0;)
+      // this is correct, not >= 0
+      sb.appendC(padChar);
+    if (!alignLeft)
+      sb.append(isNeg ? padChar + value.substring(1) : value);
+    return sb.toString();
+  }
+
+  /**
+   * Does a clean replace of any of the characters in str with chrTo
+   * If strTo contains strFrom, then only a single pass is done.
+   * Otherwise, multiple passes are made until no more replacements can be made.
+   * 
+   * @param str
+   * @param strFrom
+   * @param chTo
+   * @return  replaced string
+   */
+  public static String replaceWithCharacter(String str, String strFrom,
+                                            char chTo) {
+    if (str == null)
+      return null;
+    for (int i = strFrom.length(); --i >= 0;)
+      str = str.replace(strFrom.charAt(i), chTo);
+    return str;
+  }
+
+  /**
+   * Does a clean replace of any of the characters in str with strTo
+   * If strTo contains strFrom, then only a single pass is done.
+   * Otherwise, multiple passes are made until no more replacements can be made.
+   * 
+   * @param str
+   * @param strFrom
+   * @param strTo
+   * @return  replaced string
+   */
+  public static String replaceAllCharacters(String str, String strFrom,
+                                            String strTo) {
+    for (int i = strFrom.length(); --i >= 0;) {
+      String chFrom = strFrom.substring(i, i + 1);
+      str = rep(str, chFrom, strTo);
+    }
+    return str;
+  }
+
+  public static String trim(String str, String chars) {
+    if (str == null || str.length() == 0)
+      return str;
+    if (chars.length() == 0)
+      return str.trim();
+    int len = str.length();
+    int k = 0;
+    while (k < len && chars.indexOf(str.charAt(k)) >= 0)
+      k++;
+    int m = str.length() - 1;
+    while (m > k && chars.indexOf(str.charAt(m)) >= 0)
+      m--;
+    return str.substring(k, m + 1);
+  }
+
+  public static String trimQuotes(String value) {
+    return (value != null && value.length() > 1 && value.startsWith("\"")
+        && value.endsWith("\"") ? value.substring(1, value.length() - 1)
+        : value);
+  }
+
+  public static boolean isNonStringPrimitive(Object info) {
+    // note that we don't use Double, Float, or Integer here
+    // because in JavaScript those would be false for unwrapped primitives
+    // coming from equivalent of Array.get()
+    // Strings will need their own escaped processing
+    
+    return info instanceof Number || info instanceof Boolean;
+  }
+
+//  private static Object arrayGet(Object info, int i) {
+//    /**
+//     * 
+//     * Note that info will be a primitive in JavaScript
+//     * but a wrapped primitive in Java.
+//     * 
+//     * @j2sNative
+//     * 
+//     *            return info[i];
+//     */
+//    {
+//      return Array.get(info, i);
+//    }
+//  }
+//  
+  @SuppressWarnings("unchecked")
+  public static String toJSON(String infoType, Object info) {
+    if (info == null)
+      return packageJSON(infoType, null);
+    if (isNonStringPrimitive(info))
+      return packageJSON(infoType, info.toString());
+    String s = null;
+    SB sb = null;
+    while (true) {
+      if (info instanceof String) {
+        s = (String) info;
+        /**
+         * @j2sNative
+         * 
+         * if (typeof s == "undefined") s = "null"
+         * 
+         */
+        {}
+        
+        if (s.indexOf("{\"") != 0) {
+          //don't doubly fix JSON strings when retrieving status
+          // what about  \1 \2 \3 etc.?
+          s = esc(s);
+        }
+        break;
+      }
+      if (info instanceof JSONEncodable) {
+        // includes javajs.util.BS, org.jmol.script.SV
+        if ((s = ((JSONEncodable) info).toJSON()) == null)
+          s = "null"; // perhaps a list has a null value (group3List, for example)
+        break;
+      }
+      sb = new SB();
+      if (info instanceof Map) {
+        sb.append("{ ");
+        String sep = "";
+        for (String key : ((Map<String, ?>) info).keySet()) {
+          sb.append(sep).append(
+              packageJSON(key, toJSON(null, ((Map<?, ?>) info).get(key))));
+          sep = ",";
+        }
+        sb.append(" }");
+        break;
+      }
+      if (info instanceof Lst) {
+        sb.append("[ ");
+        int n = ((Lst<?>) info).size();
+        for (int i = 0; i < n; i++) {
+          if (i > 0)
+            sb.appendC(',');
+          sb.append(toJSON(null, ((Lst<?>) info).get(i)));
+        }
+        sb.append(" ]");
+        break;
+      }
+      if (info instanceof M34) {
+        // M4 extends M3
+        int len = (info instanceof M4 ? 4 : 3);
+        float[] x = new float[len];
+        M34 m = (M34) info;
+        sb.appendC('[');
+        for (int i = 0; i < len; i++) {
+          if (i > 0)
+            sb.appendC(',');
+          m.getRow(i, x);
+          sb.append(toJSON(null, x));
+        }
+        sb.appendC(']');
+        break;
+      }
+      s = nonArrayString(info);
+      if (s == null) {
+        sb.append("[");
+        int n = AU.getLength(info);
+        for (int i = 0; i < n; i++) {
+          if (i > 0)
+            sb.appendC(',');
+          sb.append(toJSON(null, Array.get(info, i)));
+        }
+        sb.append("]");
+        break;
+      }
+      info = info.toString();
+    }
+    return packageJSON(infoType, (s == null ? sb.toString() : s));
+  }
+
+  /**
+   * Checks to see if an object is an array (including typed arrays), and if it is, returns null;
+   * otherwise it returns the string equivalent of that object.
+   * 
+   * @param x
+   * @return String or null
+   */
+  public static String nonArrayString(Object x) {
+    /**
+     * @j2sNative
+     * 
+     * return (x.constructor == Array || x.BYTES_PER_ELEMENT ? null : x.toString());
+     * 
+     */
+    {
+      try {
+        Array.getLength(x);
+        return null;
+      } catch (Exception e) {
+        return x.toString();
+      }
+    }
+  }
+
+  public static String byteArrayToJSON(byte[] data) {
+    SB sb = new SB();
+    sb.append("[");
+    int n = data.length;
+    for (int i = 0; i < n; i++) {
+      if (i > 0)
+        sb.appendC(',');
+      sb.appendI(data[i] & 0xFF);
+    }
+    sb.append("]");
+    return sb.toString();
+  }
+  
+  public static String packageJSON(String infoType, String info) {
+    return (infoType == null ? info : "\"" + infoType + "\": " + info);
+  }
+
+  public static String escapeUrl(String url) {
+    url = rep(url, "\n", "");
+    url = rep(url, "%", "%25");
+    url = rep(url, "#", "%23");
+    url = rep(url, "[", "%5B");
+    url = rep(url, "\\", "%5C");
+    url = rep(url, "]", "%5D");
+    url = rep(url, " ", "%20");
+    return url;
+  }
+
+  private final static String escapable = "\\\\\tt\rr\nn\"\""; 
+
+  public static String esc(String str) {
+    if (str == null || str.length() == 0)
+      return "\"\"";
+    boolean haveEscape = false;
+    int i = 0;
+    for (; i < escapable.length(); i += 2)
+      if (str.indexOf(escapable.charAt(i)) >= 0) {
+        haveEscape = true;
+        break;
+      }
+    if (haveEscape)
+      while (i < escapable.length()) {
+        int pt = -1;
+        char ch = escapable.charAt(i++);
+        char ch2 = escapable.charAt(i++);
+        SB sb = new SB();
+        int pt0 = 0;
+        while ((pt = str.indexOf(ch, pt + 1)) >= 0) {
+          sb.append(str.substring(pt0, pt)).appendC('\\').appendC(ch2);
+          pt0 = pt + 1;
+        }
+        sb.append(str.substring(pt0, str.length()));
+        str = sb.toString();
+      }    
+    return "\"" + escUnicode(str) + "\"";
+  }
+
+  public static String escUnicode(String str) {
+    for (int i = str.length(); --i >= 0;)
+      if (str.charAt(i) > 0x7F) {
+        String s = "0000" + Integer.toHexString(str.charAt(i));
+        str = str.substring(0, i) + "\\u" + s.substring(s.length() - 4)
+            + str.substring(i + 1);
+      }
+    return str;
+  }
+
+  /**
+   * ensures that a float turned to string has a decimal point
+   * 
+   * @param f
+   * @return string version of float
+   */
+  public static String escF(float f) {
+    String sf = "" + f;
+    /**
+     * @j2sNative
+     * 
+     * if (sf.indexOf(".") < 0 && sf.indexOf("e") < 0)
+     *   sf += ".0";
+     */
+    {
+    }
+    return sf;
+  }
+  public static String join(String[] s, char c, int i0) {
+    if (s.length < i0)
+      return null;
+    SB sb = new SB();
+    sb.append(s[i0++]);
+    for (int i = i0; i < s.length; i++)
+      sb.appendC(c).append(s[i]);
+    return sb.toString();
+  }
+
+  /**
+   * a LIKE "x"    a is a string and equals x
+   * 
+   * a LIKE "*x"   a is a string and ends with x
+   * 
+   * a LIKE "x*"   a is a string and starts with x
+   * 
+   * a LIKE "*x*"  a is a string and contains x
+   *  
+   * @param a
+   * @param b
+   * @return  a LIKE b
+   */
+  public static boolean isLike(String a, String b) {
+    boolean areEqual = a.equals(b);
+    if (areEqual)
+      return true;
+    boolean isStart = b.startsWith("*");
+    boolean isEnd = b.endsWith("*");
+    return (!isStart && !isEnd) ? areEqual
+        : isStart && isEnd ? b.length() == 1 || a.contains(b.substring(1, b.length() - 1))
+        : isStart ? a.endsWith(b.substring(1))
+        : a.startsWith(b.substring(0, b.length() - 1));
+  }
+
+  public static Object getMapValueNoCase(Map<String, ?> h, String key) {
+    if ("this".equals(key))
+      return h;
+    Object val = h.get(key);
+    if (val == null)
+      for (Entry<String, ?> e : h.entrySet())
+        if (e.getKey().equalsIgnoreCase(key))
+          return e.getValue();
+    return val;
+  }
+
+  public static String clean(String s) {
+    return rep(replaceAllCharacters(s, " \t\n\r", " "), "  ", " ").trim();
+  }
+
+  /**
+   * 
+   * fdup      duplicates p or q formats for formatCheck
+   *           and the format() function.
+   * 
+   * @param f
+   * @param pt
+   * @param n
+   * @return     %3.5q%3.5q%3.5q%3.5q or %3.5p%3.5p%3.5p
+   */
+  public static String fdup(String f, int pt, int n) {
+    char ch;
+    int count = 0;
+    for (int i = pt; --i >= 1; ) {
+      if (isDigit(ch = f.charAt(i)))
+        continue;
+      switch (ch) {
+      case '.':
+        if (count++ != 0)
+          return f;
+        continue;
+      case '-':
+        if (i != 1 && f.charAt(i - 1) != '.')
+          return f;
+        continue;
+      default:
+        return f;
+      }
+    }
+    String s = f.substring(0, pt + 1);
+    SB sb = new SB();
+    for (int i = 0; i < n; i++)
+      sb.append(s);
+    sb.append(f.substring(pt + 1));
+    return sb.toString();
+  }
+
+  /**
+   * generic string formatter  based on formatLabel in Atom
+   * 
+   * 
+   * @param strFormat   .... %width.precisionKEY....
+   * @param key      any string to match
+   * @param strT     replacement string or null
+   * @param floatT   replacement float or Float.NaN
+   * @param doubleT  replacement double or Double.NaN -- for exponential
+   * @param doOne    mimic sprintf    
+   * @return         formatted string
+   */
+  
+  private static String formatString(String strFormat, String key, String strT,
+                                    float floatT, double doubleT, boolean doOne) {
+    if (strFormat == null)
+      return null;
+    if ("".equals(strFormat))
+      return "";
+    int len = key.length();
+    if (strFormat.indexOf("%") < 0 || len == 0 || strFormat.indexOf(key) < 0)
+      return strFormat;
+  
+    String strLabel = "";
+    int ich, ichPercent, ichKey;
+    for (ich = 0; (ichPercent = strFormat.indexOf('%', ich)) >= 0
+        && (ichKey = strFormat.indexOf(key, ichPercent + 1)) >= 0;) {
+      if (ich != ichPercent)
+        strLabel += strFormat.substring(ich, ichPercent);
+      ich = ichPercent + 1;
+      if (ichKey > ichPercent + 6) {
+        strLabel += '%';
+        continue;//%12.10x
+      }
+      try {
+        boolean alignLeft = false;
+        if (strFormat.charAt(ich) == '-') {
+          alignLeft = true;
+          ++ich;
+        }
+        boolean zeroPad = false;
+        if (strFormat.charAt(ich) == '0') {
+          zeroPad = true;
+          ++ich;
+        }
+        char ch;
+        int width = 0;
+        while ((ch = strFormat.charAt(ich)) >= '0' && (ch <= '9')) {
+          width = (10 * width) + (ch - '0');
+          ++ich;
+        }
+        int precision = Integer.MAX_VALUE;
+        boolean isExponential = false;
+        if (strFormat.charAt(ich) == '.') {
+          ++ich;
+          if ((ch = strFormat.charAt(ich)) == '-') {
+            isExponential = (strT == null);
+            ++ich;
+          } 
+          if ((ch = strFormat.charAt(ich)) >= '0' && ch <= '9') {
+            precision = ch - '0';
+            ++ich;
+          }
+          if (isExponential)
+            precision = -precision;
+        }
+        String st = strFormat.substring(ich, ich + len);
+        if (!st.equals(key)) {
+          ich = ichPercent + 1;
+          strLabel += '%';
+          continue;
+        }
+        ich += len;
+        if (!Float.isNaN(floatT)) // 'f'
+          strLabel += formatF(floatT, width, precision, alignLeft,
+              zeroPad);
+        else if (strT != null)  // 'd' 'i' or 's'
+          strLabel += formatS(strT, width, precision, alignLeft,
+              zeroPad);
+        else if (!Double.isNaN(doubleT)) // 'e'
+          strLabel += formatD(doubleT, width, precision - 1, alignLeft,
+              zeroPad, true);
+        if (doOne)
+          break;
+      } catch (IndexOutOfBoundsException ioobe) {
+        ich = ichPercent;
+        break;
+      }
+    }
+    strLabel += strFormat.substring(ich);
+    //if (strLabel.length() == 0)
+      //return null;
+    return strLabel;
+  }
+
+  public static String formatStringS(String strFormat, String key, String strT) {
+    return formatString(strFormat, key, strT, Float.NaN, Double.NaN, false);
+  }
+
+  public static String formatStringF(String strFormat, String key, float floatT) {
+    return formatString(strFormat, key, null, floatT, Double.NaN, false);
+  }
+
+  public static String formatStringI(String strFormat, String key, int intT) {
+    return formatString(strFormat, key, "" + intT, Float.NaN, Double.NaN, false);
+  }
+
+  /**
+   * sprintf emulation uses (almost) c++ standard string formats
+   * 
+   * 's' string 'i' or 'd' integer, 'e' double, 'f' float, 'p' point3f 'q'
+   * quaternion/plane/axisangle with added "i" (equal to the insipid "d" --
+   * digits?)
+   * 
+   * @param strFormat
+   * @param list
+   *        a listing of what sort of data will be found in Object[] values, in
+   *        order: s string, f float, i integer, d double, p point3f, q
+   *        quaternion/point4f, S String[], F float[], I int[], and D double[]
+   * @param values
+   *        Object[] containing above types
+   * @return formatted string
+   */
+  public static String sprintf(String strFormat, String list, Object[] values) {
+    if (values == null)
+      return strFormat;
+    int n = list.length();
+    if (n == values.length)
+      try {
+        for (int o = 0; o < n; o++) {
+          if (values[o] == null)
+            continue;
+          switch (list.charAt(o)) {
+          case 's':
+            strFormat = formatString(strFormat, "s", (String) values[o],
+                Float.NaN, Double.NaN, true);
+            break;
+          case 'f':
+            strFormat = formatString(strFormat, "f", null, ((Float) values[o])
+                .floatValue(), Double.NaN, true);
+            break;
+          case 'i':
+            strFormat = formatString(strFormat, "d", "" + values[o], Float.NaN,
+                Double.NaN, true);
+            strFormat = formatString(strFormat, "i", "" + values[o], Float.NaN,
+                Double.NaN, true);
+            break;
+          case 'd':
+            strFormat = formatString(strFormat, "e", null, Float.NaN,
+                ((Double) values[o]).doubleValue(), true);
+            break;
+          case 'p':
+            T3 pVal = (T3) values[o];
+            strFormat = formatString(strFormat, "p", null, pVal.x, Double.NaN,
+                true);
+            strFormat = formatString(strFormat, "p", null, pVal.y, Double.NaN,
+                true);
+            strFormat = formatString(strFormat, "p", null, pVal.z, Double.NaN,
+                true);
+            break;
+          case 'q':
+            T4 qVal = (T4) values[o];
+            strFormat = formatString(strFormat, "q", null, qVal.x, Double.NaN,
+                true);
+            strFormat = formatString(strFormat, "q", null, qVal.y, Double.NaN,
+                true);
+            strFormat = formatString(strFormat, "q", null, qVal.z, Double.NaN,
+                true);
+            strFormat = formatString(strFormat, "q", null, qVal.w, Double.NaN,
+                true);
+            break;
+          case 'S':
+            String[] sVal = (String[]) values[o];
+            for (int i = 0; i < sVal.length; i++)
+              strFormat = formatString(strFormat, "s", sVal[i], Float.NaN,
+                  Double.NaN, true);
+            break;
+          case 'F':
+            float[] fVal = (float[]) values[o];
+            for (int i = 0; i < fVal.length; i++)
+              strFormat = formatString(strFormat, "f", null, fVal[i],
+                  Double.NaN, true);
+            break;
+          case 'I':
+            int[] iVal = (int[]) values[o];
+            for (int i = 0; i < iVal.length; i++)
+              strFormat = formatString(strFormat, "d", "" + iVal[i], Float.NaN,
+                  Double.NaN, true);
+            for (int i = 0; i < iVal.length; i++)
+              strFormat = formatString(strFormat, "i", "" + iVal[i], Float.NaN,
+                  Double.NaN, true);
+            break;
+          case 'D':
+            double[] dVal = (double[]) values[o];
+            for (int i = 0; i < dVal.length; i++)
+              strFormat = formatString(strFormat, "e", null, Float.NaN,
+                  dVal[i], true);
+          }
+  
+        }
+        return rep(strFormat, "%%", "%");
+      } catch (Exception e) {
+        //
+      }
+    System.out.println("TextFormat.sprintf error " + list + " " + strFormat);
+    return rep(strFormat, "%", "?");
+  }
+
+  /**
+   * 
+   * formatCheck   checks p and q formats and duplicates if necessary
+   *               "%10.5p xxxx" ==> "%10.5p%10.5p%10.5p xxxx" 
+   * 
+   * @param strFormat
+   * @return    f or dupicated format
+   */
+  public static String formatCheck(String strFormat) {
+    if (strFormat == null || strFormat.indexOf('p') < 0 && strFormat.indexOf('q') < 0)
+      return strFormat;
+    strFormat = rep(strFormat, "%%", "\1");
+    strFormat = rep(strFormat, "%p", "%6.2p");
+    strFormat = rep(strFormat, "%q", "%6.2q");
+    String[] format = split(strFormat, "%");
+    SB sb = new SB();
+    sb.append(format[0]);
+    for (int i = 1; i < format.length; i++) {
+      String f = "%" + format[i];
+      int pt;
+      if (f.length() >= 3) {
+        if ((pt = f.indexOf('p')) >= 0)
+          f = fdup(f, pt, 3);
+        if ((pt = f.indexOf('q')) >= 0)
+          f = fdup(f, pt, 4);
+      }
+      sb.append(f);
+    }
+    return sb.toString().replace('\1', '%');
+  }
+
+  public static void leftJustify(SB s, String s1, String s2) {
+    s.append(s2);
+    int n = s1.length() - s2.length();
+    if (n > 0)
+      s.append(s1.substring(0, n));
+  }
+
+  public static void rightJustify(SB s, String s1, String s2) {
+    int n = s1.length() - s2.length();
+    if (n > 0)
+      s.append(s1.substring(0, n));
+    s.append(s2);
+  }
+
+  public static String safeTruncate(float f, int n) {
+    if (f > -0.001 && f < 0.001)
+      f = 0;
+    return (f + "         ").substring(0,n);
+  }
+
+  public static boolean isWild(String s) {
+    return s != null && (s.indexOf("*") >= 0 || s.indexOf("?") >= 0);
+  }
+
+  /**
+   * A general non-regex (for performance) text matcher that utilizes ? and *.
+   * 
+   * ??? means "at most three" characters if at beginning or end; 
+   *   "exactly three" otherwise
+   * \1 in search is a stand-in for actual ?
+   * 
+   * @param search
+   *        the string to search
+   * @param match
+   *        the match string
+   * @param checkStar
+   * @param allowInitialStar
+   * @return true if found
+   */
+  public static boolean isMatch(String search, String match, boolean checkStar,
+                                boolean allowInitialStar) {
+    // search == match --> true
+    if (search.equals(match))
+      return true;
+    int mLen = match.length();
+    // match == ""  --> false
+    if (mLen == 0)
+      return false;
+    boolean isStar0 = (checkStar && allowInitialStar ? match.charAt(0) == '*'
+        : false);
+    // match == "*" --> true
+    if (mLen == 1 && isStar0)
+      return true;
+    boolean isStar1 = (checkStar && match.endsWith("*"));
+    boolean haveQ = (match.indexOf('?') >= 0);
+    // match == "**" --> true
+    // match == "*xxx*" --> search contains "xxx"
+    // match == "*xxx" --> search ends with "xxx"
+    // match == "xxx*" --> search starts with "xxx"
+    if (!haveQ) {
+      if (isStar0)
+        return (isStar1 ? (mLen < 3 || search.indexOf(match.substring(1,
+            mLen - 1)) >= 0) : search.endsWith(match.substring(1)));
+      else if (isStar1)
+        return search.startsWith(match.substring(0, mLen - 1));
+    }
+    int sLen = search.length();
+    // pad match with "?" -- same as *
+    String qqqq = "????";
+    int nq = 4;
+    while (nq < sLen) {
+      qqqq += qqqq;
+      nq += 4;
+    }
+    if (checkStar) {
+      if (isStar0) {
+        match = qqqq + match.substring(1);
+        mLen += nq - 1;
+      }
+      if (isStar1) {
+        match = match.substring(0, mLen - 1) + qqqq;
+        mLen += nq - 1;
+      }
+    }
+    // length of match < length of search --> false 
+    if (mLen < sLen)
+      return false;
+  
+    // -- each ? matches ONE character if not at end
+    // -- extra ? at end ignored
+  
+    // (allowInitialStar == true)
+    // -- extra ? at beginning reduced to match length
+  
+    int ich = 0;
+    while (mLen > sLen) {
+      if (allowInitialStar && match.charAt(ich) == '?') {
+        ++ich;
+      } else if (match.charAt(ich + mLen - 1) != '?') {
+        return false;
+      }
+      --mLen;
+    }
+  
+    // both are effectively same length now.
+    // \1 is stand-in for "?"
+  
+    for (int i = sLen; --i >= 0;) {
+      char chm = match.charAt(ich + i);
+      if (chm == '?')
+        continue;
+      char chs = search.charAt(i);
+      if (chm != chs && (chm != '\1' || chs != '?'))
+        return false;
+    }
+    return true;
+  }
+
+  public static String replaceQuotedStrings(String s, Lst<String> list,
+                                            Lst<String> newList) {
+    int n = list.size();
+    for (int i = 0; i < n; i++) {
+      String name = list.get(i);
+      String newName = newList.get(i);
+      if (!newName.equals(name))
+        s = rep(s, "\"" + name + "\"", "\"" + newName
+            + "\"");
+    }
+    return s;
+  }
+
+  public static String replaceStrings(String s, Lst<String> list,
+                                      Lst<String> newList) {
+    int n = list.size();
+    for (int i = 0; i < n; i++) {
+      String name = list.get(i);
+      String newName = newList.get(i);
+      if (!newName.equals(name))
+        s = rep(s, name, newName);
+    }
+    return s;
+  }
+
+  public static boolean isDigit(char ch) {
+    // just way simpler code than  Character.isDigit(ch);
+    int c = ch;
+    return (48 <= c && c <= 57);
+  }
+
+  public static boolean isUpperCase(char ch) {
+    int c = ch;
+    return (65 <= c && c <= 90);
+  }
+
+  public static boolean isLowerCase(char ch) {
+    int c = ch;
+    return (97 <= c && c <= 122);
+  }
+
+  public static boolean isLetter(char ch) {
+    // just way simpler code than     Character.isLetter(ch);
+    int c = ch;
+    return (65 <= c && c <= 90 || 97 <= c && c <= 122);
+  }
+
+  public static boolean isLetterOrDigit(char ch) {
+    // just way simpler code than     Character.isLetterOrDigit(ch);
+    int c = ch;
+    return (65 <= c && c <= 90 || 97 <= c && c <= 122 || 48 <= c && c <= 57);
+  }
+
+  public static boolean isWhitespace(char ch) {
+    int c = ch;
+    return (c >= 0x1c && c <= 0x20 || c >= 0x9 && c <= 0xd);
+  }
+
+  public static final float FRACTIONAL_PRECISION = 100000f;
+  public static final float CARTESIAN_PRECISION =  10000f;
+
+  public static void fixPtFloats(T3 pt, float f) {
+    //this will equate float and double as long as -256 <= x <= 256
+    pt.x = Math.round(pt.x * f) / f;
+    pt.y = Math.round(pt.y * f) / f;
+    pt.z = Math.round(pt.z * f) / f;
+  }
+  
+  public static double fixDouble(double d, double f) {
+    return Math.round(d * f) / f;
+  }
+
+  /**
+   * parse a float or "float/float"
+   * @param s
+   * @return a/b
+   */
+  public static float parseFloatFraction(String s) {
+      int pt = s.indexOf("/");
+      return (pt < 0 ? parseFloat(s) : parseFloat(s.substring(0, pt))
+          / parseFloat(s.substring(pt + 1)));
+  }
+
+//static {
+//    
+//  double d = 790.8999998888;
+//  float x  = 790.8999998888f;
+//  for (int i = 0; i < 50; i++) {
+//  System.out.println(x + " " + d);
+//  System.out.println(Math.round(x * 100000) / 100000f);
+//  System.out.println(Math.round(d * 100000) / 100000.);
+//  System.out.println(Math.round(x * 10000) / 10000f);
+//  System.out.println(Math.round(d * 10000) / 10000.);
+//  x+=1; 
+//  d+=1;
+//  }
+//  System.out.println(100.123456789f);
+//}
+
+//  static {
+//    long t;
+//    char c = '0';
+//    t = System.currentTimeMillis();
+//    for (int i = 0; i < 10000000; i++) {
+//      boolean b = PT.isUpperCase(c);
+//    }
+//    System.out.println(System.currentTimeMillis() - t);
+//
+//    t = System.currentTimeMillis();
+//    for (int i = 0; i < 10000000; i++) {
+//      boolean b = Character.isUpperCase(c);
+//    }
+//    System.out.println(System.currentTimeMillis() - t);
+//    
+//    t = System.currentTimeMillis();
+//    for (int i = 0; i < 10000000; i++) {
+//      boolean b = PT.isUpperCase(c);
+//    }
+//    System.out.println(System.currentTimeMillis() - t);
+//
+//    System.out.println("PT test");
+//  }
+}
diff --git a/src2/javajs/util/Quat.java b/src2/javajs/util/Quat.java
new file mode 100644 (file)
index 0000000..d4a7bf9
--- /dev/null
@@ -0,0 +1,818 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2007-04-05 09:07:28 -0500 (Thu, 05 Apr 2007) $
+ * $Revision: 7326 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2003-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.util;
+
+/*
+ * Standard UNIT quaternion math -- for rotation.
+ * 
+ * All rotations can be represented as two identical quaternions. 
+ * This is because any rotation can be considered from either end of the
+ * rotational axis -- either as a + rotation or a - rotation. This code
+ * is designed to always maintain the quaternion with a rotation in the
+ * [0, PI) range. 
+ * 
+ * This ensures that the reported theta is always positive, and the normal
+ * reported is always associated with a positive theta.  
+ * 
+ * @author Bob Hanson, hansonr@stolaf.edu 6/2008
+ * 
+ */
+
+public class Quat {
+  public float q0, q1, q2, q3;
+  private M3 mat;
+
+  private final static P4 qZero = new P4();
+  private static final double RAD_PER_DEG = Math.PI / 180;
+  
+  public Quat() {
+    q0 = 1;
+  }
+
+  public static Quat newQ(Quat q) {
+    Quat q1 = new Quat();
+    q1.set(q);
+    return q1;
+  }
+
+  public static Quat newVA(T3 v, float theta) {
+    Quat q = new Quat();
+    q.setTA(v, theta);
+    return q;
+  }
+
+  public static Quat newM(M3 mat) {
+    Quat q = new Quat();
+    q.setM(M3.newM3(mat));
+    return q;
+  }
+
+  public static Quat newAA(A4 a) {
+    Quat q = new Quat();
+    q.setAA(a);
+    return q;
+  }
+
+  public static Quat newP4(P4 pt) {
+    Quat q = new Quat();
+    q.setP4(pt);
+    return q;
+  }
+
+  /**
+   * Note that q0 is the last parameter here
+   * 
+   * @param q1
+   * @param q2
+   * @param q3
+   * @param q0
+   * @return {q1 q2 q3 q0}
+   */
+  public static Quat new4(float q1, float q2, float q3, float q0) {
+    Quat q = new Quat();
+    if (q0 < -1) {
+      q.q0 = -1;
+      return q;
+    }
+    if (q0 > 1) {
+      q.q0 = 1;
+      return q;
+    }
+    q.q0 = q0;
+    q.q1 = q1;
+    q.q2 = q2;
+    q.q3 = q3;
+    return q;
+  }
+
+  public void set(Quat q) {
+    q0 = q.q0;
+    q1 = q.q1;
+    q2 = q.q2;
+    q3 = q.q3;
+  }
+
+  /**
+   * {x y z w} --> {q1 q2 q3 q0} and factored
+   * 
+   * @param pt
+   */
+  private void setP4(P4 pt) {
+    float factor = (pt == null ? 0 : pt.distance4(qZero));
+    if (factor == 0) {
+      q0 = 1;
+      return;
+    }
+    q0 = pt.w / factor;
+    q1 = pt.x / factor;
+    q2 = pt.y / factor;
+    q3 = pt.z / factor;
+  }
+
+  /**
+   * q = (cos(theta/2), sin(theta/2) * n)
+   * 
+   * @param pt
+   * @param theta
+   */
+  public void setTA(T3 pt, float theta) {
+    if (pt.x == 0 && pt.y == 0 && pt.z == 0) {
+      q0 = 1;
+      return;
+    }
+    double fact = (Math.sin(theta / 2 * RAD_PER_DEG) / Math.sqrt(pt.x
+        * pt.x + pt.y * pt.y + pt.z * pt.z));
+    q0 = (float) (Math.cos(theta / 2 * RAD_PER_DEG));
+    q1 = (float) (pt.x * fact);
+    q2 = (float) (pt.y * fact);
+    q3 = (float) (pt.z * fact);
+  }
+
+  public void setAA(A4 a) {
+    A4 aa = A4.newAA(a);
+    if (aa.angle == 0)
+      aa.y = 1;
+    setM(new M3().setAA(aa));
+  }
+
+  private void setM(M3 mat) {
+
+    /*
+     * Changed 7/16/2008 to double precision for 11.5.48.
+     * 
+     * <quote>
+     *  
+     * RayTrace Software Package, release 3.0.  May 3, 2006.
+     *
+     * Mathematics Subpackage (VrMath)
+     *
+     * Author: Samuel R. Buss
+     *
+     * Software is "as-is" and carries no warranty.  It may be used without
+     *   restriction, but if you modify it, please change the filenames to
+     *   prevent confusion between different versions.  Please acknowledge
+     *   all use of the software in any publications or products based on it.
+     *
+     * Bug reports: Sam Buss, sbuss@ucsd.edu.
+     * Web page: http://math.ucsd.edu/~sbuss/MathCG
+     
+     // Use Shepperd's algorithm, which is stable, does not lose
+     //    significant precision and uses only one sqrt.
+     //   J. Guidance and Control, 1 (1978) 223-224.
+
+     * </quote>
+     * 
+     * Except, that code has errors.
+     * 
+     * CORRECTIONS (as noted below) of Quaternion.cpp. I have reported the bug.
+     *  
+     * -- Bob Hanson
+     * 
+     *  theory:    
+     *         cos(theta/2)^2 = (cos(theta) + 1)/2
+     *  and      
+     *         trace = (1-x^2)ct + (1-y^2)ct + (1-z^2)ct + 1 = 2cos(theta) + 1
+     *  or
+     *         cos(theta) = (trace - 1)/2 
+     *         
+     *  so in general,       
+     *       
+     *       w = cos(theta/2) 
+     *         = sqrt((cos(theta)+1)/2) 
+     *         = sqrt((trace-1)/4+1/2)
+     *         = sqrt((trace+1)/4)
+     *         = sqrt(trace+1)/2
+     *     
+     *  but there are precision issues, so we allow for other situations.
+     *  note -- trace >= 0.5 when cos(theta) >= -0.25 (-104.48 <= theta <= 104.48).
+     *  this code cleverly matches the precision in all four options.
+     *
+     */
+
+    this.mat = mat;
+    
+    double trace = mat.m00 + mat.m11 + mat.m22;
+    double temp;
+    double w, x, y, z;
+    if (trace >= 0.5) {
+      w = Math.sqrt(1.0 + trace);
+      x = (mat.m21 - mat.m12) / w;
+      y = (mat.m02 - mat.m20) / w;
+      z = (mat.m10 - mat.m01) / w;
+    } else if ((temp = mat.m00 + mat.m00 - trace) >= 0.5) {
+      x = Math.sqrt(1.0 + temp);
+      w = (mat.m21 - mat.m12) / x;
+      y = (mat.m10 + mat.m01) / x;
+      z = (mat.m20 + mat.m02) / x;
+    } else if ((temp = mat.m11 + mat.m11 - trace) >= 0.5 
+        || mat.m11 > mat.m22) {
+      y = Math.sqrt(1.0 + temp);
+      w = (mat.m02 - mat.m20) / y;
+      x = (mat.m10 + mat.m01) / y;
+      z = (mat.m21 + mat.m12) / y;
+    } else {
+      z = Math.sqrt(1.0 + mat.m22 + mat.m22 - trace);
+      w = (mat.m10 - mat.m01) / z;
+      x = (mat.m20 + mat.m02) / z; // was -
+      y = (mat.m21 + mat.m12) / z; // was -
+    }
+
+    q0 = (float) (w * 0.5);
+    q1 = (float) (x * 0.5);
+    q2 = (float) (y * 0.5);
+    q3 = (float) (z * 0.5);
+
+    /*
+     *  Originally from http://www.gamedev.net/community/forums/topic.asp?topic_id=448380
+     *  later algorithm was adapted from Visualizing Quaternions, by Andrew J. Hanson
+     *   (Morgan Kaufmann, 2006), page 446
+     *  
+     *  HOWEVER, checking with AxisAngle4f and Quat4f equivalents, it was found that
+     *  BOTH of these sources produce inverted quaternions. So here we do an inversion.
+     *  
+     *  This correction was made in 11.5.42  6/19/2008  -- Bob Hanson
+     *
+     *  former algorithm used:     
+     * /
+     
+     double tr = mat.m00 + mat.m11 + mat.m22; //Matrix trace 
+     double s;
+     double[] q = new double[4];
+     if (tr > 0) {
+     s = Math.sqrt(tr + 1);
+     q0 = (float) (0.5 * s);
+     s = 0.5 / s; // = 1/q0
+     q1 = (float) ((mat.m21 - mat.m12) * s);
+     q2 = (float) ((mat.m02 - mat.m20) * s);
+     q3 = (float) ((mat.m10 - mat.m01) * s);
+     } else {
+     float[][] m = new float[][] { new float[3], new float[3], new float[3] };
+     mat.getRow(0, m[0]);
+     mat.getRow(1, m[1]);
+     mat.getRow(2, m[2]);
+
+     //Find out the biggest element along the diagonal 
+     float max = Math.max(mat.m11, mat.m00);
+     int i = (mat.m22 > max ? 2 : max == mat.m11 ? 1 : 0);
+     int j = (i + 1) % 3;
+     int k = (j + 1) % 3;
+     s = -Math.sqrt(1 + m[i][i] - m[j][j] - m[k][k]);
+     // 0 = 1 + (1-x^2)ct + x^2 -(1-y^2)ct - y^2 - (1-z^2)ct - z^2
+     // 0 = 1 - ct + (x^2 - y^2 - z^2) - (x^2 - y^2 - z^2)ct
+     // 0 = 1 - ct + 2x^2 - 1 - (2x^2)ct + ct
+     // 0 = 2x^2(1 - ct)
+     // theta = 0 (but then trace = 1 + 1 + 1 = 3)
+     // or x = 0. 
+     q[i] = s * 0.5;
+     if (s != 0)
+     s = 0.5 / s; // = 1/q[i]
+     q[j] = (m[i][j] + m[j][i]) * s;
+     q[k] = (m[i][k] + m[k][i]) * s;
+     q0 = (float) ((m[k][j] - m[j][k]) * s);
+     q1 = (float) q[0]; // x
+     q2 = (float) q[1]; // y
+     q3 = (float) q[2]; // z 
+     }
+
+     */
+  }
+
+  /*
+   * if qref is null, "fix" this quaternion
+   * otherwise, return a quaternion that is CLOSEST to the given quaternion
+   * that is, one that gives a positive dot product
+   * 
+   */
+  public void setRef(Quat qref) {
+    if (qref == null) {
+      mul(getFixFactor());
+      return;
+    }
+    if (dot(qref) >= 0)
+      return;
+    q0 *= -1;
+    q1 *= -1;
+    q2 *= -1;
+    q3 *= -1;
+  }
+
+  /**
+   * returns a quaternion frame based on three points (center, x, and any point in xy plane)
+   * or two vectors (vA, vB).
+   * 
+   * @param center  (null for vA/vB option)
+   * @param x
+   * @param xy
+   * @return quaternion for frame
+   */
+  public static final Quat getQuaternionFrame(P3 center, T3 x,
+                                                    T3 xy) {
+    V3 vA = V3.newV(x);
+    V3 vB = V3.newV(xy);
+    if (center != null) {
+      vA.sub(center);
+      vB.sub(center);
+    }
+    return getQuaternionFrameV(vA, vB, null, false);
+  }
+
+  /**
+   * Create a quaternion based on a frame
+   * @param vA
+   * @param vB
+   * @param vC
+   * @param yBased
+   * @return quaternion
+   */
+  public static final Quat getQuaternionFrameV(V3 vA, V3 vB,
+                                                    V3 vC, boolean yBased) {
+    if (vC == null) {
+      vC = new V3();
+      vC.cross(vA, vB);
+      if (yBased)
+        vA.cross(vB, vC);
+    }
+    V3 vBprime = new V3();
+    vBprime.cross(vC, vA);
+    vA.normalize();
+    vBprime.normalize();
+    vC.normalize();
+    M3 mat = new M3();
+    mat.setColumnV(0, vA);
+    mat.setColumnV(1, vBprime);
+    mat.setColumnV(2, vC);
+
+    /*
+     * 
+     * Verification tests using Quat4f and AngleAxis4f:
+     * 
+     System.out.println("quaternion frame matrix: " + mat);
+     
+     Point3f pt2 = new Point3f();
+     mat.transform(Point3f.new3(1, 0, 0), pt2);
+     System.out.println("vA=" + vA + " M(100)=" + pt2);
+     mat.transform(Point3f.new3(0, 1, 0), pt2);
+     System.out.println("vB'=" + vBprime + " M(010)=" + pt2);
+     mat.transform(Point3f.new3(0, 0, 1), pt2);
+     System.out.println("vC=" + vC + " M(001)=" + pt2);
+     Quat4f q4 = new Quat4f();
+     q4.set(mat);
+     System.out.println("----");
+     System.out.println("Quat4f: {" + q4.w + " " + q4.x + " " + q4.y + " " + q4.z + "}");
+     System.out.println("Quat4f: 2xy + 2wz = m10: " + (2 * q4.x * q4.y + 2 * q4.w * q4.z) + " = " + mat.m10);   
+     
+     */
+
+    Quat q = newM(mat);
+
+     /*
+     System.out.println("Quaternion mat from q \n" + q.getMatrix());
+     System.out.println("Quaternion: " + q.getNormal() + " " + q.getTheta());
+     AxisAngle4f a = new AxisAngle4f();
+     a.set(mat);
+     Vector3f v = Vector3f.new3(a.x, a.y, a.z);
+     v.normalize();
+     System.out.println("angleAxis: " + v + " "+(a.angle/Math.PI * 180));
+     */
+     
+    return q;
+  }
+
+  public M3 getMatrix() {
+    if (mat == null)
+      setMatrix();
+    return mat;
+  }
+
+  private void setMatrix() {
+    mat = new M3();
+    // q0 = w, q1 = x, q2 = y, q3 = z
+    mat.m00 = q0 * q0 + q1 * q1 - q2 * q2 - q3 * q3;
+    mat.m01 = 2 * q1 * q2 - 2 * q0 * q3;
+    mat.m02 = 2 * q1 * q3 + 2 * q0 * q2;
+    mat.m10 = 2 * q1 * q2 + 2 * q0 * q3;
+    mat.m11 = q0 * q0 - q1 * q1 + q2 * q2 - q3 * q3;
+    mat.m12 = 2 * q2 * q3 - 2 * q0 * q1;
+    mat.m20 = 2 * q1 * q3 - 2 * q0 * q2;
+    mat.m21 = 2 * q2 * q3 + 2 * q0 * q1;
+    mat.m22 = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3;
+  }
+
+  public Quat add(float x) {
+    // scalar theta addition (degrees) 
+   return newVA(getNormal(), getTheta() + x);
+  }
+
+  public Quat mul(float x) {
+    // scalar theta multiplication
+    return (x == 1 ? new4(q1, q2, q3, q0) : 
+      newVA(getNormal(), getTheta() * x));
+  }
+
+  public Quat mulQ(Quat p) {
+    return new4(
+        q0 * p.q1 + q1 * p.q0 + q2 * p.q3 - q3 * p.q2, 
+        q0 * p.q2 + q2 * p.q0 + q3 * p.q1 - q1 * p.q3, 
+        q0 * p.q3 + q3 * p.q0 + q1 * p.q2 - q2 * p.q1, 
+        q0 * p.q0 - q1 * p.q1 - q2 * p.q2 - q3 * p.q3);
+  }
+
+  public Quat div(Quat p) {
+    // unit quaternions assumed -- otherwise would scale by 1/p.dot(p)
+    return mulQ(p.inv());
+  }
+
+  public Quat divLeft(Quat p) {
+    // unit quaternions assumed -- otherwise would scale by 1/p.dot(p)
+    return this.inv().mulQ(p);
+  }
+
+  public float dot(Quat q) {
+    return this.q0 * q.q0 + this.q1 * q.q1 + this.q2 * q.q2 + this.q3 * q.q3;
+  }
+
+  public Quat inv() {
+    return new4(-q1, -q2, -q3, q0);
+  }
+
+  public Quat negate() {
+    return new4(-q1, -q2, -q3, -q0);
+  }
+
+  /**
+   * ensures 
+   * 
+   * 1) q0 > 0
+   * or
+   * 2) q0 = 0 and q1 > 0
+   * or
+   * 3) q0 = 0 and q1 = 0 and q2 > 0
+   * or
+   * 4) q0 = 0 and q1 = 0 and q2 = 0 and q3 > 0
+   * 
+   * @return 1 or -1  
+   * 
+   */
+
+  private float getFixFactor() {
+    return (q0 < 0 || 
+        q0 == 0 && (q1 < 0 || q1 == 0 && (q2 < 0 || q2 == 0 && q3 < 0)) ? -1 : 1);
+  }
+  
+  public V3 getVector(int i) {
+    return getVectorScaled(i, 1f);
+  }
+
+  public V3 getVectorScaled(int i, float scale) {
+    if (i == -1) {
+      scale *= getFixFactor();
+      return V3.new3(q1 * scale, q2 * scale, q3 * scale);
+    }
+    if (mat == null)
+      setMatrix();
+    V3 v = new V3();
+    mat.getColumnV(i, v);
+    if (scale != 1f)
+      v.scale(scale);
+    return v;
+  }
+
+  /**
+   * 
+   * @return  vector such that 0 <= angle <= 180
+   */
+  public V3 getNormal() {
+    V3 v = getRawNormal(this);
+    v.scale(getFixFactor());
+    return v;
+  }
+
+  private static V3 getRawNormal(Quat q) {
+    V3 v = V3.new3(q.q1, q.q2, q.q3);
+    if (v.length() == 0)
+      return V3.new3(0, 0, 1);
+    v.normalize();
+    return v;
+  }
+
+  /**
+   * 
+   * @return 0 <= angle <= 180 in degrees
+   */
+  public float getTheta() {
+    return (float) (Math.acos(Math.abs(q0)) * 2 * 180 / Math.PI);
+  }
+
+  public float getThetaRadians() {
+    return (float) (Math.acos(Math.abs(q0)) * 2);
+  }
+
+  /**
+   * 
+   * @param v0
+   * @return    vector option closest to v0
+   * 
+   */
+  public V3 getNormalDirected(V3 v0) {
+    V3 v = getNormal();
+    if (v.x * v0.x + v.y * v0.y + v.z * v0.z < 0) {
+      v.scale(-1);
+    }
+    return v;
+  }
+
+  public V3 get3dProjection(V3 v3d) {
+    v3d.set(q1, q2, q3);
+    return v3d;
+  }
+  
+  /**
+   * 
+   * @param axisAngle
+   * @return   fill in theta of axisAngle such that 
+   */
+  public P4 getThetaDirected(P4 axisAngle) {
+    //fills in .w;
+    float theta = getTheta();
+    V3 v = getNormal();
+    if (axisAngle.x * q1 + axisAngle.y * q2 + axisAngle.z * q3 < 0) {
+      v.scale(-1);
+      theta = -theta;
+    }
+    axisAngle.set4(v.x, v.y, v.z, theta);
+    return axisAngle;
+  }
+
+  /**
+   * 
+   * @param vector  a vector, same as for getNormalDirected
+   * @return   return theta 
+   */
+  public float getThetaDirectedV(V3 vector) {
+    //fills in .w;
+    float theta = getTheta();
+    V3 v = getNormal();
+    if (vector.x * q1 + vector.y * q2 + vector.z * q3 < 0) {
+      v.scale(-1);
+      theta = -theta;
+    }
+    return theta;
+  }
+
+  /**
+   *   Quaternions are saved as {q1, q2, q3, q0} 
+   * 
+   * While this may seem odd, it is so that for any point4 -- 
+   * planes, axisangles, and quaternions -- we can use the 
+   * first three coordinates to determine the relavent axis
+   * the fourth then gives us offset to {0,0,0} (plane), 
+   * rotation angle (axisangle), and cos(theta/2) (quaternion).
+   * @return {x y z w} (unnormalized)
+   */
+  public P4 toPoint4f() {
+    return P4.new4(q1, q2, q3, q0); // x,y,z,w
+  }
+
+  public A4 toAxisAngle4f() {
+    double theta = 2 * Math.acos(Math.abs(q0));
+    double sinTheta2 = Math.sin(theta/2);
+    V3 v = getNormal();
+    if (sinTheta2 < 0) {
+      v.scale(-1);
+      theta = Math.PI - theta;
+    }
+    return A4.newVA(v, (float) theta);
+  }
+
+  public T3 transform2(T3 pt, T3 ptNew) {
+    if (mat == null)
+      setMatrix();
+    mat.rotate2(pt, ptNew);
+    return ptNew;
+  }
+
+  public Quat leftDifference(Quat q2) {
+    //dq = q.leftDifference(qnext);//q.inv().mul(qnext);
+    Quat q2adjusted = (this.dot(q2) < 0 ? q2.negate() : q2);
+    return inv().mulQ(q2adjusted);
+  }
+
+  public Quat rightDifference(Quat q2) {
+    //dq = qnext.rightDifference(q);//qnext.mul(q.inv());
+    Quat q2adjusted = (this.dot(q2) < 0 ? q2.negate() : q2);
+    return mulQ(q2adjusted.inv());
+  }
+
+  /**
+   * 
+   *  Java axisAngle / plane / Point4f format
+   *  all have the format {x y z w}
+   *  so we go with that here as well
+   *   
+   * @return  "{q1 q2 q3 q0}"
+   */
+  @Override
+  public String toString() {
+    return "{" + q1 + " " + q2 + " " + q3 + " " + q0 + "}";
+  }
+
+  /**
+   * 
+   * @param data1
+   * @param data2
+   * @param nMax     > 0 --> limit to this number
+   * @param isRelative
+   * 
+   * @return       pairwise array of data1 / data2 or data1 \ data2
+   */
+  public static Quat[] div(Quat[] data1, Quat[] data2, int nMax, boolean isRelative) {
+    int n;
+    if (data1 == null || data2 == null || (n = Math.min(data1.length, data2.length)) == 0)
+      return null;
+    if (nMax > 0 && n > nMax)
+      n = nMax;
+    Quat[] dqs = new Quat[n];
+    for (int i = 0; i < n; i++) {
+      if (data1[i] == null || data2[i] == null)
+        return null;
+      dqs[i] = (isRelative ? data1[i].divLeft(data2[i]) : data1[i].div(data2[i]));
+    }
+    return dqs;
+  }
+  
+  public static Quat sphereMean(Quat[] data, float[] retStddev, float criterion) {
+    // Samuel R. Buss, Jay P. Fillmore: 
+    // Spherical averages and applications to spherical splines and interpolation. 
+    // ACM Trans. Graph. 20(2): 95-126 (2001)
+      if (data == null || data.length == 0)
+        return new Quat();
+      if (retStddev == null)
+        retStddev = new float[1];
+      if (data.length == 1) {
+        retStddev[0] = 0;
+        return newQ(data[0]);
+      }
+      float diff = Float.MAX_VALUE;
+      float lastStddev = Float.MAX_VALUE;
+      Quat qMean = simpleAverage(data);
+      int maxIter = 100; // typically goes about 5 iterations
+      int iter = 0;
+      while (diff > criterion && lastStddev != 0 && iter < maxIter) {
+        qMean = newMean(data, qMean);
+        retStddev[0] = stdDev(data, qMean);
+        diff = Math.abs(retStddev[0] - lastStddev);
+        lastStddev = retStddev[0];
+        //Logger.info(++iter + " sphereMean " + qMean + " stddev=" + lastStddev + " diff=" + diff);
+      }
+      return qMean;
+  }
+
+  /**
+   * Just a starting point.
+   * get average normal vector
+   * scale normal by average projection of vectors onto it
+   * create quaternion from this 3D projection
+   * 
+   * @param ndata
+   * @return approximate average
+   */
+  private static Quat simpleAverage(Quat[] ndata) {
+    V3 mean = V3.new3(0, 0, 1);
+    // using the directed normal ensures that the mean is 
+    // continually added to and never subtracted from 
+    V3 v = ndata[0].getNormal();
+    mean.add(v);
+    for (int i = ndata.length; --i >= 0;)
+      mean.add(ndata[i].getNormalDirected(mean));
+    mean.sub(v);
+    mean.normalize();
+    float f = 0;
+    // the 3D projection of the quaternion is [sin(theta/2)]*n
+    // so dotted with the normalized mean gets us an approximate average for sin(theta/2)
+    for (int i = ndata.length; --i >= 0;)
+      f += Math.abs(ndata[i].get3dProjection(v).dot(mean)); 
+    if (f != 0)
+      mean.scale(f / ndata.length);
+    // now convert f to the corresponding cosine instead of sine
+    f = (float) Math.sqrt(1 - mean.lengthSquared());
+    if (Float.isNaN(f))
+      f = 0;
+    return newP4(P4.new4(mean.x, mean.y, mean.z, f));
+  }
+
+  private static Quat newMean(Quat[] data, Quat mean) {
+    /* quaternion derivatives nicely take care of producing the necessary 
+     * metric. Since dq gives us the normal with the smallest POSITIVE angle, 
+     * we just scale by that -- using degrees.
+     * No special normalization is required.
+     * 
+     * The key is that the mean has been set up already, and dq.getTheta()
+     * will always return a value between 0 and 180. True, for groupings
+     * where dq swings wildly -- 178, 182, 178, for example -- there will
+     * be problems, but the presumption here is that there is a REASONABLE
+     * set of data. Clearly there are spherical data sets that simply cannot
+     * be assigned a mean. (For example, where the three projected points
+     * are equally distant on the sphere. We just can't worry about those
+     * cases here. Rather, if there is any significance to the data,
+     * there will be clusters of projected points, and the analysis will
+     * be meaningful.
+     * 
+     * Note that the hemisphere problem drops out because dq.getNormal() and
+     * dq.getTheta() will never return (n, 182 degrees) but will 
+     * instead return (-n, 2 degrees). That's just what we want in that case.
+     *
+     *  Note that the projection in this case is to 3D -- a set of vectors
+     *  in space with lengths proportional to theta (not the sin(theta/2) 
+     *  that is associated with a quaternion map).
+     *  
+     *  This is officially an "exponential" or "hyperbolic" projection.
+     *  
+     */
+    V3 sum = new V3();
+    V3 v;
+    Quat q, dq;
+    //System.out.println("newMean mean " + mean);
+    for (int i = data.length; --i >= 0;) {
+      q = data[i];
+      dq = q.div(mean);
+      v = dq.getNormal();
+      v.scale(dq.getTheta());
+      sum.add(v);
+    }
+    sum.scale(1f/data.length);
+    Quat dqMean = newVA(sum, sum.length());
+    //System.out.println("newMean dqMean " + dqMean + " " + dqMean.getNormal() + " " + dqMean.getTheta());
+    return dqMean.mulQ(mean);
+  }
+
+  /**
+   * @param data
+   * @param mean
+   * @return     standard deviation in units of degrees
+   */
+  private static float stdDev(Quat[] data, Quat mean) {
+    // the quaternion dot product gives q0 for dq (i.e. q / mean)
+    // that is, cos(theta/2) for theta between them
+    double sum2 = 0;
+    int n = data.length;
+    for (int i = n; --i >= 0;) {
+      float theta = data[i].div(mean).getTheta(); 
+      sum2 += theta * theta;
+    }
+    return (float) Math.sqrt(sum2 / n);
+  }
+
+  public float[] getEulerZYZ() {
+    // http://www.swarthmore.edu/NatSci/mzucker1/e27/diebel2006attitude.pdf
+    double rA, rB, rG;
+    if (q1 == 0 && q2 == 0) {
+      float theta = getTheta();
+      // pure Z rotation - ambiguous
+      return new float[] { q3 < 0 ? -theta : theta , 0, 0 };
+    }
+    rA = Math.atan2(2 * (q2 * q3 + q0 * q1), 2 * (-q1 * q3 + q0 * q2 ));
+    rB = Math.acos(q3 * q3 - q2 * q2 - q1 * q1 + q0 * q0);
+    rG = Math.atan2( 2 * (q2 * q3 - q0 * q1), 2 * (q0 * q2 + q1 * q3));
+    return new float[]  {(float) (rA / RAD_PER_DEG), (float) (rB / RAD_PER_DEG), (float) (rG / RAD_PER_DEG)};
+  } 
+
+  public float[] getEulerZXZ() {
+    // NOT http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
+    // http://www.swarthmore.edu/NatSci/mzucker1/e27/diebel2006attitude.pdf
+    double rA, rB, rG;
+    if (q1 == 0 && q2 == 0) {
+      float theta = getTheta();
+      // pure Z rotation - ambiguous
+      return new float[] { q3 < 0 ? -theta : theta , 0, 0 };
+    }
+    rA = Math.atan2(2 * (q1 * q3 - q0 * q2), 2 * (q0 * q1 + q2 * q3 ));
+    rB = Math.acos(q3 * q3 - q2 * q2 - q1 * q1 + q0 * q0);
+    rG = Math.atan2( 2 * (q1 * q3 + q0 * q2), 2 * (-q2 * q3 + q0 * q1));
+    return new float[]  {(float) (rA / RAD_PER_DEG), (float) (rB / RAD_PER_DEG), (float) (rG / RAD_PER_DEG)};
+  }
+
+}
diff --git a/src2/javajs/util/Rdr.java b/src2/javajs/util/Rdr.java
new file mode 100644 (file)
index 0000000..995a629
--- /dev/null
@@ -0,0 +1,614 @@
+/* $RCSfile$
+ * $Author: hansonr $
+ * $Date: 2007-04-05 09:07:28 -0500 (Thu, 05 Apr 2007) $
+ * $Revision: 7326 $
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2003-2005  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+package javajs.util;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+
+import java.util.Map;
+
+import javajs.api.Interface;
+
+
+import javajs.api.GenericCifDataParser;
+import javajs.api.GenericLineReader;
+import javajs.api.GenericZipTools;
+
+/**
+ * A general helper class for a variety of stream and reader functionality
+ * including:
+ * 
+ *  stream and byte magic-number decoding for PNG, PNGJ, ZIP, and GZIP streams
+ *  
+ *  various stream/reader methods, including UTF-encoded stream reading
+ *  
+ *  reflection-protected access to a CIF parser and ZIP tools
+ *  
+ *   
+ * 
+ * 
+ */
+public class Rdr implements GenericLineReader {
+
+  public static class StreamReader extends BufferedReader {
+
+    private BufferedInputStream stream;
+
+    public StreamReader(BufferedInputStream bis, String charSet) throws UnsupportedEncodingException {
+      super(new InputStreamReader(bis, (charSet == null ? "UTF-8" : charSet)));
+      stream = bis;
+    }
+    
+    public BufferedInputStream getStream() {
+      try {
+        stream.reset();
+      } catch (IOException e) {
+        // ignore
+      }
+      return stream;
+    }
+
+  }
+
+  BufferedReader reader;
+
+  public Rdr(BufferedReader reader) {
+    this.reader = reader;
+  }
+  
+  @Override
+  public String readNextLine() throws Exception {
+    return reader.readLine();
+  }
+
+  public static Map<String, Object> readCifData(GenericCifDataParser parser, BufferedReader br) {
+    return parser.set(null, br, false).getAllCifData();
+  }
+  
+  
+  ///////////
+  
+
+  /**
+   * 
+   * Read a UTF-8 byte array fully, converting it to a String.
+   * Called by Jmol's XMLReaders
+   * 
+   * @param bytes
+   * @return a UTF-8 string
+   */
+  public static String bytesToUTF8String(byte[] bytes) {
+       return streamToUTF8String(new BufferedInputStream(new ByteArrayInputStream(bytes)));
+  }
+
+  /**
+   * 
+   * Read a UTF-8 stream fully, converting it to a String.
+   * Called by Jmol's XMLReaders
+   * 
+   * @param bis
+   * @return a UTF-8 string
+   */
+  public static String streamToUTF8String(BufferedInputStream bis) {
+    String[] data = new String[1];
+    try {
+      readAllAsString(getBufferedReader(bis, "UTF-8"), -1, true, data, 0);
+    } catch (IOException e) {
+    }
+    return data[0];
+  }
+
+  /**
+   * Read an input stream fully, saving a byte array, then
+   * return a buffered reader to those bytes converted to string form.
+   * 
+   * @param bis
+   * @param charSet
+   * @return Reader
+   * @throws IOException
+   */
+  public static BufferedReader getBufferedReader(BufferedInputStream bis, String charSet)
+      throws IOException {
+    // could also just make sure we have a buffered input stream here.
+    if (getUTFEncodingForStream(bis) == Encoding.NONE)
+      return new StreamReader(bis, (charSet == null ? "UTF-8" : charSet));
+    byte[] bytes = getLimitedStreamBytes(bis, -1);
+    bis.close();
+    return getBR(charSet == null ? fixUTF(bytes) : new String(bytes, charSet));
+  }
+
+  /**
+   * This method is specifically for strings that are marked for UTF 8 or 16.
+   * 
+   * @param bytes
+   * @return UTF-decoded bytes
+   */
+       public static String fixUTF(byte[] bytes) {
+               Encoding encoding = getUTFEncoding(bytes);
+               if (encoding != Encoding.NONE)
+                       try {
+                               String s = new String(bytes, encoding.name().replace('_', '-'));
+                               switch (encoding) {
+                               case UTF8:
+                               case UTF_16BE:
+                               case UTF_16LE:
+                                       // extra byte at beginning removed
+                                       s = s.substring(1);
+                                       break;
+                               default:
+                                       break;
+                               }
+                               return s;
+                       } catch (UnsupportedEncodingException e) {
+                               System.out.println(e);
+                       }
+               return new String(bytes);
+       }
+
+  private static Encoding getUTFEncoding(byte[] bytes) {
+    if (bytes.length >= 3 && (bytes[0] & 0xFF) == 0xEF && (bytes[1] & 0xFF) == 0xBB && (bytes[2] & 0xFF) == 0xBF)
+      return Encoding.UTF8;
+    if (bytes.length >= 4 && (bytes[0] & 0xFF) == 0 && (bytes[1] & 0xFF) == 0 
+        && (bytes[2] & 0xFF) == 0xFE && (bytes[3] & 0xFF) == 0xFF)
+      return Encoding.UTF_32BE;
+    if (bytes.length >= 4 && (bytes[0] & 0xFF) == 0xFF && (bytes[1] & 0xFF) == 0xFE 
+        && (bytes[2] & 0xFF) == 0 && (bytes[3] & 0xFF) == 0)
+      return Encoding.UTF_32LE;
+    if (bytes.length >= 2 && (bytes[0] & 0xFF) == 0xFF && (bytes[1] & 0xFF) == 0xFE)
+      return Encoding.UTF_16LE;
+    if (bytes.length >= 2 && (bytes[0] & 0xFF) == 0xFE && (bytes[1] & 0xFF) == 0xFF)
+      return Encoding.UTF_16BE;
+    return Encoding.NONE;
+  
+  }
+  
+  ////////// stream type checking //////////
+  
+
+  private static Encoding getUTFEncodingForStream(BufferedInputStream is) throws IOException {
+//    /**
+//     * @j2sNative
+//     * 
+//     *  is.resetStream();
+//     * 
+//     */
+//    {
+//    }
+    byte[] abMagic = new byte[4];
+    abMagic[3] = 1;
+    try{
+    is.mark(5);
+    } catch (Exception e) {
+      return Encoding.NONE;
+    }
+    is.read(abMagic, 0, 4);
+    is.reset();
+    return getUTFEncoding(abMagic);
+  }
+
+  public static boolean isBase64(SB sb) {
+    return (sb.indexOf(";base64,") == 0);
+  }
+
+  public static boolean isCompoundDocumentS(InputStream is) {
+    return isCompoundDocumentB(getMagic(is, 8));
+  }
+
+  public static boolean isCompoundDocumentB(byte[] bytes) {
+    return (bytes.length >= 8 && (bytes[0] & 0xFF) == 0xD0
+        && (bytes[1] & 0xFF) == 0xCF && (bytes[2] & 0xFF) == 0x11
+        && (bytes[3] & 0xFF) == 0xE0 && (bytes[4] & 0xFF) == 0xA1
+        && (bytes[5] & 0xFF) == 0xB1 && (bytes[6] & 0xFF) == 0x1A 
+        && (bytes[7] & 0xFF) == 0xE1);
+  }
+
+  public static boolean isBZip2S(InputStream is) {
+    return isBZip2B(getMagic(is, 3));
+  }
+
+  public static boolean isGzipS(InputStream is) {
+    return isGzipB(getMagic(is, 2));
+  }
+
+  public static boolean isBZip2B(byte[] bytes) {    
+    return (bytes != null && bytes.length >= 3  // BZh
+        && (bytes[0] & 0xFF) == 0x42 && (bytes[1] & 0xFF) == 0x5A  && (bytes[2] & 0xFF) == 0x68);
+}
+
+  public static boolean isGzipB(byte[] bytes) {    
+      return (bytes != null && bytes.length >= 2 
+          && (bytes[0] & 0xFF) == 0x1F && (bytes[1] & 0xFF) == 0x8B);
+  }
+
+  public static boolean isPickleS(InputStream is) {
+    return isPickleB(getMagic(is, 2));
+  }
+  
+  public static boolean isPickleB(byte[] bytes) {    
+      return (bytes != null && bytes.length >= 2 
+          && (bytes[0] & 0xFF) == 0x7D && (bytes[1] & 0xFF) == 0x71);
+  }
+
+  public static boolean isMessagePackS(InputStream is) {
+    return isMessagePackB(getMagic(is, 2));
+  }
+
+  public static boolean isMessagePackB(byte[] bytes) {
+    // look for 'map' start, but PNG files start with 0x89, which is
+    // the MessagePack start for a 9-member map, so in that case we have
+    // to check that the next byte is not "P" as in <89>PNG
+    int b;
+    
+    return (bytes != null && bytes.length >= 1 && (((b = bytes[0] & 0xFF)) == 0xDE || (b & 0xE0) == 0x80 && bytes[1] != 0x50));
+  }
+
+  public static boolean isPngZipStream(InputStream is) {
+    return isPngZipB(getMagic(is, 55));
+  }
+
+  public static boolean isPngZipB(byte[] bytes) {
+    // \0PNGJ starting at byte 50
+    return (bytes[50] == 0 && bytes[51] == 0x50 && bytes[52] == 0x4E && bytes[53] == 0x47 && bytes[54] == 0x4A);
+  }
+
+  /**
+   * Check for a ZIP input stream - starting with "PK<03><04>"
+   * @param is
+   * @return true if a ZIP stream
+   */
+  public static boolean isZipS(InputStream is) {
+    return isZipB(getMagic(is, 4));
+  }
+
+  public static boolean isZipB(byte[] bytes) {
+    return (bytes.length >= 4 
+        && bytes[0] == 0x50  //PK<03><04> 
+        && bytes[1] == 0x4B
+        && bytes[2] == 0x03 
+        && bytes[3] == 0x04);
+  }
+
+  public static byte[] getMagic(InputStream is, int n) {
+    byte[] abMagic = new byte[n];
+//    /**
+//     * @j2sNative
+//     * 
+//     * is.resetStream();
+//     * 
+//     */
+//    {
+//    }
+    try {
+      is.mark(n + 1);
+      is.read(abMagic, 0, n);
+    } catch (IOException e) {
+    }
+    try {
+      is.reset();
+    } catch (IOException e) {
+    }
+    return abMagic;
+  }
+
+  public static String guessMimeTypeForBytes(byte[] bytes) {
+     // only options here are JPEG, PNG, GIF, and BMP
+    switch (bytes.length < 2 ? -1 : bytes[1]) {
+    case 0:
+      return "image/jpg"; // 0xFF 0x00 ...
+    case 0x49:
+      return "image/gif"; // GIF89a...
+    case 0x4D:
+      return "image/BMP"; // BM...
+    case 0x50:
+      return "image/png";
+    default:
+      return  "image/unknown";
+    }
+  }
+
+
+  ////////// stream/byte methods ///////////
+  
+  public static BufferedInputStream getBIS(byte[] bytes) {
+    return new BufferedInputStream(new ByteArrayInputStream(bytes));
+  }
+
+  public static BufferedReader getBR(String string) {
+    return new BufferedReader(new StringReader(string));
+  }
+
+  
+       public static BufferedInputStream toBIS(Object o) {
+               return (AU.isAB(o) ? getBIS((byte[]) o)
+                               : o instanceof SB ? getBIS(Rdr.getBytesFromSB((SB) o))
+                                               : o instanceof String ? getBIS(((String) o).getBytes()) : null);
+       }
+
+
+  /**
+   * Drill down into a GZIP stack until no more layers.
+   * @param jzt 
+   * 
+   * @param bis
+   * @return non-gzipped buffered input stream.
+   * 
+   * @throws IOException
+   */
+  public static BufferedInputStream getUnzippedInputStream(GenericZipTools jzt, BufferedInputStream bis) throws IOException {
+    while (isGzipS(bis))
+      bis = new BufferedInputStream(jzt.newGZIPInputStream(bis));
+    return bis;
+  }
+
+  public static BufferedInputStream getUnzippedInputStreamBZip2(GenericZipTools jzt,
+                                                                BufferedInputStream bis) throws IOException  {
+    while (isBZip2S(bis))
+      bis = new BufferedInputStream(jzt.newBZip2InputStream(bis));
+    return bis;
+  }
+
+
+  /**
+   * Allow for base64-encoding check.
+   * 
+   * @param sb
+   * @return byte array
+   */
+  public static byte[] getBytesFromSB(SB sb) {
+    return (isBase64(sb) ? Base64.decodeBase64(sb.substring(8)) : sb.toBytes(0, -1));    
+  }
+
+ /**
+   * Read a an entire BufferedInputStream for its bytes, and 
+   * either return them or leave them in the designated output channel.
+   *  
+   * @param bis
+   * @param out a destination output channel, or null
+   * @return byte[] (if out is null) or a message indicating length (if not)
+   * 
+   * @throws IOException
+   */
+  public static Object getStreamAsBytes(BufferedInputStream bis,
+                                         OC out) throws IOException {
+    byte[] buf = new byte[1024];
+    byte[] bytes = (out == null ? new byte[4096] : null);
+    int len = 0;
+    int totalLen = 0;
+    while ((len = bis.read(buf, 0, 1024)) > 0) {
+      totalLen += len;
+      if (out == null) {
+        if (totalLen >= bytes.length)
+          bytes = AU.ensureLengthByte(bytes, totalLen * 2);
+        System.arraycopy(buf, 0, bytes, totalLen - len, len);
+      } else {
+        out.write(buf, 0, len);
+      }
+    }
+    bis.close();
+    if (out == null) {
+      return AU.arrayCopyByte(bytes, totalLen);
+    }
+    return totalLen + " bytes";
+  }
+
+  /**
+   * Read a possibly limited number of bytes (when n > 0) from a stream, 
+   * leaving the stream open.
+   * 
+   * @param is an input stream, not necessarily buffered.
+   * @param n the maximum number of bytes to read, or -1 for all
+   * @return the bytes read
+   * 
+   * @throws IOException
+   */
+  public static byte[] getLimitedStreamBytes(InputStream is, long n)
+      throws IOException {
+
+    //Note: You cannot use InputStream.available() to reliably read
+    //      zip data from the web. 
+
+    int buflen = (n > 0 && n < 1024 ? (int) n : 1024);
+    byte[] buf = new byte[buflen];
+    byte[] bytes = new byte[n < 0 ? 4096 : (int) n];
+    int len = 0;
+    int totalLen = 0;
+    if (n < 0)
+      n = Integer.MAX_VALUE;
+    while (totalLen < n && (len = is.read(buf, 0, buflen)) > 0) {
+      totalLen += len;
+      if (totalLen > bytes.length)
+        bytes = AU.ensureLengthByte(bytes, totalLen * 2);
+      System.arraycopy(buf, 0, bytes, totalLen - len, len);
+      if (n != Integer.MAX_VALUE && totalLen + buflen > bytes.length)
+        buflen = bytes.length - totalLen;
+
+    }
+    if (totalLen == bytes.length)
+      return bytes;
+    buf = new byte[totalLen];
+    System.arraycopy(bytes, 0, buf, 0, totalLen);
+    return buf;
+  }
+
+  /**
+   * This method fills data[i] with string data from a file that may or may not
+   * be binary even though it is being read by a reader. It is meant to be used
+   * simple text-based files only.
+   *  
+   * @param br
+   * @param nBytesMax
+   * @param allowBinary
+   * @param data
+   * @param i
+   * @return true if data[i] holds the data; false if data[i] holds an error message. 
+   */
+  public static boolean readAllAsString(BufferedReader br, int nBytesMax, boolean allowBinary, String[] data, int i) {
+    try {
+      SB sb = SB.newN(8192);
+      String line;
+      if (nBytesMax < 0) {
+        line = br.readLine();
+        if (allowBinary || line != null && line.indexOf('\0') < 0
+            && (line.length() != 4 || line.charAt(0) != 65533
+            || line.indexOf("PNG") != 1)) {
+          sb.append(line).appendC('\n');
+          while ((line = br.readLine()) != null)
+            sb.append(line).appendC('\n');
+        }
+      } else {
+        int n = 0;
+        int len;
+        while (n < nBytesMax && (line = br.readLine()) != null) {
+          if (nBytesMax - n < (len = line.length()) + 1)
+            line = line.substring(0, nBytesMax - n - 1);
+          sb.append(line).appendC('\n');
+          n += len + 1;
+        }
+      }
+      br.close();
+      data[i] = sb.toString();
+      return true;
+    } catch (Exception ioe) {
+      data[i] = ioe.toString();
+      return false;
+    }
+  }
+
+  
+  /////////// PNGJ support /////////////
+  
+  
+  /**
+   * Look at byte 50 for "\0PNGJxxxxxxxxx+yyyyyyyyy" where xxxxxxxxx is a byte
+   * offset to the JMOL data and yyyyyyyyy is the length of the data.
+   * 
+   * @param bis
+   * @return same stream or byte stream
+   */
+
+  /**
+   * Retrieve the two numbers in a PNG iTXt tag indicating the 
+   * file pointer for the start of the ZIP data as well as its length.
+   * 
+   * @param bis
+   * @param pt_count
+   */
+  static void getPngZipPointAndCount(BufferedInputStream bis, int[] pt_count) {
+    bis.mark(75);
+    try {
+      byte[] data = getLimitedStreamBytes(bis, 74);
+      bis.reset();
+      int pt = 0;
+      for (int i = 64, f = 1; --i > 54; f *= 10)
+        pt += (data[i] - '0') * f;
+      int n = 0;
+      for (int i = 74, f = 1; --i > 64; f *= 10)
+        n += (data[i] - '0') * f;
+      pt_count[0] = pt;
+      pt_count[1] = n;
+    } catch (Throwable e) {
+      pt_count[1] = 0;
+    }
+  }
+
+  /**
+   * Either advance a PNGJ stream to its zip file data or pull out the ZIP data
+   * bytes and create a new stream for them from which a ZIP utility can start
+   * extracting files.
+   * 
+   * @param bis
+   * @param asNewStream  
+   * @return new buffered ByteArrayInputStream, possibly with no data if there is an error
+   */
+  public static BufferedInputStream getPngZipStream(BufferedInputStream bis, boolean asNewStream) {
+    if (!isPngZipStream(bis))
+      return bis;
+    byte[] data = new byte[0];
+    bis.mark(75);
+    try {
+      int pt_count[] = new int[2];
+      getPngZipPointAndCount(bis, pt_count);
+      if (pt_count[1] != 0) {
+        int pt = pt_count[0];
+        while (pt > 0)
+          pt -= bis.skip(pt);
+        if (!asNewStream)
+          return bis;
+        data = getLimitedStreamBytes(bis, pt_count[1]);
+      }
+    } catch (Throwable e) {
+    } finally {
+      try {
+        if (asNewStream)
+          bis.close();
+      } catch (Exception e) {
+        // ignore
+      }
+    }
+    return getBIS(data);
+  }
+
+  /** We define a request for zip file extraction by vertical bar:
+   *  zipName|interiorFileName. These may be nested if there is a
+   *  zip file contained in a zip file. 
+   *  
+   * @param fileName
+   * @return filename trimmed of interior fileName
+   * 
+   */
+  public static String getZipRoot(String fileName) {
+    int pt = fileName.indexOf("|");
+    return (pt < 0 ? fileName : fileName.substring(0, pt));
+  }
+
+       public static BufferedWriter getBufferedWriter(OutputStream os, String charSetName) {
+               OutputStreamWriter osw = (OutputStreamWriter) Interface.getInstanceWithParams("java.io.OutputStreamWriter", 
+                               new Class<?>[] { java.io.OutputStream.class, String.class }, 
+                               new Object[] { os, charSetName == null ? "UTF-8" : charSetName }
+               );
+               /**
+                * @j2sNative
+                * return osw.getBufferedWriter();
+                * 
+                */
+               {
+                       return new BufferedWriter(osw);
+               }
+       }
+
+  
+}
+
diff --git a/src2/javajs/util/SB.java b/src2/javajs/util/SB.java
new file mode 100644 (file)
index 0000000..aed71f3
--- /dev/null
@@ -0,0 +1,354 @@
+
+package javajs.util;
+
+import java.nio.charset.Charset;
+
+/**
+ * Interesting thing here is that JavaScript is 3x faster than Java in handling strings.
+ * 
+ * Java StringBuilder is final, unfortunately. I guess they weren't thinking about Java2Script!
+ * 
+ * The reason we have to do this that several overloaded append methods is WAY too expensive
+ * 
+ */
+
+public class SB {
+  
+  private java.lang.StringBuilder sb;
+  String s; // used by JavaScript only; no Java references
+  
+  //TODO: JS experiment with using array and .push() here
+
+  public SB() {
+    /**
+     * @j2sNative
+     * 
+     *            this.s = "";
+     * 
+     */
+    {
+      sb = new java.lang.StringBuilder();
+    }
+  }
+
+  public static SB newN(int n) {
+    /**
+     * @j2sNative
+     *            return new javajs.util.SB(); 
+     */
+    {
+      // not perfect, because it requires defining sb twice. 
+      // We can do better...
+      SB sb = new SB();
+      sb.sb = new java.lang.StringBuilder(n);
+      return sb;
+    }
+  }
+
+  public static SB newS(String s) {
+    /**
+     * @j2sNative 
+     * 
+     * var sb = new javajs.util.SB();
+     * sb.s = s;
+     * return sb; 
+     * 
+     */
+    {
+    SB sb = new SB();
+    sb.sb = new java.lang.StringBuilder(s);
+    return sb;
+    }
+  }
+
+  public SB append(String s) {
+    /**
+     * @j2sNative
+     * 
+     *            this.s += s
+     * 
+     */
+    {
+      sb.append(s);
+    }
+    return this;
+  }
+  
+  public SB appendC(char c) {
+    /**
+     * @j2sNative
+     * 
+     *            this.s += c;
+     */
+    {
+      sb.append(c);
+    }
+    return this;
+    
+  }
+
+  public SB appendI(int i) {
+    /**
+     * @j2sNative
+     * 
+     *            this.s += i
+     * 
+     */
+    {
+      sb.append(i);
+    }
+    return this;
+  }
+
+  public SB appendB(boolean b) {
+    /**
+     * @j2sNative
+     * 
+     *            this.s += b
+     * 
+     */
+    {
+      sb.append(b);
+    }
+    return this;
+  }
+
+  /**
+   * note that JavaScript could drop off the ".0" in "1.0"
+   * @param f
+   * @return this
+   */
+  public SB appendF(float f) {
+    /**
+     * @j2sNative
+     * 
+     * var sf = "" + f;
+     * if (sf.indexOf(".") < 0 && sf.indexOf("e") < 0)
+     *   sf += ".0" ;
+     *            this.s += sf;
+     * 
+     */
+    {
+      sb.append(f);
+    }
+    return this;
+  }
+
+  public SB appendD(double d) {
+    /**
+     * @j2sNative
+     * 
+     * var sf = "" + d;
+     * if (sf.indexOf(".") < 0 && sf.indexOf("e") < 0)
+     *   sf += ".0" ;
+     *            this.s += sf;
+     * 
+     */
+    {
+      sb.append(d);
+    }
+    return this;
+  }
+
+  public SB appendSB(SB buf) {
+    /**
+     * @j2sNative
+     * 
+     *            this.s += buf.s;
+     * 
+     */
+    {
+      sb.append(buf.sb);
+    }
+    return this;
+  }
+
+  public SB appendO(Object data) {
+    if (data != null) {
+      /**
+       * @j2sNative
+       * 
+       *            this.s += data.toString();
+       * 
+       */
+      {
+        sb.append(data);
+      }
+    }
+    return this;
+  }
+
+  public void appendCB(char[] cb, int off, int len) {
+    /**
+     * @j2sNative
+     * 
+     * this.s += cb.slice(off,off+len).join("");
+     * 
+     */
+    {
+       sb.append(cb, off, len);
+    }
+  }
+
+  @Override
+  public String toString() {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s;
+     * 
+     */
+    {
+      return sb.toString();
+    }
+  }
+
+  public int length() {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s.length;
+     * 
+     */
+    {
+      return sb.length();
+    }
+  }
+
+  public int indexOf(String s) {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s.indexOf(s);
+     * 
+     */
+    {
+      return sb.indexOf(s);
+    }
+  }
+
+  public char charAt(int i) {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s.charAt(i);
+     * 
+     */
+    {
+      return sb.charAt(i);
+    }
+  }
+
+  public int charCodeAt(int i) {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s.charCodeAt(i);
+     * 
+     */
+    {
+      return sb.codePointAt(i);
+    }
+  }
+
+  public void setLength(int n) {
+    /**
+     * @j2sNative
+     * 
+     *            this.s = this.s.substring(0, n);
+     */
+    {
+      sb.setLength(n);
+    }
+  }
+
+  public int lastIndexOf(String s) {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s.lastIndexOf(s);
+     */
+    {
+      return sb.lastIndexOf(s);
+    }
+  }
+
+  public int indexOf2(String s, int i) {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s.indexOf(s, i);
+     */
+    {
+      return sb.indexOf(s, i);
+    }
+  }
+
+  public String substring(int i) {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s.substring(i);
+     */
+    {
+      return sb.substring(i);
+    }
+  }
+
+  public String substring2(int i, int j) {
+    /**
+     * @j2sNative
+     * 
+     *            return this.s.substring(i, j);
+     */
+    {
+      return sb.substring(i, j);
+    }
+  }
+
+  /**
+   * simple byte conversion properly implementing UTF-8. * Used for base64
+   * conversion and allows for offset
+   * 
+   * @param off
+   * @param len
+   *        or -1 for full length (then off must = 0)
+   * @return byte[]
+   */
+  public byte[] toBytes(int off, int len) {
+    if (len == 0)
+      return new byte[0];
+    Charset cs;
+    /**
+     * 
+     * just a string in JavaScript
+     * 
+     * @j2sNative
+     * 
+     *            cs = "UTF-8";
+     * 
+     */
+    {
+      cs = Charset.forName("UTF-8");
+    }
+    return (len > 0 ? substring2(off, off + len) 
+        : off == 0 ? toString()
+        : substring2(off, length() - off)).getBytes(cs);
+  }
+
+       public void replace(int start, int end, String str) {
+               /**
+                * @j2sNative
+                * 
+                * this.s = this.s.substring(0, start) + str + this.s.substring(end);
+                */
+               {
+                       sb.replace(start, end, str);
+               }
+       }
+
+       public void insert(int offset, String str) {
+               replace(offset, offset, str);
+       }
+
+}
diff --git a/src2/javajs/util/StringDataReader.java b/src2/javajs/util/StringDataReader.java
new file mode 100644 (file)
index 0000000..e78a6f8
--- /dev/null
@@ -0,0 +1,51 @@
+/* $RCSfile$
+ * $Author$
+ * $Date$
+ * $Revision$
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2011  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301, USA.
+ */
+
+package javajs.util;
+
+import java.io.StringReader;
+
+
+
+
+
+public class StringDataReader extends DataReader {
+
+  public StringDataReader() {
+    super();
+  }
+  
+  public StringDataReader(String data) {
+    super(new StringReader(data));
+  }
+
+  @Override
+  public DataReader setData(Object data) {
+    return new StringDataReader((String) data);
+  }
+}
\ No newline at end of file
diff --git a/src2/javajs/util/T3.java b/src2/javajs/util/T3.java
new file mode 100644 (file)
index 0000000..6cd5108
--- /dev/null
@@ -0,0 +1,337 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+import java.io.Serializable;
+
+import javajs.api.JSONEncodable;
+
+/**
+ * A generic 3 element tuple that is represented by single precision floating
+ * point x,y and z coordinates.
+ * 
+ * @version specification 1.1, implementation $Revision: 1.10 $, $Date:
+ *          2006/09/08 20:20:20 $
+ * @author Kenji hiranabe
+ * 
+ * additions by Bob Hanson hansonr@stolaf.edu 9/30/2012
+ * for unique constructor and method names
+ * for the optimization of compiled JavaScript using Java2Script
+ */
+public abstract class T3 implements JSONEncodable, Serializable {
+
+  public float x, y, z;
+
+  public T3() {
+  }
+
+  /**
+   * Sets the value of this tuple to the specified xyz coordinates.
+   * 
+   * @param x
+   *        the x coordinate
+   * @param y
+   *        the y coordinate
+   * @param z
+   *        the z coordinate
+   */
+  public final void set(float x, float y, float z) {
+    this.x = x;
+    this.y = y;
+    this.z = z;
+  }
+
+  /**
+   * Sets the value of this tuple from the 3 values specified in the array.
+   * 
+   * @param t
+   *        the array of length 3 containing xyz in order
+   */
+  public final void setA(float t[]) {
+    // ArrayIndexOutOfBounds is thrown if t.length < 3
+    x = t[0];
+    y = t[1];
+    z = t[2];
+  }
+
+  /**
+   * Sets the value of this tuple to the value of the Tuple3f argument.
+   * 
+   * @param t1
+   *        the tuple to be copied
+   */
+  public final void setT(T3 t1) {
+    x = t1.x;
+    y = t1.y;
+    z = t1.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the vector sum of tuples t1 and t2.
+   * 
+   * @param t1
+   *        the first tuple
+   * @param t2
+   *        the second tuple
+   */
+  public final void add2(T3 t1, T3 t2) {
+    x = t1.x + t2.x;
+    y = t1.y + t2.y;
+    z = t1.z + t2.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the vector sum of itself and tuple t1.
+   * 
+   * @param t1
+   *        the other tuple
+   */
+  public final void add(T3 t1) {
+    x += t1.x;
+    y += t1.y;
+    z += t1.z;
+  }
+
+  /**
+   * Computes the square of the distance between this point and point p1.
+   * 
+   * @param p1
+   *        the other point
+   * @return the square of distance between these two points as a float
+   */
+  public final float distanceSquared(T3 p1) {
+    double dx = x - p1.x;
+    double dy = y - p1.y;
+    double dz = z - p1.z;
+    return (float) (dx * dx + dy * dy + dz * dz);
+  }
+
+  /**
+   * Returns the distance between this point and point p1.
+   * 
+   * @param p1
+   *        the other point
+   * @return the distance between these two points
+   */
+  public final float distance(T3 p1) {
+    return (float) Math.sqrt(distanceSquared(p1));
+  }
+
+  /**
+   * Sets the value of this tuple to the vector difference of tuple t1 and t2
+   * (this = t1 - t2).
+   * 
+   * @param t1
+   *        the first tuple
+   * @param t2
+   *        the second tuple
+   */
+  public final void sub2(T3 t1, T3 t2) {
+    x = t1.x - t2.x;
+    y = t1.y - t2.y;
+    z = t1.z - t2.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the vector difference of itself and tuple
+   * t1 (this = this - t1).
+   * 
+   * @param t1
+   *        the other tuple
+   */
+  public final void sub(T3 t1) {
+    x -= t1.x;
+    y -= t1.y;
+    z -= t1.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the scalar multiplication of itself.
+   * 
+   * @param s
+   *        the scalar value
+   */
+  public final void scale(float s) {
+    x *= s;
+    y *= s;
+    z *= s;
+  }
+
+  /**
+   * Add {a b c}
+   * 
+   * @param a
+   * @param b
+   * @param c
+   */
+  public final void add3(float a, float b, float c) {
+    x += a;
+    y += b;
+    z += c;
+  }
+
+  
+  /**
+   * {x*p.x, y*p.y, z*p.z)  used for three-way scaling
+   * 
+   * @param p
+   */
+  public final void scaleT(T3 p) {
+    x *= p.x;
+    y *= p.y;
+    z *= p.z;
+  }
+
+  
+  /**
+   * Sets the value of this tuple to the scalar multiplication of tuple t1 and
+   * then adds tuple t2 (this = s*t1 + t2).
+   * 
+   * @param s
+   *        the scalar value
+   * @param t1
+   *        the tuple to be multipled
+   * @param t2
+   *        the tuple to be added
+   */
+  public final void scaleAdd2(float s, T3 t1, T3 t2) {
+    x = s * t1.x + t2.x;
+    y = s * t1.y + t2.y;
+    z = s * t1.z + t2.z;
+  }
+
+  
+  /**
+   * average of two tuples
+   * 
+   * @param a
+   * @param b
+   */
+  public void ave(T3 a, T3 b) {
+    x = (a.x + b.x) / 2f;
+    y = (a.y + b.y) / 2f;
+    z = (a.z + b.z) / 2f; 
+  }
+
+  /**
+   * Vector dot product. Was in Vector3f; more useful here, though.
+   * 
+   * @param v
+   *        the other vector
+   * @return this.dot.v
+   */
+  public final float dot(T3 v) {
+    return x * v.x + y * v.y + z * v.z;
+  }
+
+  /**
+   * Returns the squared length of this vector.
+   * Was in Vector3f; more useful here, though.
+   * 
+   * @return the squared length of this vector
+   */
+  public final float lengthSquared() {
+    return x * x + y * y + z * z;
+  }
+
+  /**
+   * Returns the length of this vector.
+   * Was in Vector3f; more useful here, though.
+   * 
+   * @return the length of this vector
+   */
+  public final float length() {
+    return (float) Math.sqrt(lengthSquared());
+  }
+
+  /**
+   * Normalizes this vector in place.
+   * Was in Vector3f; more useful here, though.
+   */
+  public final void normalize() {
+    double d = length();
+
+    // zero-div may occur.
+    x /= d;
+    y /= d;
+    z /= d;
+  }
+
+  /**
+   * Sets this tuple to be the vector cross product of vectors v1 and v2.
+   * 
+   * @param v1
+   *        the first vector
+   * @param v2
+   *        the second vector
+   */
+  public final void cross(T3 v1, T3 v2) {
+    set(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y
+        - v1.y * v2.x);
+  }
+
+  /**
+   * Returns a hash number based on the data values in this object. Two
+   * different Tuple3f objects with identical data values (ie, returns true for
+   * equals(Tuple3f) ) will return the same hash number. Two vectors with
+   * different data members may return the same hash value, although this is not
+   * likely.
+   */
+  @Override
+  public int hashCode() {
+    long bits = 1L;
+    bits = 31L * bits + floatToIntBits(x);
+    bits = 31L * bits + floatToIntBits(y);
+    bits = 31L * bits + floatToIntBits(z);
+    return (int) (bits ^ (bits >> 32));
+  }
+
+  public static int floatToIntBits(float x) {
+    return (x == 0 ? 0 : Float.floatToIntBits(x));
+  }
+
+  /**
+   * Returns true if all of the data members of Tuple3f t1 are equal to the
+   * corresponding data members in this
+   * 
+   * @param t1
+   *        the vector with which the comparison is made.
+   */
+  @Override
+  public boolean equals(Object t1) {
+    if (!(t1 instanceof T3))
+      return false;
+    T3 t2 = (T3) t1;
+    return (x == t2.x && y == t2.y && z == t2.z);
+  }
+
+  /**
+   * Returns a string that contains the values of this Tuple3f. The form is
+   * (x,y,z).
+   * 
+   * @return the String representation
+   */
+  @Override
+  public String toString() {
+    return "{" + x + ", " + y + ", " + z + "}";
+  }
+  
+  @Override
+  public String toJSON() {
+    return "[" + x + "," + y + "," + z + "]";
+  }
+}
diff --git a/src2/javajs/util/T3d.java b/src2/javajs/util/T3d.java
new file mode 100644 (file)
index 0000000..08d02d7
--- /dev/null
@@ -0,0 +1,225 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+import java.io.Serializable;
+
+/**
+ * A generic 3 element tuple that is represented by double precision floating
+ * point x,y and z coordinates.
+ * 
+ * @version specification 1.1, implementation $Revision: 1.9 $, $Date:
+ *          2006/07/28 17:01:32 $
+ * @author Kenji hiranabe
+ * 
+ * additions by Bob Hanson hansonr@stolaf.edu 9/30/2012
+ * for unique constructor and method names
+ * for the optimization of compiled JavaScript using Java2Script
+ */
+public abstract class T3d implements Serializable {
+  /**
+   * The x coordinate.
+   */
+  public double x;
+
+  /**
+   * The y coordinate.
+   */
+  public double y;
+
+  /**
+   * The z coordinate.
+   */
+  public double z;
+
+  /**
+   * Constructs and initializes a Tuple3d to (0,0,0).
+   */
+  public T3d() {
+  }
+
+  /**
+   * Sets the value of this tuple to the specified xyz coordinates.
+   * 
+   * @param x
+   *        the x coordinate
+   * @param y
+   *        the y coordinate
+   * @param z
+   *        the z coordinate
+   */
+  public final void set(double x, double y, double z) {
+    this.x = x;
+    this.y = y;
+    this.z = z;
+  }
+
+  /**
+   * Sets the value of this tuple from the 3 values specified in the array.
+   * 
+   * @param t
+   *        the array of length 3 containing xyz in order
+   */
+  public final void setA(double t[]) {
+    // ArrayIndexOutOfBounds is thrown if t.length < 3
+    x = t[0];
+    y = t[1];
+    z = t[2];
+  }
+
+  /**
+   * Sets the value of this tuple to the value of the Tuple3d argument.
+   * 
+   * @param t1
+   *        the tuple to be copied
+   */
+  public final void setT(T3d t1) {
+    x = t1.x;
+    y = t1.y;
+    z = t1.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the vector sum of tuples t1 and t2.
+   * 
+   * @param t1
+   *        the first tuple
+   * @param t2
+   *        the second tuple
+   */
+  public final void add2(T3d t1, T3d t2) {
+    x = t1.x + t2.x;
+    y = t1.y + t2.y;
+    z = t1.z + t2.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the vector sum of itself and tuple t1.
+   * 
+   * @param t1
+   *        the other tuple
+   */
+  public final void add(T3d t1) {
+    x += t1.x;
+    y += t1.y;
+    z += t1.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the vector difference of tuple t1 and t2
+   * (this = t1 - t2).
+   * 
+   * @param t1
+   *        the first tuple
+   * @param t2
+   *        the second tuple
+   */
+  public final void sub2(T3d t1, T3d t2) {
+    x = t1.x - t2.x;
+    y = t1.y - t2.y;
+    z = t1.z - t2.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the vector difference of itself and tuple
+   * t1 (this = this - t1).
+   * 
+   * @param t1
+   *        the other tuple
+   */
+  public final void sub(T3d t1) {
+    x -= t1.x;
+    y -= t1.y;
+    z -= t1.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the scalar multiplication of itself.
+   * 
+   * @param s
+   *        the scalar value
+   */
+  public final void scale(double s) {
+    x *= s;
+    y *= s;
+    z *= s;
+  }
+
+  /**
+   * Sets the value of this tuple to the scalar multiplication of tuple t1 and
+   * then adds tuple t2 (this = s*t1 + t2).
+   * 
+   * @param s
+   *        the scalar value
+   * @param t1
+   *        the tuple to be multipled
+   * @param t2
+   *        the tuple to be added
+   */
+  public final void scaleAdd(double s, T3d t1, T3d t2) {
+    x = s * t1.x + t2.x;
+    y = s * t1.y + t2.y;
+    z = s * t1.z + t2.z;
+  }
+
+  /**
+   * Returns a hash number based on the data values in this object. Two
+   * different Tuple3d objects with identical data values (ie, returns true for
+   * equals(Tuple3d) ) will return the same hash number. Two vectors with
+   * different data members may return the same hash value, although this is not
+   * likely.
+   */
+  @Override
+  public int hashCode() {
+    long xbits = doubleToLongBits0(x);
+    long ybits = doubleToLongBits0(y);
+    long zbits = doubleToLongBits0(z);
+    return (int) (xbits ^ (xbits >> 32) ^ ybits ^ (ybits >> 32) ^ zbits ^ (zbits >> 32));
+  }
+
+  static long doubleToLongBits0(double d) {
+    // Check for +0 or -0
+    return (d == 0 ? 0 : Double.doubleToLongBits(d));
+  }
+
+  /**
+   * Returns true if all of the data members of Tuple3d t1 are equal to the
+   * corresponding data members in this
+   * 
+   * @param t1
+   *        the vector with which the comparison is made.
+   */
+  @Override
+  public boolean equals(Object t1) {
+    if (!(t1 instanceof T3d))
+      return false;
+    T3d t2 = (T3d) t1;
+    return (this.x == t2.x && this.y == t2.y && this.z == t2.z);
+  }
+
+  /**
+   * Returns a string that contains the values of this Tuple3d. The form is
+   * (x,y,z).
+   * 
+   * @return the String representation
+   */
+  @Override
+  public String toString() {
+    return "{" + x + ", " + y + ", " + z + "}";
+  }
+
+}
diff --git a/src2/javajs/util/T3i.java b/src2/javajs/util/T3i.java
new file mode 100644 (file)
index 0000000..7fbd3bb
--- /dev/null
@@ -0,0 +1,151 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+import java.io.Serializable;
+
+/**
+ * A 3-element tuple represented by signed integer x,y,z coordinates.
+ * 
+ * @since Java 3D 1.2
+ * @version specification 1.2, implementation $Revision: 1.9 $, $Date:
+ *          2006/07/28 17:01:32 $
+ * @author Kenji hiranabe
+ * 
+ *         additions by Bob Hanson hansonr@stolaf.edu 9/30/2012 for unique
+ *         constructor and method names for the optimization of compiled
+ *         JavaScript using Java2Script
+ */
+public abstract class T3i implements Serializable {
+
+  /**
+   * The x coordinate.
+   */
+  public int x;
+
+  /**
+   * The y coordinate.
+   */
+  public int y;
+
+  /**
+   * The z coordinate.
+   */
+  public int z;
+
+  /**
+   * Constructs and initializes a Tuple3i to (0,0,0).
+   */
+  public T3i() {
+  }
+
+  /**
+   * Sets the value of this tuple to to the specified x, y, and z coordinates.
+   * 
+   * @param x
+   *        the x coordinate.
+   * @param y
+   *        the y coordinate.
+   * @param z
+   *        the z coordinate.
+   */
+  public final void set(int x, int y, int z) {
+    this.x = x;
+    this.y = y;
+    this.z = z;
+  }
+
+  /**
+   * Sets the value of this tuple to the value of tuple t1.
+   * 
+   * @param t1
+   *        the tuple to be copied.
+   */
+  public final void setT(T3i t1) {
+    x = t1.x;
+    y = t1.y;
+    z = t1.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the sum of itself and t1.
+   * 
+   * @param t
+   *        is the other tuple
+   */
+  public final void add(T3i t) {
+    x += t.x;
+    y += t.y;
+    z += t.z;
+  }
+
+  /**
+   * Sets the value of this tuple to the scalar multiplication of tuple t1 plus
+   * tuple t2 (this = s*t1 + t2).
+   * 
+   * @param s
+   *        the scalar value
+   * @param t1
+   *        the tuple to be multipled
+   * @param t2
+   *        the tuple to be added
+   */
+  public final void scaleAdd(int s, T3i t1, T3i t2) {
+    x = s * t1.x + t2.x;
+    y = s * t1.y + t2.y;
+    z = s * t1.z + t2.z;
+  }
+
+  /**
+   * Returns a hash number based on the data values in this object. Two
+   * different Tuple3i objects with identical data values (ie, returns true for
+   * equals(Tuple3i) ) will return the same hash number. Two vectors with
+   * different data members may return the same hash value, although this is not
+   * likely.
+   */
+  @Override
+  public int hashCode() {
+    return x ^ y ^ z;
+  }
+
+  /**
+   * Returns true if the Object o is of type Tuple3i and all of the data members
+   * of t are equal to the corresponding data members in this Tuple3i.
+   * 
+   * @param o
+   *        the object with which the comparison is made.
+   */
+  @Override
+  public boolean equals(Object o) {
+    if (!(o instanceof T3i))
+      return false;
+    T3i t = (T3i) o;
+    return (this.x == t.x && this.y == t.y && this.z == t.z);
+  }
+
+  /**
+   * Returns a string that contains the values of this Tuple3i. The form is
+   * (x,y,z).
+   * 
+   * @return the String representation
+   */
+  @Override
+  public String toString() {
+    return "(" + x + ", " + y + ", " + z + ")";
+  }
+
+}
diff --git a/src2/javajs/util/T4.java b/src2/javajs/util/T4.java
new file mode 100644 (file)
index 0000000..21b2741
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+/**
+ * A generic 4 element tuple that is represented by single precision floating
+ * point x,y,z and w coordinates.
+ * 
+ * @version specification 1.1, implementation $Revision: 1.9 $, $Date:
+ *          2006/07/28 17:01:32 $
+ * @author Kenji hiranabe
+ * 
+ * additions by Bob Hanson hansonr@stolaf.edu 9/30/2012
+ * for unique constructor and method names
+ * for the optimization of compiled JavaScript using Java2Script
+ */
+public abstract class T4 extends T3 {
+
+  /**
+   * The w coordinate.
+   */
+  public float w;
+
+  /**
+   * Constructs and initializes a Tuple4f to (0,0,0,0).
+   * 
+   */
+  public T4() {
+  }
+
+  /**
+   * Sets the value of this tuple to the specified xyzw coordinates.
+   * 
+   * @param x
+   *        the x coordinate
+   * @param y
+   *        the y coordinate
+   * @param z
+   *        the z coordinate
+   * @param w
+   *        the w coordinate
+   */
+  public final void set4(float x, float y, float z, float w) {
+    this.x = x;
+    this.y = y;
+    this.z = z;
+    this.w = w;
+  }
+
+  /**
+   * Sets the value of this tuple to the scalar multiplication of itself.
+   * 
+   * @param s
+   *        the scalar value
+   */
+  public final void scale4(float s) {
+    scale(s);
+    w *= s;
+  }
+
+  /**
+   * Returns a hash number based on the data values in this object. Two
+   * different Tuple4f objects with identical data values (ie, returns true for
+   * equals(Tuple4f) ) will return the same hash number. Two vectors with
+   * different data members may return the same hash value, although this is not
+   * likely.
+   */
+  @Override
+  public int hashCode() {
+    return T3.floatToIntBits(x) ^ T3.floatToIntBits(y)
+        ^ T3.floatToIntBits(z) ^ T3.floatToIntBits(w);
+  }
+
+  /**
+   * Returns true if all of the data members of Object are equal to the
+   * corresponding data members in this
+   * 
+   * @param o
+   *        the vector with which the comparison is made.
+   */
+  @Override
+  public boolean equals(Object o) {
+    if (!(o instanceof T4))
+      return false;
+    T4 t = (T4) o;
+    return (this.x == t.x && this.y == t.y && this.z == t.z && this.w == t.w);
+  }
+
+  /**
+   * Returns a string that contains the values of this Tuple4f. The form is
+   * (x,y,z,w).
+   * 
+   * @return the String representation
+   */
+  @Override
+  public String toString() {
+    return "(" + x + ", " + y + ", " + z + ", " + w + ")";
+  }
+
+  @Override
+  public String toJSON() {
+    return "[" + x + ", " + y + ", " + z + ", " + w + "]";
+  }
+
+}
diff --git a/src2/javajs/util/V3.java b/src2/javajs/util/V3.java
new file mode 100644 (file)
index 0000000..51325d2
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ Copyright (C) 1997,1998,1999
+ Kenji Hiranabe, Eiwa System Management, Inc.
+
+ This program is free software.
+ Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+ conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+ 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. Kenji Hiranabe and Eiwa System Management,Inc.
+ makes no representations about the suitability of this software for any
+ purpose.  It is provided "AS IS" with NO WARRANTY.
+ */
+package javajs.util;
+
+
+/**
+ * A 3-element vector that is represented by single precision floating point
+ * x,y,z coordinates. If this value represents a normal, then it should be
+ * normalized.
+ * 
+ * @version specification 1.1, implementation $Revision: 1.10 $, $Date:
+ *          2006/10/03 19:52:30 $
+ * @author Kenji hiranabe
+ * 
+ * additions by Bob Hanson hansonr@stolaf.edu 9/30/2012
+ * for unique constructor and method names
+ * for the optimization of compiled JavaScript using Java2Script
+ */
+public class V3 extends T3 {
+
+  public V3() {
+  }
+  
+  public static V3 newV(T3 t) {
+    return V3.new3(t.x, t.y, t.z);
+  }
+
+  public static V3 newVsub(T3 t1, T3 t2) {
+    return V3.new3(t1.x - t2.x, t1.y - t2.y,t1.z - t2.z);
+  }
+
+  public static V3 new3(float x, float y, float z) {
+    V3 v = new V3();
+    v.x = x;
+    v.y = y;
+    v.z = z;
+    return v;
+  }
+
+  /**
+   * Returns the angle in radians between this vector and the vector parameter;
+   * the return value is constrained to the range [0,PI].
+   * 
+   * @param v1
+   *        the other vector
+   * @return the angle in radians in the range [0,PI]
+   */
+  public final float angle(V3 v1) {
+    // return (double)Math.acos(dot(v1)/v1.length()/v.length());
+    // Numerically, near 0 and PI are very bad condition for acos.
+    // In 3-space, |atan2(sin,cos)| is much stable.
+
+    double xx = y * v1.z - z * v1.y;
+    double yy = z * v1.x - x * v1.z;
+    double zz = x * v1.y - y * v1.x;
+    double cross = Math.sqrt(xx * xx + yy * yy + zz * zz);
+
+    return (float) Math.abs(Math.atan2(cross, dot(v1)));
+  }
+}
diff --git a/src2/javajs/util/V3d.java b/src2/javajs/util/V3d.java
new file mode 100644 (file)
index 0000000..9060575
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+   Copyright (C) 1997,1998,1999
+   Kenji Hiranabe, Eiwa System Management, Inc.
+
+   This program is free software.
+   Implemented by Kenji Hiranabe(hiranabe@esm.co.jp),
+   conforming to the Java(TM) 3D API specification by Sun Microsystems.
+
+   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. Kenji Hiranabe and Eiwa System Management,Inc.
+   makes no representations about the suitability of this software for any
+   purpose.  It is provided "AS IS" with NO WARRANTY.
+*/
+package javajs.util;
+
+
+
+
+/**
+ * A 3 element vector that is represented by double precision floating point
+ * x,y,z coordinates. If this value represents a normal, then it should be
+ * normalized.
+ * 
+ * @version specification 1.1, implementation $Revision: 1.9 $, $Date:
+ *          2006/07/28 17:01:32 $
+ * @author Kenji hiranabe
+ * 
+ * additions by Bob Hanson hansonr@stolaf.edu 9/30/2012
+ * for unique constructor and method names
+ * for the optimization of compiled JavaScript using Java2Script
+ */
+public class V3d extends T3d {
+
+  /**
+   * Sets this vector to be the vector cross product of vectors v1 and v2.
+   * 
+   * @param v1
+   *        the first vector
+   * @param v2
+   *        the second vector
+   */
+  public final void cross(V3d v1, V3d v2) {
+    // store on stack once for aliasing-safty
+    // i.e. safe when a.cross(a, b)
+    set(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y
+        - v1.y * v2.x);
+  }
+
+  /**
+   * Normalizes this vector in place.
+   */
+  public final void normalize() {
+    double d = length();
+
+    // zero-div may occur.
+    x /= d;
+    y /= d;
+    z /= d;
+  }
+
+  /**
+   * Computes the dot product of the this vector and vector v.
+   * 
+   * @param v
+   *        the other vector
+   * @return this.dot.v
+   */
+  public final double dot(V3d v) {
+    return x * v.x + y * v.y + z * v.z;
+  }
+
+  /**
+   * Returns the squared length of this vector.
+   * 
+   * @return the squared length of this vector
+   */
+  public final double lengthSquared() {
+    return x * x + y * y + z * z;
+  }
+
+  /**
+   * Returns the length of this vector.
+   * 
+   * @return the length of this vector
+   */
+  public final double length() {
+    return Math.sqrt(lengthSquared());
+  }
+
+}
diff --git a/src2/javajs/util/XmlUtil.java b/src2/javajs/util/XmlUtil.java
new file mode 100644 (file)
index 0000000..3e30e4b
--- /dev/null
@@ -0,0 +1,171 @@
+/* $RCSfile$
+ * $Author$
+ * $Date$
+ * $Revision$
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2006  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301, USA.
+ */
+
+package javajs.util;
+
+/**
+ * A very simplistic XML generator
+ */
+
+public class XmlUtil {
+
+  public XmlUtil() {
+    // Jmol's PropertyManager and JvxlCoder classes use reflection 
+  }
+  public static void openDocument(SB data) {
+    data.append("<?xml version=\"1.0\"?>\n");
+  }
+
+  public static void openTag(SB sb, String name) {
+    sb.append("<").append(name).append(">\n");
+  }
+
+  public static void openTagAttr(SB sb, String name, Object[] attributes) {
+    appendTagAll(sb, name, attributes, null, false, false);
+    sb.append("\n");
+  }
+
+  public static void closeTag(SB sb, String name) {
+    sb.append("</").append(name).append(">\n");
+  }
+
+  public static void appendTagAll(SB sb, String name,
+                               Object[] attributes, Object data,
+                               boolean isCdata, boolean doClose) {
+    String closer = ">";
+    if (name.endsWith("/")){
+      name = name.substring(0, name.length() - 1);
+      if (data == null) {
+        closer = "/>\n";
+        doClose = false;
+      }
+    }
+    sb.append("<").append(name);
+    if (attributes != null)
+      for (int i = 0; i < attributes.length; i++) {
+        Object o = attributes[i];
+        if (o == null)
+          continue;
+        if (o instanceof Object[])
+          for (int j = 0; j < ((Object[]) o).length; j+= 2)
+          appendAttrib(sb, ((Object[]) o)[j], ((Object[]) o)[j + 1]);
+        else
+          appendAttrib(sb, o, attributes[++i]);
+      }
+    sb.append(closer);
+    if (data != null) {
+      if (isCdata)
+        data = wrapCdata(data);
+      sb.appendO(data);
+    }
+    if (doClose)
+      closeTag(sb, name);
+  }
+
+  /**
+   * wrap the string as character data, with replacements for [ noted 
+   * as a list starting with * after the CDATA termination
+   * 
+   * @param data
+   * @return      wrapped text
+   */
+  public static String wrapCdata(Object data) {
+    String s = "" + data;
+    return (s.indexOf("&") < 0 && s.indexOf("<") < 0 ? (s.startsWith("\n") ? "" : "\n") + s 
+        : "<![CDATA[" + PT.rep(s, "]]>", "]]]]><![CDATA[>") + "]]>");
+  }
+  
+  /**
+   * standard <name attr="..." attr="...">data</name>"
+   * 
+   * @param sb
+   * @param name
+   * @param attributes
+   * @param data
+   */
+  public static void appendTagObj(SB sb, String name,
+                               Object[] attributes, Object data) {
+    appendTagAll(sb, name, attributes, data, false, true);
+  }
+
+  /**
+   * standard <name>data</name>"
+   * standard <name attr="..." attr="..."></name>"
+   * 
+   * @param sb
+   * @param name
+   * @param data
+   */
+  public static void appendTag(SB sb, String name, Object data) {
+    if (data instanceof Object[])
+      appendTagAll(sb, name, (Object[]) data, null, false, true);
+    else
+      appendTagAll(sb, name, null, data, false, true);
+  }
+
+  /**
+   * <name><![CDATA[data]]></name>"
+   * 
+   * will convert ]]> to ]] >
+   * 
+   * @param sb
+   * @param name
+   * @param attributes 
+   * @param data
+   */
+  public static void appendCdata(SB sb, String name, 
+                                 Object[] attributes, String data) {
+    appendTagAll(sb, name, attributes, data, true, true);
+  }
+
+  /**
+   * 
+   * @param sb
+   * @param name
+   * @param value
+   */
+  public static void appendAttrib(SB sb, Object name, Object value) {
+    if (value == null)
+      return;
+    
+    // note: <&" are disallowed but not checked for here
+    
+    sb.append(" ").appendO(name).append("=\"").appendO(value).append("\"");
+  }
+
+//  /**
+//   * @param s
+//   * @return   unwrapped text
+//   */
+//  public static String unwrapCdata(String s) {
+//    return (s.startsWith("<![CDATA[") && s.endsWith("]]>") ?
+//        PT.rep(s.substring(9, s.length()-3),"]]]]><![CDATA[>", "]]>") : s);
+//  }
+//  
+
+}
diff --git a/src2/javajs/util/ZipData.java b/src2/javajs/util/ZipData.java
new file mode 100644 (file)
index 0000000..f20715f
--- /dev/null
@@ -0,0 +1,76 @@
+/* $RCSfile$
+ * $Author$
+ * $Date$
+ * $Revision$
+ *
+ * Copyright (C) 2006  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301, USA.
+ */
+
+package javajs.util;
+
+import java.io.BufferedInputStream;
+
+import javajs.api.GenericZipTools;
+
+
+
+
+public class ZipData {
+  boolean isEnabled = true;
+  byte[] buf;
+  int pt;
+  int nBytes;
+  
+  public ZipData(int nBytes) {
+    this.nBytes = nBytes;
+  }
+  
+  public int addBytes(byte[] byteBuf, int nSectorBytes, int nBytesRemaining) {
+    if (pt == 0) {
+      if (!Rdr.isGzipB(byteBuf)) {
+        isEnabled = false;
+        return -1;
+      }
+      buf = new byte[nBytesRemaining];
+    }
+    int nToAdd = Math.min(nSectorBytes, nBytesRemaining);
+    System.arraycopy(byteBuf, 0, buf, pt, nToAdd);
+    pt += nToAdd;
+    return nBytesRemaining - nToAdd;
+  }    
+
+  public void addTo(GenericZipTools jzt, SB data) {
+    data.append(getGzippedBytesAsString(jzt, buf));
+  }
+
+  static String getGzippedBytesAsString(GenericZipTools jzt, byte[] bytes) {
+    try {
+      BufferedInputStream bis = jzt.getUnGzippedInputStream(bytes);
+      String s = ZipTools.getStreamAsString(bis);
+      bis.close();
+      return s;
+    } catch (Exception e) {
+      return "";
+    }
+  }
+
+}
+
diff --git a/src2/javajs/util/ZipTools.java b/src2/javajs/util/ZipTools.java
new file mode 100644 (file)
index 0000000..a4082ec
--- /dev/null
@@ -0,0 +1,462 @@
+/* $RCSfile$
+ * $Author$
+ * $Date$
+ * $Revision$
+ *
+ * Some portions of this file have been modified by Robert Hanson hansonr.at.stolaf.edu 2012-2017
+ * for use in SwingJS via transpilation into JavaScript using Java2Script.
+ *
+ * Copyright (C) 2006  The Jmol Development Team
+ *
+ * Contact: jmol-developers@lists.sf.net
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2.1 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ *  02110-1301, USA.
+ */
+
+package javajs.util;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Map;
+import java.util.zip.CRC32;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import javajs.api.GenericZipInputStream;
+import javajs.api.GenericZipTools;
+import javajs.api.Interface;
+import javajs.api.ZInputStream;
+
+import org.apache.tools.bzip2.CBZip2InputStreamFactory;
+
+
+/**
+ * Note the JSmol/HTML5 must use its own version of java.util.zip.ZipOutputStream.
+ * 
+ */
+public class ZipTools implements GenericZipTools {
+
+  public ZipTools() {
+    // for reflection
+  }
+  
+  @Override
+  public ZInputStream newZipInputStream(InputStream is) {
+    return newZIS(is);
+  }
+
+  @SuppressWarnings("resource")
+  private static ZInputStream newZIS(InputStream is) {
+    return (is instanceof ZInputStream ? (ZInputStream) is
+        : is instanceof BufferedInputStream ? new GenericZipInputStream(is)
+            : new GenericZipInputStream(new BufferedInputStream(is)));
+  }
+
+  /**
+   * reads a ZIP file and saves all data in a Hashtable so that the files may be
+   * organized later in a different order. Also adds a #Directory_Listing entry.
+   * 
+   * Files are bracketed by BEGIN Directory Entry and END Directory Entry lines,
+   * similar to CompoundDocument.getAllData.
+   * 
+   * @param is
+   * @param subfileList
+   * @param name0
+   *        prefix for entry listing
+   * @param binaryFileList
+   *        |-separated list of files that should be saved as xx xx xx hex byte
+   *        strings. The directory listing is appended with ":asBinaryString"
+   * @param fileData
+   */
+  @Override
+  public void getAllZipData(InputStream is, String[] subfileList,
+                                          String name0, String binaryFileList, String exclude,
+                                          Map<String, String> fileData) {
+    ZipInputStream zis = (ZipInputStream) newZIS(is);
+    ZipEntry ze;
+    SB listing = new SB();
+    binaryFileList = "|" + binaryFileList + "|";
+    String prefix = PT.join(subfileList, '/', 1);
+    String prefixd = null;
+    if (prefix != null) {
+      prefixd = prefix.substring(0, prefix.indexOf("/") + 1);
+      if (prefixd.length() == 0)
+        prefixd = null;
+    }
+    try {
+      while ((ze = zis.getNextEntry()) != null) {
+        String name = ze.getName();
+        if (prefix != null && prefixd != null
+            && !(name.equals(prefix) || name.startsWith(prefixd))
+            || exclude != null && name.contains(exclude))
+          continue;
+        //System.out.println("ziputil: " + name);
+        listing.append(name).appendC('\n');
+        String sname = "|" + name.substring(name.lastIndexOf("/") + 1) + "|";
+        boolean asBinaryString = (binaryFileList.indexOf(sname) >= 0);
+        byte[] bytes = Rdr.getLimitedStreamBytes(zis, ze.getSize());
+        String str;
+        if (asBinaryString) {
+          str = getBinaryStringForBytes(bytes);
+          name += ":asBinaryString";
+        } else {
+          str = Rdr.fixUTF(bytes);
+        }
+        str = "BEGIN Directory Entry " + name + "\n" + str
+            + "\nEND Directory Entry " + name + "\n";
+        String key = name0 + "|" + name;
+        fileData.put(key, str);
+      }
+    } catch (Exception e) {
+    }
+    fileData.put("#Directory_Listing", listing.toString());
+  }
+
+  private String getBinaryStringForBytes(byte[] bytes) {
+    SB ret = new SB();
+    for (int i = 0; i < bytes.length; i++)
+      ret.append(Integer.toHexString(bytes[i] & 0xFF)).appendC(' ');
+    return ret.toString();
+  }
+
+  /**
+   * iteratively drills into zip files of zip files to extract file content or
+   * zip file directory. Also works with JAR files.
+   * 
+   * Does not return "__MACOS" paths
+   * 
+   * @param bis
+   * @param list
+   * @param listPtr
+   * @param asBufferedInputStream
+   *        for Pmesh
+   * @return directory listing or subfile contents
+   */
+  @Override
+  public Object getZipFileDirectory(BufferedInputStream bis, String[] list,
+                                    int listPtr, boolean asBufferedInputStream) {
+    SB ret;
+    if (list == null || listPtr >= list.length)
+      return getZipDirectoryAsStringAndClose(bis);
+    bis = Rdr.getPngZipStream(bis, true);
+    String fileName = list[listPtr];
+    ZipInputStream zis = new ZipInputStream(bis);
+    ZipEntry ze;
+    //System.out.println("fname=" + fileName);
+    try {
+      boolean isAll = (fileName.equals("."));
+      if (isAll || fileName.lastIndexOf("/") == fileName.length() - 1) {
+        ret = new SB();
+        while ((ze = zis.getNextEntry()) != null) {
+          String name = ze.getName();
+          if (isAll || name.startsWith(fileName))
+            ret.append(name).appendC('\n');
+        }
+        String str = ret.toString();
+        return (asBufferedInputStream ? Rdr.getBIS(str.getBytes()) : str);
+      }
+      int pt = fileName.indexOf(":asBinaryString");
+      boolean asBinaryString = (pt > 0);
+      if (asBinaryString)
+        fileName = fileName.substring(0, pt);
+      fileName = fileName.replace('\\', '/');
+      while ((ze = zis.getNextEntry()) != null
+          && !fileName.equals(ze.getName())) {
+      }
+      byte[] bytes = (ze == null ? null : Rdr.getLimitedStreamBytes(zis,
+          ze.getSize()));
+      ze = null;
+      zis.close();
+      if (bytes == null)
+        return "";
+      if (Rdr.isZipB(bytes) || Rdr.isPngZipB(bytes))
+        return getZipFileDirectory(Rdr.getBIS(bytes), list, ++listPtr,
+            asBufferedInputStream);
+      if (asBufferedInputStream)
+        return Rdr.getBIS(bytes);
+      if (asBinaryString) {
+        ret = new SB();
+        for (int i = 0; i < bytes.length; i++)
+          ret.append(Integer.toHexString(bytes[i] & 0xFF)).appendC(' ');
+        return ret.toString();
+      }
+      if (Rdr.isGzipB(bytes))
+        bytes = Rdr.getLimitedStreamBytes(getUnGzippedInputStream(bytes), -1);
+      return Rdr.fixUTF(bytes);
+    } catch (Exception e) {
+      return "";
+    }
+  }
+
+  @Override
+  public byte[] getZipFileContentsAsBytes(BufferedInputStream bis,
+                                          String[] list, int listPtr) {
+    byte[] ret = new byte[0];
+    String fileName = list[listPtr];
+    if (fileName.lastIndexOf("/") == fileName.length() - 1)
+      return ret;
+    try {
+      bis = Rdr.getPngZipStream(bis, true);
+      ZipInputStream zis = new ZipInputStream(bis);
+      ZipEntry ze;
+      while ((ze = zis.getNextEntry()) != null) {
+        if (!fileName.equals(ze.getName()))
+          continue;
+        byte[] bytes = Rdr.getLimitedStreamBytes(zis, ze.getSize());
+        return ((Rdr.isZipB(bytes) || Rdr.isPngZipB(bytes)) && ++listPtr < list.length ? getZipFileContentsAsBytes(
+            Rdr.getBIS(bytes), list, listPtr) : bytes);
+      }
+    } catch (Exception e) {
+    }
+    return ret;
+  }
+  
+  @Override
+  public String getZipDirectoryAsStringAndClose(BufferedInputStream bis) {
+    SB sb = new SB();
+    String[] s = new String[0];
+    try {
+      s = getZipDirectoryOrErrorAndClose(bis, null);
+      bis.close();
+    } catch (Exception e) {
+      System.out.println(e.toString());
+    }
+    for (int i = 0; i < s.length; i++)
+      sb.append(s[i]).appendC('\n');
+    return sb.toString();
+  }
+
+  @Override
+  public String[] getZipDirectoryAndClose(BufferedInputStream bis,
+                                                 String manifestID) {
+    String[] s = new String[0];
+    try {
+      s = getZipDirectoryOrErrorAndClose(bis, manifestID);
+      bis.close();
+    } catch (Exception e) {
+      System.out.println(e.toString());
+    }
+    return s;
+  }
+
+  private String[] getZipDirectoryOrErrorAndClose(BufferedInputStream bis,
+                                                  String manifestID)
+      throws IOException {
+    bis = Rdr.getPngZipStream(bis, true);
+    Lst<String> v = new Lst<String>();
+    ZipInputStream zis = new ZipInputStream(bis);
+    ZipEntry ze;
+    String manifest = null;
+    while ((ze = zis.getNextEntry()) != null) {
+      String fileName = ze.getName();
+      if (manifestID != null && fileName.startsWith(manifestID))
+        manifest = getStreamAsString(zis);
+      else if (!fileName.startsWith("__MACOS")) // resource fork not nec.
+        v.addLast(fileName);
+    }
+    zis.close();
+    if (manifestID != null)
+      v.add(0, manifest == null ? "" : manifest + "\n############\n");
+    return v.toArray(new String[v.size()]);
+  }
+
+  public static String getStreamAsString(InputStream is) throws IOException {
+    return Rdr.fixUTF(Rdr.getLimitedStreamBytes(is, -1));
+  }
+
+  @Override
+  public InputStream newGZIPInputStream(InputStream is) throws IOException {
+    return new BufferedInputStream(new GZIPInputStream(is, 512));
+  }
+
+  @Override
+  public InputStream newBZip2InputStream(InputStream is) throws IOException {
+    return new BufferedInputStream(((CBZip2InputStreamFactory) Interface.getInterface("org.apache.tools.bzip2.CBZip2InputStreamFactory")).getStream(is));
+  }
+
+  @Override
+  public BufferedInputStream getUnGzippedInputStream(byte[] bytes) {
+    try {
+      return Rdr.getUnzippedInputStream(this, Rdr.getBIS(bytes));
+    } catch (Exception e) {
+      return null;
+    }
+  }
+
+  @Override
+  public void addZipEntry(Object zos, String fileName) throws IOException {
+    ((ZipOutputStream) zos).putNextEntry(new ZipEntry(fileName));
+  }
+
+  @Override
+  public void closeZipEntry(Object zos) throws IOException {
+    ((ZipOutputStream) zos).closeEntry();
+  }
+
+  @Override
+  public Object getZipOutputStream(Object bos) {
+//    /**
+//     * @j2sNative
+//     * 
+//     *            return javajs.api.Interface.getInterface(
+//     *            "java.util.zip.ZipOutputStream").setZOS(bos);
+//     * 
+//     */
+//    {
+      return new ZipOutputStream((OutputStream) bos);
+//    }
+  }
+
+  @Override
+  public int getCrcValue(byte[] bytes) {
+    CRC32 crc = new CRC32();
+    crc.update(bytes, 0, bytes.length);
+    return (int) crc.getValue();
+  }
+
+  @Override
+  public void readFileAsMap(BufferedInputStream bis, Map<String, Object> bdata, String name) {
+       readFileAsMapStatic(bis, bdata, name);
+  }
+
+  public static void readFileAsMapStatic(BufferedInputStream bis,
+                       Map<String, Object> bdata, String name) {
+    int pt = (name == null ? -1 : name.indexOf("|"));
+    name = (pt >= 0 ? name.substring(pt + 1) : null);
+    try {
+      if (Rdr.isPngZipStream(bis)) {
+        boolean isImage = "_IMAGE_".equals(name);
+        if (name == null || isImage)
+          bdata.put((isImage ? "_DATA_" : "_IMAGE_"), new BArray(getPngImageBytes(bis)));
+        if (!isImage)
+          cacheZipContentsStatic(bis, name, bdata, true);
+      } else if (Rdr.isZipS(bis)) {
+        cacheZipContentsStatic(bis, name, bdata, true);
+      } else if (name == null){
+        bdata.put("_DATA_", new BArray(Rdr.getLimitedStreamBytes(bis, -1)));
+      } else {
+        throw new IOException("ZIP file " + name + " not found");
+      }
+      bdata.put("$_BINARY_$", Boolean.TRUE);
+    } catch (IOException e) {
+      bdata.clear();
+      bdata.put("_ERROR_", e.getMessage());
+    }
+  }
+
+  @Override
+  public String cacheZipContents(BufferedInputStream bis,
+                                        String fileName,
+                                        Map<String, Object> cache, 
+                                        boolean asByteArray) {
+               return cacheZipContentsStatic(bis, fileName, cache, asByteArray);
+  }
+
+       /**
+        * 
+        * @param bis
+        * @param fileName may end with "/" for a prefix or contain "|xxxx.xxx" for a specific file or be null
+        * @param cache
+        * @param asByteArray
+        * @return
+        */
+  public static String cacheZipContentsStatic(BufferedInputStream bis,
+                       String fileName, Map<String, Object> cache, boolean asByteArray) {
+    ZipInputStream zis = (ZipInputStream) newZIS(bis);
+    ZipEntry ze;
+    SB listing = new SB();
+    long n = 0;
+    boolean isPath = (fileName != null && fileName.endsWith("/"));
+    boolean oneFile = (asByteArray && !isPath && fileName != null);
+    int pt = (oneFile ? fileName.indexOf("|") : -1);
+    String file0 = (pt >= 0 ? fileName : null);
+    if (pt >= 0)
+      fileName = fileName.substring(0,  pt);
+    String prefix = (fileName == null ? "" : isPath ? fileName : fileName + "|");
+    try {
+      while ((ze = zis.getNextEntry()) != null) {
+        String name = ze.getName();
+        if (fileName != null) {
+          if (oneFile) {
+            if (!name.equalsIgnoreCase(fileName))
+              continue;
+          } else {
+            listing.append(name).appendC('\n');
+          }
+        }
+        long nBytes = ze.getSize();
+        byte[] bytes = Rdr.getLimitedStreamBytes(zis, nBytes);
+        if (file0 != null) {
+          readFileAsMapStatic(Rdr.getBIS(bytes), cache, file0);
+          return null;
+        }
+        n += bytes.length;
+        Object o = (asByteArray ? new BArray(bytes) : bytes);        
+        cache.put((oneFile ? "_DATA_" : prefix + name), o);
+        if (oneFile)
+          break;
+      }
+      zis.close();
+    } catch (Exception e) {
+      try {
+        zis.close();
+      } catch (IOException e1) {
+      }
+      return null;
+    }
+    if (n == 0 || fileName == null)
+      return null;
+    System.out.println("ZipTools cached " + n + " bytes from " + fileName);
+    return listing.toString();
+  }
+
+  private static byte[] getPngImageBytes(BufferedInputStream bis) {
+    try {
+      if (Rdr.isPngZipStream(bis)) {
+        int pt_count[] = new int[2];
+        Rdr.getPngZipPointAndCount(bis, pt_count);
+        if (pt_count[1] != 0)
+          return deActivatePngZipB(Rdr.getLimitedStreamBytes(bis, pt_count[0]));
+      }
+      return Rdr.getLimitedStreamBytes(bis, -1);
+    } catch (IOException e) {
+      return null;
+    }
+  }
+
+  /**
+   * Once a PNGJ image has been extracted, we want to red-line its
+   * iTXt "Jmol Type PNGJ" tag, since it is no longer associated with
+   * ZIP data.
+   *  
+   * @param bytes
+   * @return disfigured bytes
+   * 
+   */
+  private static byte[] deActivatePngZipB(byte[] bytes) {
+    // \0PNGJ starting at byte 50 changed to \0 NGJ
+    if (Rdr.isPngZipB(bytes))
+      bytes[51] = 32;
+    return bytes;
+  }
+
+
+
+}
similarity index 96%
rename from src/net/miginfocom/layout/AC.java
rename to src2/net/miginfocom/layout/AC.java
index 231b333..2d1032c 100644 (file)
@@ -1,10 +1,6 @@
 package net.miginfocom.layout;
 
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.io.ObjectStreamException;
+import java.io.*;
 import java.util.ArrayList;
 
 /*
@@ -50,7 +46,7 @@ import java.util.ArrayList;
  * Note that there are two way to build this constraint. Through String (e.g. <code>"[100]3[200,fill]"</code> or through API (E.g.
  * <code>new AC().size("100").gap("3").size("200").fill()</code>.
  */
-public final class AC //implements Externalizable
+public final class AC implements Externalizable
 {
        private final ArrayList<DimConstraint> cList = new ArrayList<DimConstraint>(1);
 
@@ -547,25 +543,25 @@ public final class AC //implements Externalizable
                }
        }
 
-//     // ************************************************
-//     // Persistence Delegate and Serializable combined.
-//     // ************************************************
-//
-//     private Object readResolve() throws ObjectStreamException
-//     {
-//             return LayoutUtil.getSerializedObject(this);
-//     }
-//
-//     @Override
-//     public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
-//     {
-//             LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
-//     }
-//
-//     @Override
-//     public void writeExternal(ObjectOutput out) throws IOException
-//     {
-//             if (getClass() == AC.class)
-//                     LayoutUtil.writeAsXML(out, this);
-//     }
+       // ************************************************
+       // Persistence Delegate and Serializable combined.
+       // ************************************************
+
+       private Object readResolve() throws ObjectStreamException
+       {
+               return LayoutUtil.getSerializedObject(this);
+       }
+
+       @Override
+       public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
+       {
+               LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
+       }
+
+       @Override
+       public void writeExternal(ObjectOutput out) throws IOException
+       {
+               if (getClass() == AC.class)
+                       LayoutUtil.writeAsXML(out, this);
+       }
 }
\ No newline at end of file
diff --git a/src2/net/miginfocom/layout/BoundSize.java b/src2/net/miginfocom/layout/BoundSize.java
new file mode 100644 (file)
index 0000000..5bc0948
--- /dev/null
@@ -0,0 +1,293 @@
+package net.miginfocom.layout;
+
+import java.beans.Encoder;
+import java.beans.Expression;
+import java.beans.PersistenceDelegate;
+/*
+ * License (BSD):
+ * ==============
+ *
+ * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (miglayout (at) miginfocom (dot) com)
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright notice, this list
+ * of conditions and the following disclaimer.
+ * 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.
+ * Neither the name of the MiG InfoCom AB nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without specific
+ * prior written permission.
+ *
+ * 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 OWNER 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.
+ *
+ * @version 1.0
+ * @author Mikael Grev, MiG InfoCom AB
+ *         Date: 2006-sep-08
+ */
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+
+/** A size that contains minimum, preferred and maximum size of type {@link UnitValue}.
+ * <p>
+ * This class is a simple value container and it is immutable.
+ * <p>
+ * If a size is missing (i.e., <code>null</code>) that boundary should be considered "not in use".
+ * <p>
+ * You can create a BoundSize from a String with the use of {@link ConstraintParser#parseBoundSize(String, boolean, boolean)}
+ */
+public class BoundSize implements Serializable
+{
+       public static final BoundSize NULL_SIZE = new BoundSize(null, null);
+       public static final BoundSize ZERO_PIXEL = new BoundSize(UnitValue.ZERO, "0px");
+
+       private final transient UnitValue min;
+       private final transient UnitValue pref;
+       private final transient UnitValue max;
+       private final transient boolean gapPush;
+
+       /** Constructor that use the same value for min/preferred/max size.
+        * @param minMaxPref The value to use for min/preferred/max size.
+        * @param createString The string used to create the BoundsSize.
+        */
+       public BoundSize(UnitValue minMaxPref, String createString)
+       {
+               this(minMaxPref, minMaxPref, minMaxPref, createString);
+       }
+
+       /** Constructor. <b>This method is here for serialization only and should normally not be used.</b> Use
+        * {@link ConstraintParser#parseBoundSize(String, boolean, boolean)} instead.
+        * @param min The minimum size. May be <code>null</code>.
+        * @param preferred  The preferred size. May be <code>null</code>.
+        * @param max  The maximum size. May be <code>null</code>.
+        * @param createString The string used to create the BoundsSize.
+        */
+       public BoundSize(UnitValue min, UnitValue preferred, UnitValue max, String createString)    // Bound to old delegate!!!!!
+       {
+               this(min, preferred, max, false, createString);
+       }
+
+       /** Constructor. <b>This method is here for serialization only and should normally not be used.</b> Use
+        * {@link ConstraintParser#parseBoundSize(String, boolean, boolean)} instead.
+        * @param min The minimum size. May be <code>null</code>.
+        * @param preferred  The preferred size. May be <code>null</code>.
+        * @param max  The maximum size. May be <code>null</code>.
+        * @param gapPush If the size should be hinted as "pushing" and thus want to occupy free space if no one else is claiming it.
+        * @param createString The string used to create the BoundsSize.
+        */
+       public BoundSize(UnitValue min, UnitValue preferred, UnitValue max, boolean gapPush, String createString)
+       {
+               this.min = min;
+               this.pref = preferred;
+               this.max = max;
+               this.gapPush = gapPush;
+
+               LayoutUtil.putCCString(this, createString);    // this escapes!!
+       }
+
+       /** Returns the minimum size as sent into the constructor.
+        * @return The minimum size as sent into the constructor. May be <code>null</code>.
+        */
+       public final UnitValue getMin()
+       {
+               return min;
+       }
+
+       /** Returns the preferred size as sent into the constructor.
+        * @return The preferred size as sent into the constructor. May be <code>null</code>.
+        */
+       public final UnitValue getPreferred()
+       {
+               return pref;
+       }
+
+       /** Returns the maximum size as sent into the constructor.
+        * @return The maximum size as sent into the constructor. May be <code>null</code>.
+        */
+       public final UnitValue getMax()
+       {
+               return max;
+       }
+
+       /** If the size should be hinted as "pushing" and thus want to occupy free space if no one else is claiming it.
+        * @return The value.
+        */
+       public boolean getGapPush()
+       {
+               return gapPush;
+       }
+
+       /** Returns if this bound size has no min, preferred and maximum size set (they are all <code>null</code>)
+        * @return If unset.
+        */
+       public boolean isUnset()
+       {
+               // Most common case by far is this == ZERO_PIXEL...
+               return this == ZERO_PIXEL || (pref == null && min == null && max == null && gapPush == false);
+       }
+
+       /** Makes sure that <code>size</code> is within min and max of this size.
+        * @param size The size to constrain.
+        * @param refValue The reference to use for relative sizes.
+        * @param parent The parent container.
+        * @return The size, constrained within min and max.
+        */
+       public int constrain(int size, float refValue, ContainerWrapper parent)
+       {
+               if (max != null)
+                       size = Math.min(size, max.getPixels(refValue, parent, parent));
+               if (min != null)
+                       size = Math.max(size, min.getPixels(refValue, parent, parent));
+               return size;
+       }
+
+       /** Returns the minimum, preferred or maximum size for this bounded size.
+        * @param sizeType The type. <code>LayoutUtil.MIN</code>, <code>LayoutUtil.PREF</code> or <code>LayoutUtil.MAX</code>.
+        * @return
+        */
+       final UnitValue getSize(int sizeType)
+       {
+               switch(sizeType) {
+                       case LayoutUtil.MIN:
+                               return min;
+                       case LayoutUtil.PREF:
+                               return pref;
+                       case LayoutUtil.MAX:
+                               return max;
+                       default:
+                               throw new IllegalArgumentException("Unknown size: " + sizeType);
+               }
+       }
+
+       /** Convert the bound sizes to pixels.
+        * <p>
+        * <code>null</code> bound sizes will be 0 for min and preferred and {@link net.miginfocom.layout.LayoutUtil#INF} for max.
+        * @param refSize The reference size.
+        * @param parent The parent. Not <code>null</code>.
+        * @param comp The component, if applicable, can be <code>null</code>.
+        * @return An array of length three (min,pref,max).
+        */
+       final int[] getPixelSizes(float refSize, ContainerWrapper parent, ComponentWrapper comp)
+       {
+               return new int[] {
+                               min != null ? min.getPixels(refSize, parent, comp) : 0,
+                               pref != null ? pref.getPixels(refSize, parent, comp) : 0,
+                               max != null ? max.getPixels(refSize, parent, comp) : LayoutUtil.INF
+               };
+       }
+
+       /** Returns the a constraint string that can be re-parsed to be the exact same UnitValue.
+        * @return A String. Never <code>null</code>.
+        */
+       String getConstraintString()
+       {
+               String cs = LayoutUtil.getCCString(this);
+               if (cs != null)
+                       return cs;
+
+               if (min == pref && pref == max)
+                       return min != null ? (min.getConstraintString() + "!") : "null";
+
+               StringBuilder sb = new StringBuilder(16);
+
+               if (min != null)
+                       sb.append(min.getConstraintString()).append(':');
+
+               if (pref != null) {
+                       if (min == null && max != null)
+                               sb.append(":");
+                       sb.append(pref.getConstraintString());
+               } else if (min != null) {
+                       sb.append('n');
+               }
+
+               if (max != null)
+                       sb.append(sb.length() == 0 ? "::" : ":").append(max.getConstraintString());
+
+               if (gapPush) {
+                       if (sb.length() > 0)
+                               sb.append(':');
+                       sb.append("push");
+               }
+
+               return sb.toString();
+       }
+
+       void checkNotLinked()
+       {
+               if (isLinked())
+                       throw new IllegalArgumentException("Size may not contain links");
+       }
+
+       boolean isLinked()
+       {
+               return min != null && min.isLinkedDeep() || pref != null && pref.isLinkedDeep() || max != null && max.isLinkedDeep();
+       }
+
+       boolean isAbsolute()
+       {
+               return (min == null || min.isAbsoluteDeep()) && (pref == null || pref.isAbsoluteDeep()) && (max == null || max.isAbsoluteDeep());
+       }
+
+       public String toString()
+       {
+               return "BoundSize{" + "min=" + min + ", pref=" + pref + ", max=" + max + ", gapPush=" + gapPush +'}';
+       }
+
+//     static {
+//        if(LayoutUtil.HAS_BEANS){
+//            LayoutUtil.setDelegate(BoundSize.class, new PersistenceDelegate() {
+//                @Override
+//                protected Expression instantiate(Object oldInstance, Encoder out)
+//                {
+//                    BoundSize bs = (BoundSize) oldInstance;
+//                    if (Grid.TEST_GAPS) {
+//                        return new Expression(oldInstance, BoundSize.class, "new", new Object[] {
+//                                bs.getMin(), bs.getPreferred(), bs.getMax(), bs.getGapPush(), bs.getConstraintString()
+//                        });
+//                    } else {
+//                        return new Expression(oldInstance, BoundSize.class, "new", new Object[] {
+//                                bs.getMin(), bs.getPreferred(), bs.getMax(), bs.getConstraintString()
+//                        });
+//                    }
+//                }
+//            });
+//        }
+//     }
+
+       // ************************************************
+       // Persistence Delegate and Serializable combined.
+       // ************************************************
+
+       private static final long serialVersionUID = 1L;
+
+       protected Object readResolve() throws ObjectStreamException
+       {
+               return LayoutUtil.getSerializedObject(this);
+       }
+
+       private void writeObject(ObjectOutputStream out) throws IOException
+       {
+//             if (getClass() == BoundSize.class)
+//                     LayoutUtil.writeAsXML(out, this);
+       }
+
+       private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
+       {
+//             LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
+       }
+}
similarity index 99%
rename from src/net/miginfocom/layout/CC.java
rename to src2/net/miginfocom/layout/CC.java
index e4cfff9..7206733 100644 (file)
@@ -1,5 +1,6 @@
 package net.miginfocom.layout;
 
+import java.io.*;
 import java.util.ArrayList;
 /*
  * License (BSD):
@@ -37,7 +38,7 @@ import java.util.ArrayList;
 
 /** A simple value holder for one component's constraint.
  */
-public final class CC// s implements Externalizable
+public final class CC implements Externalizable
 {
        private static final BoundSize DEF_GAP = BoundSize.NULL_SIZE;    // Only used to denote default wrap/newline gap.
 
@@ -1856,25 +1857,25 @@ public final class CC// s implements Externalizable
        }
 
 
-//     // ************************************************
-//     // Persistence Delegate and Serializable combined.
-//     // ************************************************
-//
-//     private Object readResolve() throws ObjectStreamException
-//     {
-//             return LayoutUtil.getSerializedObject(this);
-//     }
-//
-//     @Override
-//     public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
-//     {
-//             LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
-//     }
-//
-//     @Override
-//     public void writeExternal(ObjectOutput out) throws IOException
-//     {
-//             if (getClass() == CC.class)
-//                     LayoutUtil.writeAsXML(out, this);
-//     }
+       // ************************************************
+       // Persistence Delegate and Serializable combined.
+       // ************************************************
+
+       private Object readResolve() throws ObjectStreamException
+       {
+               return LayoutUtil.getSerializedObject(this);
+       }
+
+       @Override
+       public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
+       {
+               LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
+       }
+
+       @Override
+       public void writeExternal(ObjectOutput out) throws IOException
+       {
+               if (getClass() == CC.class)
+                       LayoutUtil.writeAsXML(out, this);
+       }
 }
\ No newline at end of file
similarity index 96%
rename from src/net/miginfocom/layout/DimConstraint.java
rename to src2/net/miginfocom/layout/DimConstraint.java
index 0ea29df..c36d88c 100644 (file)
@@ -41,7 +41,7 @@ import java.io.ObjectStreamException;
 
 /** A simple value holder for a constraint for one dimension.
  */
-public final class DimConstraint// implements Externalizable
+public final class DimConstraint implements Externalizable
 {
        /** How this entity can be resized in the dimension that this constraint represents.
         */
@@ -453,25 +453,25 @@ public final class DimConstraint// implements Externalizable
                return ret;
        }
 
-//     // ************************************************
-//     // Persistence Delegate and Serializable combined.
-//     // ************************************************
-//
-//     private Object readResolve() throws ObjectStreamException
-//     {
-//             return LayoutUtil.getSerializedObject(this);
-//     }
-//
-//     @Override
-//     public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
-//     {
-//             LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
-//     }
-//
-//     @Override
-//     public void writeExternal(ObjectOutput out) throws IOException
-//     {
-//             if (getClass() == DimConstraint.class)
-//                     LayoutUtil.writeAsXML(out, this);
-//     }
+       // ************************************************
+       // Persistence Delegate and Serializable combined.
+       // ************************************************
+
+       private Object readResolve() throws ObjectStreamException
+       {
+               return LayoutUtil.getSerializedObject(this);
+       }
+
+       @Override
+       public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
+       {
+               LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
+       }
+
+       @Override
+       public void writeExternal(ObjectOutput out) throws IOException
+       {
+               if (getClass() == DimConstraint.class)
+                       LayoutUtil.writeAsXML(out, this);
+       }
 }
similarity index 98%
rename from src/net/miginfocom/layout/LC.java
rename to src2/net/miginfocom/layout/LC.java
index 3c8fc69..b40fa75 100644 (file)
@@ -1,5 +1,6 @@
 package net.miginfocom.layout;
 
+import java.io.*;
 /*
  * License (BSD):
  * ==============
@@ -34,11 +35,9 @@ package net.miginfocom.layout;
  *         Date: 2006-sep-08
  */
 
-
-
 /** Contains the constraints for an instance of the {@link LC} layout manager.
  */
-public final class LC //implements Externalizable
+public final class LC implements Externalizable
 {
        // See the corresponding set/get method for documentation of the property!
 
@@ -1020,26 +1019,26 @@ public final class LC //implements Externalizable
                setHeight(LayoutUtil.derive(getHeight(), null, null, ConstraintParser.parseUnitValue(height, false)));
                return this;
        }
-//
-//     // ************************************************
-//     // Persistence Delegate and Serializable combined.
-//     // ************************************************
-//
-//     private Object readResolve() throws ObjectStreamException
-//     {
-//             return LayoutUtil.getSerializedObject(this);
-//     }
-//
-//     @Override
-//     public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
-//     {
-//             LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
-//     }
-//
-//     @Override
-//     public void writeExternal(ObjectOutput out) throws IOException
-//     {
-//             if (getClass() == LC.class)
-//                     LayoutUtil.writeAsXML(out, this);
-//     }
+
+       // ************************************************
+       // Persistence Delegate and Serializable combined.
+       // ************************************************
+
+       private Object readResolve() throws ObjectStreamException
+       {
+               return LayoutUtil.getSerializedObject(this);
+       }
+
+       @Override
+       public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
+       {
+               LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
+       }
+
+       @Override
+       public void writeExternal(ObjectOutput out) throws IOException
+       {
+               if (getClass() == LC.class)
+                       LayoutUtil.writeAsXML(out, this);
+       }
 }
similarity index 82%
rename from src/net/miginfocom/layout/LayoutUtil.java
rename to src2/net/miginfocom/layout/LayoutUtil.java
index 4a23e0f..c817827 100644 (file)
@@ -1,18 +1,7 @@
 package net.miginfocom.layout;
 
-//import java.beans.Beans;
-//import java.beans.ExceptionListener;
-//import java.beans.Introspector;
-//import java.beans.PersistenceDelegate;
-//import java.beans.XMLDecoder;
-//import java.beans.XMLEncoder;
-//import java.io.ByteArrayInputStream;
-//import java.io.ByteArrayOutputStream;
-import java.io.EOFException;
-import java.io.IOException;
-//import java.io.ObjectInput;
-//import java.io.ObjectOutput;
-//import java.io.OutputStream;
+import java.beans.*;
+import java.io.*;
 import java.util.IdentityHashMap;
 import java.util.TreeSet;
 import java.util.WeakHashMap;
@@ -76,18 +65,17 @@ public final class LayoutUtil
        private static volatile WeakHashMap<Object, Boolean> DT_MAP = null;      // The Containers that have design time. Value not used.
        private static int eSz = 0;
        private static int globalDebugMillis = 0;
-       
- //   public static final boolean HAS_BEANS = hasBeans();
-
-//    private static boolean hasBeans()
-//    {
-//        try {
-//            LayoutUtil.class.getClassLoader().loadClass("java.beans.Beans");
-//            return true;
-//        } catch (Throwable e) {
-//            return false;
-//        }
-//    }
+    public static final boolean HAS_BEANS = hasBeans();
+
+    private static boolean hasBeans()
+    {
+        try {
+            LayoutUtil.class.getClassLoader().loadClass("java.beans.Beans");
+            return true;
+        } catch (Throwable e) {
+            return false;
+        }
+    }
 
        private LayoutUtil()
        {
@@ -152,7 +140,7 @@ public final class LayoutUtil
        public static boolean isDesignTime(ContainerWrapper cw)
        {
                if (DT_MAP == null)
-                       return false;// BH 2018 //HAS_BEANS && Beans.isDesignTime();
+                       return HAS_BEANS && Beans.isDesignTime();
 
                // assume design time "in general" (cw is null) if there is at least one container with design time
                // (for storing constraints creation strings in method putCCString())
@@ -202,17 +190,17 @@ public final class LayoutUtil
                }
        }
 
-//     /** Sets/add the persistence delegates to be used for a class.
-//      * @param c The class to set the registered delegate for.
-//      * @param del The new delegate or <code>null</code> to erase to old one.
-//      */
-//     static synchronized void setDelegate(Class<?> c, PersistenceDelegate del)
-//     {
-//             try {
-//                     Introspector.getBeanInfo(c, Introspector.IGNORE_ALL_BEANINFO).getBeanDescriptor().setValue("persistenceDelegate", del);
-//             } catch (Exception ignored) {
-//             }
-//     }
+       /** Sets/add the persistence delegates to be used for a class.
+        * @param c The class to set the registered delegate for.
+        * @param del The new delegate or <code>null</code> to erase to old one.
+        */
+       static synchronized void setDelegate(Class<?> c, PersistenceDelegate del)
+       {
+               try {
+                       Introspector.getBeanInfo(c, Introspector.IGNORE_ALL_BEANINFO).getBeanDescriptor().setValue("persistenceDelegate", del);
+               } catch (Exception ignored) {
+               }
+       }
 
        /** Returns strings set with {@link #putCCString(Object, String)} or <code>null</code> if nothing is associated or
         * {@link LayoutUtil#isDesignTime(ContainerWrapper)} returns <code>false</code>.
@@ -499,89 +487,89 @@ public final class LayoutUtil
                return (i != null && i[side] != null) ? i[side] : (getDefault ? PlatformDefaults.getPanelInsets(side) : UnitValue.ZERO);
        }
 
-//     /** Writes the object and CLOSES the stream. Uses the persistence delegate registered in this class.
-//      * @param os The stream to write to. Will be closed.
-//      * @param o The object to be serialized.
-//      * @param listener The listener to receive the exceptions if there are any. If <code>null</code> not used.
-//      */
-//     static void writeXMLObject(OutputStream os, Object o, ExceptionListener listener)
-//     {
-//             ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
-//             Thread.currentThread().setContextClassLoader(LayoutUtil.class.getClassLoader());
-//
-//             XMLEncoder encoder = new XMLEncoder(os);
-//
-//             if (listener != null)
-//                     encoder.setExceptionListener(listener);
-//
-//             encoder.writeObject(o);
-//        encoder.close();    // Must be closed to write.
-//
-//             Thread.currentThread().setContextClassLoader(oldClassLoader);
-//     }
-//
-//     private static ByteArrayOutputStream writeOutputStream = null;
-//     /** Writes an object to XML.
-//      * @param out The object out to write to. Will not be closed.
-//      * @param o The object to write.
-//      */
-//     public static synchronized void writeAsXML(ObjectOutput out, Object o) throws IOException
-//     {
-//             if (writeOutputStream == null)
-//                     writeOutputStream = new ByteArrayOutputStream(16384);
-//
-//             writeOutputStream.reset();
-//
-//             writeXMLObject(writeOutputStream, o, new ExceptionListener() {
-//                     @Override
-//                     public void exceptionThrown(Exception e) {
-//                             e.printStackTrace();
-//                     }});
-//
-//             byte[] buf = writeOutputStream.toByteArray();
-//
-//             out.writeInt(buf.length);
-//             out.write(buf);
-//     }
-//
-//     private static byte[] readBuf = null;
-//     /** Reads an object from <code>in</code> using the
-//      * @param in The object input to read from.
-//      * @return The object. Never <code>null</code>.
-//      * @throws IOException If there was a problem saving as XML
-//      */
-//     public static synchronized Object readAsXML(ObjectInput in) throws IOException
-//     {
-//             if (readBuf == null)
-//                     readBuf = new byte[16384];
-//
-//             Thread cThread = Thread.currentThread();
-//             ClassLoader oldCL = null;
-//
-//             try {
-//                     oldCL = cThread.getContextClassLoader();
-//                     cThread.setContextClassLoader(LayoutUtil.class.getClassLoader());
-//             } catch(SecurityException ignored) {
-//             }
-//
-//             Object o = null;
-//             try {
-//                     int length = in.readInt();
-//                     if (length > readBuf.length)
-//                             readBuf = new byte[length];
-//
-//                     in.readFully(readBuf, 0, length);
-//
-//                     o = new XMLDecoder(new ByteArrayInputStream(readBuf, 0, length)).readObject();
-//
-//             } catch(EOFException ignored) {
-//             }
-//
-//             if (oldCL != null)
-//                     cThread.setContextClassLoader(oldCL);
-//
-//             return o;
-//     }
+       /** Writes the object and CLOSES the stream. Uses the persistence delegate registered in this class.
+        * @param os The stream to write to. Will be closed.
+        * @param o The object to be serialized.
+        * @param listener The listener to receive the exceptions if there are any. If <code>null</code> not used.
+        */
+       static void writeXMLObject(OutputStream os, Object o, ExceptionListener listener)
+       {
+               ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
+               Thread.currentThread().setContextClassLoader(LayoutUtil.class.getClassLoader());
+
+               XMLEncoder encoder = new XMLEncoder(os);
+
+               if (listener != null)
+                       encoder.setExceptionListener(listener);
+
+               encoder.writeObject(o);
+        encoder.close();    // Must be closed to write.
+
+               Thread.currentThread().setContextClassLoader(oldClassLoader);
+       }
+
+       private static ByteArrayOutputStream writeOutputStream = null;
+       /** Writes an object to XML.
+        * @param out The object out to write to. Will not be closed.
+        * @param o The object to write.
+        */
+       public static synchronized void writeAsXML(ObjectOutput out, Object o) throws IOException
+       {
+               if (writeOutputStream == null)
+                       writeOutputStream = new ByteArrayOutputStream(16384);
+
+               writeOutputStream.reset();
+
+               writeXMLObject(writeOutputStream, o, new ExceptionListener() {
+                       @Override
+                       public void exceptionThrown(Exception e) {
+                               e.printStackTrace();
+                       }});
+
+               byte[] buf = writeOutputStream.toByteArray();
+
+               out.writeInt(buf.length);
+               out.write(buf);
+       }
+
+       private static byte[] readBuf = null;
+       /** Reads an object from <code>in</code> using the
+        * @param in The object input to read from.
+        * @return The object. Never <code>null</code>.
+        * @throws IOException If there was a problem saving as XML
+        */
+       public static synchronized Object readAsXML(ObjectInput in) throws IOException
+       {
+               if (readBuf == null)
+                       readBuf = new byte[16384];
+
+               Thread cThread = Thread.currentThread();
+               ClassLoader oldCL = null;
+
+               try {
+                       oldCL = cThread.getContextClassLoader();
+                       cThread.setContextClassLoader(LayoutUtil.class.getClassLoader());
+               } catch(SecurityException ignored) {
+               }
+
+               Object o = null;
+               try {
+                       int length = in.readInt();
+                       if (length > readBuf.length)
+                               readBuf = new byte[length];
+
+                       in.readFully(readBuf, 0, length);
+
+                       o = new XMLDecoder(new ByteArrayInputStream(readBuf, 0, length)).readObject();
+
+               } catch(EOFException ignored) {
+               }
+
+               if (oldCL != null)
+                       cThread.setContextClassLoader(oldCL);
+
+               return o;
+       }
 
        private static final IdentityHashMap<Object, Object> SER_MAP = new IdentityHashMap<Object, Object>(2);
 
@@ -1,5 +1,6 @@
 package net.miginfocom.layout;
 
+import java.io.*;
 /*
  * License (BSD):
  * ==============
@@ -33,12 +34,11 @@ package net.miginfocom.layout;
  * @author Mikael Grev, MiG InfoCom AB
  *         Date: 2006-sep-08
  */
-//import java.io.Externalizable;
 
 /** A parsed constraint that specifies how an entity (normally column/row or component) can shrink or
  * grow compared to other entities.
  */
-final class ResizeConstraint //implements Externalizable
+final class ResizeConstraint implements Externalizable
 {
        static final Float WEIGHT_100 = 100f;
 
@@ -70,25 +70,25 @@ final class ResizeConstraint //implements Externalizable
                this.grow = growWeight;
        }
 
-//     // ************************************************
-//     // Persistence Delegate and Serializable combined.
-//     // ************************************************
-//
-//     private Object readResolve() throws ObjectStreamException
-//     {
-//             return LayoutUtil.getSerializedObject(this);
-//     }
-//
-//     @Override
-//     public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
-//     {
-//             LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
-//     }
-//
-//     @Override
-//     public void writeExternal(ObjectOutput out) throws IOException
-//     {
-//             if (getClass() == ResizeConstraint.class)
-//                     LayoutUtil.writeAsXML(out, this);
-//     }
+       // ************************************************
+       // Persistence Delegate and Serializable combined.
+       // ************************************************
+
+       private Object readResolve() throws ObjectStreamException
+       {
+               return LayoutUtil.getSerializedObject(this);
+       }
+
+       @Override
+       public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
+       {
+               LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
+       }
+
+       @Override
+       public void writeExternal(ObjectOutput out) throws IOException
+       {
+               if (getClass() == ResizeConstraint.class)
+                       LayoutUtil.writeAsXML(out, this);
+       }
 }
similarity index 91%
rename from src/net/miginfocom/layout/UnitValue.java
rename to src2/net/miginfocom/layout/UnitValue.java
index 690f14a..70d8f72 100644 (file)
@@ -33,10 +33,10 @@ package net.miginfocom.layout;
  *         Date: 2006-sep-08
  */
 
-//import java.beans.Encoder;
-//import java.beans.Expression;
-//import java.beans.PersistenceDelegate;
-import java.io.Serializable;
+import java.beans.Encoder;
+import java.beans.Expression;
+import java.beans.PersistenceDelegate;
+import java.io.*;
 import java.util.ArrayList;
 import java.util.HashMap;
 
@@ -648,44 +648,44 @@ public final class UnitValue implements Serializable
                PlatformDefaults.setDefaultVerticalUnit(unit);
        }
 
-//     static {
-//        if(LayoutUtil.HAS_BEANS){\
-//            LayoutUtil.setDelegate(UnitValue.class, new PersistenceDelegate() {
-//                @Override
-//                protected Expression instantiate(Object oldInstance, Encoder out)
-//                {
-//                    UnitValue uv = (UnitValue) oldInstance;
-//                    String cs = uv.getConstraintString();
-//                    if (cs == null)
-//                        throw new IllegalStateException("Design time must be on to use XML persistence. See LayoutUtil.");
-//
-//                    return new Expression(oldInstance, ConstraintParser.class, "parseUnitValueOrAlign", new Object[] {
-//                            uv.getConstraintString(), (uv.isHorizontal() ? Boolean.TRUE : Boolean.FALSE), null
-//                    });
-//                }
-//            });
-//        }
-//     }
-//
-//     // ************************************************
-//     // Persistence Delegate and Serializable combined.
-//     // ************************************************
-//
-//     private static final long serialVersionUID = 1L;
-//
-//     private Object readResolve() throws ObjectStreamException
-//     {
-//             return LayoutUtil.getSerializedObject(this);
-//     }
-//
-//     private void writeObject(ObjectOutputStream out) throws IOException
-//     {
-//             if (getClass() == UnitValue.class)
-//                     LayoutUtil.writeAsXML(out, this);
-//     }
-//
-//     private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
-//     {
-//             LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
-//     }
+       static {
+        if(LayoutUtil.HAS_BEANS){
+            LayoutUtil.setDelegate(UnitValue.class, new PersistenceDelegate() {
+                @Override
+                protected Expression instantiate(Object oldInstance, Encoder out)
+                {
+                    UnitValue uv = (UnitValue) oldInstance;
+                    String cs = uv.getConstraintString();
+                    if (cs == null)
+                        throw new IllegalStateException("Design time must be on to use XML persistence. See LayoutUtil.");
+
+                    return new Expression(oldInstance, ConstraintParser.class, "parseUnitValueOrAlign", new Object[] {
+                            uv.getConstraintString(), (uv.isHorizontal() ? Boolean.TRUE : Boolean.FALSE), null
+                    });
+                }
+            });
+        }
+       }
+
+       // ************************************************
+       // Persistence Delegate and Serializable combined.
+       // ************************************************
+
+       private static final long serialVersionUID = 1L;
+
+       private Object readResolve() throws ObjectStreamException
+       {
+               return LayoutUtil.getSerializedObject(this);
+       }
+
+       private void writeObject(ObjectOutputStream out) throws IOException
+       {
+               if (getClass() == UnitValue.class)
+                       LayoutUtil.writeAsXML(out, this);
+       }
+
+       private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
+       {
+               LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
+       }
 }
similarity index 93%
rename from src/net/miginfocom/swing/MigLayout.java
rename to src2/net/miginfocom/swing/MigLayout.java
index 8469d7c..fdd7718 100644 (file)
@@ -33,51 +33,21 @@ package net.miginfocom.swing;
  *         Date: 2006-sep-08
  */
 
-import java.awt.Component;
-import java.awt.Container;
-import java.awt.Dimension;
-import java.awt.Insets;
-import java.awt.LayoutManager;
-import java.awt.LayoutManager2;
-import java.awt.Point;
-import java.awt.Window;
+import net.miginfocom.layout.*;
+
+import javax.swing.*;
+import javax.swing.Timer;
+import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import javax.swing.BoxLayout;
-import javax.swing.JComponent;
-import javax.swing.JEditorPane;
-import javax.swing.JPopupMenu;
-import javax.swing.JTextArea;
-import javax.swing.OverlayLayout;
-import javax.swing.SwingUtilities;
-import javax.swing.Timer;
-
-import net.miginfocom.layout.AC;
-import net.miginfocom.layout.BoundSize;
-import net.miginfocom.layout.CC;
-import net.miginfocom.layout.ComponentWrapper;
-import net.miginfocom.layout.ConstraintParser;
-import net.miginfocom.layout.ContainerWrapper;
-import net.miginfocom.layout.Grid;
-import net.miginfocom.layout.LC;
-import net.miginfocom.layout.LayoutCallback;
-import net.miginfocom.layout.LayoutUtil;
-import net.miginfocom.layout.PlatformDefaults;
-import net.miginfocom.layout.UnitValue;
+import java.io.*;
+import java.util.*;
 
 /** A very flexible layout manager.
  * <p>
  * Read the documentation that came with this layout manager for information on usage.
  */
-public class MigLayout implements LayoutManager2//, Externalizable
+public class MigLayout implements LayoutManager2, Externalizable
 {
        // ******** Instance part ********
 
@@ -775,27 +745,27 @@ public class MigLayout implements LayoutManager2//, Externalizable
                dirty = true;
        }
 
-//     // ************************************************
-//     // Persistence Delegate and Serializable combined.
-//     // ************************************************
-//
-//     private Object readResolve() throws ObjectStreamException
-//     {
-//             return LayoutUtil.getSerializedObject(this);
-//     }
-//
-//     @Override
-//     public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
-//     {
-//             LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
-//     }
-//
-//     @Override
-//     public void writeExternal(ObjectOutput out) throws IOException
-//     {
-//             if (getClass() == MigLayout.class)
-//                     LayoutUtil.writeAsXML(out, this);
-//     }
+       // ************************************************
+       // Persistence Delegate and Serializable combined.
+       // ************************************************
+
+       private Object readResolve() throws ObjectStreamException
+       {
+               return LayoutUtil.getSerializedObject(this);
+       }
+
+       @Override
+       public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
+       {
+               LayoutUtil.setSerializedObject(this, LayoutUtil.readAsXML(in));
+       }
+
+       @Override
+       public void writeExternal(ObjectOutput out) throws IOException
+       {
+               if (getClass() == MigLayout.class)
+                       LayoutUtil.writeAsXML(out, this);
+       }
 
        private class MyDebugRepaintListener implements ActionListener
        {
diff --git a/src2/org/json/simple/ItemList.java b/src2/org/json/simple/ItemList.java
new file mode 100644 (file)
index 0000000..830961b
--- /dev/null
@@ -0,0 +1,147 @@
+/*
+ * $Id: ItemList.java,v 1.1 2006/04/15 14:10:48 platform Exp $
+ * Created on 2006-3-24
+ */
+package org.json.simple;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+/**
+ * |a:b:c| => |a|,|b|,|c|
+ * |:| => ||,||
+ * |a:| => |a|,||
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public class ItemList {
+       private String sp=",";
+       List items=new ArrayList();
+       
+       
+       public ItemList(){}
+       
+       
+       public ItemList(String s){
+               this.split(s,sp,items);
+       }
+       
+       public ItemList(String s,String sp){
+               this.sp=s;
+               this.split(s,sp,items);
+       }
+       
+       public ItemList(String s,String sp,boolean isMultiToken){
+               split(s,sp,items,isMultiToken);
+       }
+       
+       public List getItems(){
+               return this.items;
+       }
+       
+       public String[] getArray(){
+               return (String[])this.items.toArray();
+       }
+       
+       public void split(String s,String sp,List append,boolean isMultiToken){
+               if(s==null || sp==null)
+                       return;
+               if(isMultiToken){
+                       StringTokenizer tokens=new StringTokenizer(s,sp);
+                       while(tokens.hasMoreTokens()){
+                               append.add(tokens.nextToken().trim());
+                       }
+               }
+               else{
+                       this.split(s,sp,append);
+               }
+       }
+       
+       public void split(String s,String sp,List append){
+               if(s==null || sp==null)
+                       return;
+               int pos=0;
+               int prevPos=0;
+               do{
+                       prevPos=pos;
+                       pos=s.indexOf(sp,pos);
+                       if(pos==-1)
+                               break;
+                       append.add(s.substring(prevPos,pos).trim());
+                       pos+=sp.length();
+               }while(pos!=-1);
+               append.add(s.substring(prevPos).trim());
+       }
+       
+       public void setSP(String sp){
+               this.sp=sp;
+       }
+       
+       public void add(int i,String item){
+               if(item==null)
+                       return;
+               items.add(i,item.trim());
+       }
+
+       public void add(String item){
+               if(item==null)
+                       return;
+               items.add(item.trim());
+       }
+       
+       public void addAll(ItemList list){
+               items.addAll(list.items);
+       }
+       
+       public void addAll(String s){
+               this.split(s,sp,items);
+       }
+       
+       public void addAll(String s,String sp){
+               this.split(s,sp,items);
+       }
+       
+       public void addAll(String s,String sp,boolean isMultiToken){
+               this.split(s,sp,items,isMultiToken);
+       }
+       
+       /**
+        * @param i 0-based
+        * @return
+        */
+       public String get(int i){
+               return (String)items.get(i);
+       }
+       
+       public int size(){
+               return items.size();
+       }
+
+       public String toString(){
+               return toString(sp);
+       }
+       
+       public String toString(String sp){
+               StringBuffer sb=new StringBuffer();
+               
+               for(int i=0;i<items.size();i++){
+                       if(i==0)
+                               sb.append(items.get(i));
+                       else{
+                               sb.append(sp);
+                               sb.append(items.get(i));
+                       }
+               }
+               return sb.toString();
+
+       }
+       
+       public void clear(){
+               items.clear();
+       }
+       
+       public void reset(){
+               sp=",";
+               items.clear();
+       }
+}
diff --git a/src2/org/json/simple/JSONArray.java b/src2/org/json/simple/JSONArray.java
new file mode 100644 (file)
index 0000000..60f54c4
--- /dev/null
@@ -0,0 +1,381 @@
+/*
+ * $Id: JSONArray.java,v 1.1 2006/04/15 14:10:48 platform Exp $
+ * Created on 2006-4-10
+ */
+package org.json.simple;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+
+/**
+ * A JSON array. JSONObject supports java.util.List interface.
+ * 
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
+       private static final long serialVersionUID = 3957988303675231981L;
+       
+       /**
+        * Constructs an empty JSONArray.
+        */
+       public JSONArray(){
+               super();
+       }
+       
+       /**
+        * Constructs a JSONArray containing the elements of the specified
+        * collection, in the order they are returned by the collection's iterator.
+        * 
+        * @param c the collection whose elements are to be placed into this JSONArray
+        */
+       public JSONArray(Collection c){
+               super(c);
+       }
+       
+    /**
+     * Encode a list into JSON text and write it to out. 
+     * If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level.
+     * 
+     * @see org.json.simple.JSONValue#writeJSONString(Object, Writer)
+     * 
+     * @param collection
+     * @param out
+     */
+       public static void writeJSONString(Collection collection, Writer out) throws IOException{
+               if(collection == null){
+                       out.write("null");
+                       return;
+               }
+               
+               boolean first = true;
+               Iterator iter=collection.iterator();
+               
+        out.write('[');
+               while(iter.hasNext()){
+            if(first)
+                first = false;
+            else
+                out.write(',');
+            
+                       Object value=iter.next();
+                       if(value == null){
+                               out.write("null");
+                               continue;
+                       }
+                       
+                       JSONValue.writeJSONString(value, out);
+               }
+               out.write(']');
+       }
+       
+       public void writeJSONString(Writer out) throws IOException{
+               writeJSONString(this, out);
+       }
+       
+       /**
+        * Convert a list to JSON text. The result is a JSON array. 
+        * If this list is also a JSONAware, JSONAware specific behaviours will be omitted at this top level.
+        * 
+        * @see org.json.simple.JSONValue#toJSONString(Object)
+        * 
+        * @param collection
+        * @return JSON text, or "null" if list is null.
+        */
+       public static String toJSONString(Collection collection){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(collection, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+
+       public static void writeJSONString(byte[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[");
+                       out.write(String.valueOf(array[0]));
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write(",");
+                               out.write(String.valueOf(array[i]));
+                       }
+                       
+                       out.write("]");
+               }
+       }
+       
+       public static String toJSONString(byte[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public static void writeJSONString(short[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[");
+                       out.write(String.valueOf(array[0]));
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write(",");
+                               out.write(String.valueOf(array[i]));
+                       }
+                       
+                       out.write("]");
+               }
+       }
+       
+       public static String toJSONString(short[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public static void writeJSONString(int[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[");
+                       out.write(String.valueOf(array[0]));
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write(",");
+                               out.write(String.valueOf(array[i]));
+                       }
+                       
+                       out.write("]");
+               }
+       }
+       
+       public static String toJSONString(int[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public static void writeJSONString(long[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[");
+                       out.write(String.valueOf(array[0]));
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write(",");
+                               out.write(String.valueOf(array[i]));
+                       }
+                       
+                       out.write("]");
+               }
+       }
+       
+       public static String toJSONString(long[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public static void writeJSONString(float[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[");
+                       out.write(String.valueOf(array[0]));
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write(",");
+                               out.write(String.valueOf(array[i]));
+                       }
+                       
+                       out.write("]");
+               }
+       }
+       
+       public static String toJSONString(float[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public static void writeJSONString(double[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[");
+                       out.write(String.valueOf(array[0]));
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write(",");
+                               out.write(String.valueOf(array[i]));
+                       }
+                       
+                       out.write("]");
+               }
+       }
+       
+       public static String toJSONString(double[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public static void writeJSONString(boolean[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[");
+                       out.write(String.valueOf(array[0]));
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write(",");
+                               out.write(String.valueOf(array[i]));
+                       }
+                       
+                       out.write("]");
+               }
+       }
+       
+       public static String toJSONString(boolean[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public static void writeJSONString(char[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[\"");
+                       out.write(String.valueOf(array[0]));
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write("\",\"");
+                               out.write(String.valueOf(array[i]));
+                       }
+                       
+                       out.write("\"]");
+               }
+       }
+       
+       public static String toJSONString(char[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public static void writeJSONString(Object[] array, Writer out) throws IOException{
+               if(array == null){
+                       out.write("null");
+               } else if(array.length == 0) {
+                       out.write("[]");
+               } else {
+                       out.write("[");
+                       JSONValue.writeJSONString(array[0], out);
+                       
+                       for(int i = 1; i < array.length; i++){
+                               out.write(",");
+                               JSONValue.writeJSONString(array[i], out);
+                       }
+                       
+                       out.write("]");
+               }
+       }
+       
+       public static String toJSONString(Object[] array){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(array, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public String toJSONString(){
+               return toJSONString(this);
+       }
+
+       /**
+        * Returns a string representation of this array. This is equivalent to
+        * calling {@link JSONArray#toJSONString()}.
+        */
+       public String toString() {
+               return toJSONString();
+       }
+}
diff --git a/src2/org/json/simple/JSONAware.java b/src2/org/json/simple/JSONAware.java
new file mode 100644 (file)
index 0000000..5e7452f
--- /dev/null
@@ -0,0 +1,12 @@
+package org.json.simple;
+
+/**
+ * Beans that support customized output of JSON text shall implement this interface.  
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public interface JSONAware {
+       /**
+        * @return JSON text
+        */
+       String toJSONString();
+}
diff --git a/src2/org/json/simple/JSONObject.java b/src2/org/json/simple/JSONObject.java
new file mode 100644 (file)
index 0000000..fafa36b
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * $Id: JSONObject.java,v 1.1 2006/04/15 14:10:48 platform Exp $
+ * Created on 2006-4-10
+ */
+package org.json.simple;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
+ * 
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware{
+       
+       private static final long serialVersionUID = -503443796854799292L;
+       
+       
+       public JSONObject() {
+               super();
+       }
+
+       /**
+        * Allows creation of a JSONObject from a Map. After that, both the
+        * generated JSONObject and the Map can be modified independently.
+        * 
+        * @param map
+        */
+       public JSONObject(Map map) {
+               super(map);
+       }
+
+
+    /**
+     * Encode a map into JSON text and write it to out.
+     * If this map is also a JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific behaviours will be ignored at this top level.
+     * 
+     * @see org.json.simple.JSONValue#writeJSONString(Object, Writer)
+     * 
+     * @param map
+     * @param out
+     */
+       public static void writeJSONString(Map map, Writer out) throws IOException {
+               if(map == null){
+                       out.write("null");
+                       return;
+               }
+               
+               boolean first = true;
+               Iterator iter=map.entrySet().iterator();
+               
+        out.write('{');
+               while(iter.hasNext()){
+            if(first)
+                first = false;
+            else
+                out.write(',');
+                       Map.Entry entry=(Map.Entry)iter.next();
+            out.write('\"');
+            out.write(escape(String.valueOf(entry.getKey())));
+            out.write('\"');
+            out.write(':');
+                       JSONValue.writeJSONString(entry.getValue(), out);
+               }
+               out.write('}');
+       }
+
+       public void writeJSONString(Writer out) throws IOException{
+               writeJSONString(this, out);
+       }
+       
+       /**
+        * Convert a map to JSON text. The result is a JSON object. 
+        * If this map is also a JSONAware, JSONAware specific behaviours will be omitted at this top level.
+        * 
+        * @see org.json.simple.JSONValue#toJSONString(Object)
+        * 
+        * @param map
+        * @return JSON text, or "null" if map is null.
+        */
+       public static String toJSONString(Map map){
+               final StringWriter writer = new StringWriter();
+               
+               try {
+                       writeJSONString(map, writer);
+                       return writer.toString();
+               } catch (IOException e) {
+                       // This should never happen with a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public String toJSONString(){
+               return toJSONString(this);
+       }
+       
+       public String toString(){
+               return toJSONString();
+       }
+
+       public static String toString(String key,Object value){
+        StringBuffer sb = new StringBuffer();
+        sb.append('\"');
+        if(key == null)
+            sb.append("null");
+        else
+            JSONValue.escape(key, sb);
+               sb.append('\"').append(':');
+               
+               sb.append(JSONValue.toJSONString(value));
+               
+               return sb.toString();
+       }
+       
+       /**
+        * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
+        * It's the same as JSONValue.escape() only for compatibility here.
+        * 
+        * @see org.json.simple.JSONValue#escape(String)
+        * 
+        * @param s
+        * @return
+        */
+       public static String escape(String s){
+               return JSONValue.escape(s);
+       }
+}
diff --git a/src2/org/json/simple/JSONStreamAware.java b/src2/org/json/simple/JSONStreamAware.java
new file mode 100644 (file)
index 0000000..ab63b3e
--- /dev/null
@@ -0,0 +1,15 @@
+package org.json.simple;
+
+import java.io.IOException;
+import java.io.Writer;
+
+/**
+ * Beans that support customized output of JSON text to a writer shall implement this interface.  
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public interface JSONStreamAware {
+       /**
+        * write JSON string to out.
+        */
+       void writeJSONString(Writer out) throws IOException;
+}
diff --git a/src2/org/json/simple/JSONValue.java b/src2/org/json/simple/JSONValue.java
new file mode 100644 (file)
index 0000000..5da3cd0
--- /dev/null
@@ -0,0 +1,316 @@
+/*
+ * $Id: JSONValue.java,v 1.1 2006/04/15 14:37:04 platform Exp $
+ * Created on 2006-4-15
+ */
+package org.json.simple;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.Collection;
+// import java.util.List;
+import java.util.Map;
+
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+
+
+/**
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public class JSONValue {
+       /**
+        * Parse JSON text into java object from the input source. 
+        * Please use parseWithException() if you don't want to ignore the exception.
+        * 
+        * @see org.json.simple.parser.JSONParser#parse(Reader)
+        * @see #parseWithException(Reader)
+        * 
+        * @param in
+        * @return Instance of the following:
+        *      org.json.simple.JSONObject,
+        *      org.json.simple.JSONArray,
+        *      java.lang.String,
+        *      java.lang.Number,
+        *      java.lang.Boolean,
+        *      null
+        * 
+        * @deprecated this method may throw an {@code Error} instead of returning
+        * {@code null}; please use {@link JSONValue#parseWithException(Reader)}
+        * instead
+        */
+       public static Object parse(Reader in){
+               try{
+                       JSONParser parser=new JSONParser();
+                       return parser.parse(in);
+               }
+               catch(Exception e){
+                       return null;
+               }
+       }
+       
+       /**
+        * Parse JSON text into java object from the given string. 
+        * Please use parseWithException() if you don't want to ignore the exception.
+        * 
+        * @see org.json.simple.parser.JSONParser#parse(Reader)
+        * @see #parseWithException(Reader)
+        * 
+        * @param s
+        * @return Instance of the following:
+        *      org.json.simple.JSONObject,
+        *      org.json.simple.JSONArray,
+        *      java.lang.String,
+        *      java.lang.Number,
+        *      java.lang.Boolean,
+        *      null
+        * 
+        * @deprecated this method may throw an {@code Error} instead of returning
+        * {@code null}; please use {@link JSONValue#parseWithException(String)}
+        * instead
+        */
+       public static Object parse(String s){
+               StringReader in=new StringReader(s);
+               return parse(in);
+       }
+       
+       /**
+        * Parse JSON text into java object from the input source.
+        * 
+        * @see org.json.simple.parser.JSONParser
+        * 
+        * @param in
+        * @return Instance of the following:
+        *      org.json.simple.JSONObject,
+        *      org.json.simple.JSONArray,
+        *      java.lang.String,
+        *      java.lang.Number,
+        *      java.lang.Boolean,
+        *      null
+        * 
+        * @throws IOException
+        * @throws ParseException
+        */
+       public static Object parseWithException(Reader in) throws IOException, ParseException{
+               JSONParser parser=new JSONParser();
+               return parser.parse(in);
+       }
+       
+       public static Object parseWithException(String s) throws ParseException{
+               JSONParser parser=new JSONParser();
+               return parser.parse(s);
+       }
+       
+    /**
+     * Encode an object into JSON text and write it to out.
+     * <p>
+     * If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
+     * <p>
+     * DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with 
+     * "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead. 
+     * 
+     * @see org.json.simple.JSONObject#writeJSONString(Map, Writer)
+     * @see org.json.simple.JSONArray#writeJSONString(List, Writer)
+     * 
+     * @param value
+     * @param writer
+     */
+       public static void writeJSONString(Object value, Writer out) throws IOException {
+               if(value == null){
+                       out.write("null");
+                       return;
+               }
+               
+               if(value instanceof String){            
+            out.write('\"');
+                       out.write(escape((String)value));
+            out.write('\"');
+                       return;
+               }
+               
+               if(value instanceof Double){
+                       if(((Double)value).isInfinite() || ((Double)value).isNaN())
+                               out.write("null");
+                       else
+                               out.write(value.toString());
+                       return;
+               }
+               
+               if(value instanceof Float){
+                       if(((Float)value).isInfinite() || ((Float)value).isNaN())
+                               out.write("null");
+                       else
+                               out.write(value.toString());
+                       return;
+               }               
+               
+               if(value instanceof Number){
+                       out.write(value.toString());
+                       return;
+               }
+               
+               if(value instanceof Boolean){
+                       out.write(value.toString());
+                       return;
+               }
+               
+               if((value instanceof JSONStreamAware)){
+                       ((JSONStreamAware)value).writeJSONString(out);
+                       return;
+               }
+               
+               if((value instanceof JSONAware)){
+                       out.write(((JSONAware)value).toJSONString());
+                       return;
+               }
+               
+               if(value instanceof Map){
+                       JSONObject.writeJSONString((Map)value, out);
+                       return;
+               }
+               
+               if(value instanceof Collection){
+                       JSONArray.writeJSONString((Collection)value, out);
+            return;
+               }
+               
+               if(value instanceof byte[]){
+                       JSONArray.writeJSONString((byte[])value, out);
+                       return;
+               }
+               
+               if(value instanceof short[]){
+                       JSONArray.writeJSONString((short[])value, out);
+                       return;
+               }
+               
+               if(value instanceof int[]){
+                       JSONArray.writeJSONString((int[])value, out);
+                       return;
+               }
+               
+               if(value instanceof long[]){
+                       JSONArray.writeJSONString((long[])value, out);
+                       return;
+               }
+               
+               if(value instanceof float[]){
+                       JSONArray.writeJSONString((float[])value, out);
+                       return;
+               }
+               
+               if(value instanceof double[]){
+                       JSONArray.writeJSONString((double[])value, out);
+                       return;
+               }
+               
+               if(value instanceof boolean[]){
+                       JSONArray.writeJSONString((boolean[])value, out);
+                       return;
+               }
+               
+               if(value instanceof char[]){
+                       JSONArray.writeJSONString((char[])value, out);
+                       return;
+               }
+               
+               if(value instanceof Object[]){
+                       JSONArray.writeJSONString((Object[])value, out);
+                       return;
+               }
+               
+               out.write(value.toString());
+       }
+
+       /**
+        * Convert an object to JSON text.
+        * <p>
+        * If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly.
+        * <p>
+        * DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with 
+        * "this" as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead. 
+        * 
+        * @see org.json.simple.JSONObject#toJSONString(Map)
+        * @see org.json.simple.JSONArray#toJSONString(List)
+        * 
+        * @param value
+        * @return JSON text, or "null" if value is null or it's an NaN or an INF number.
+        */
+       public static String toJSONString(Object value){
+               final StringWriter writer = new StringWriter();
+               
+               try{
+                       writeJSONString(value, writer);
+                       return writer.toString();
+               } catch(IOException e){
+                       // This should never happen for a StringWriter
+                       throw new RuntimeException(e);
+               }
+       }
+
+       /**
+        * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
+        * @param s
+        * @return
+        */
+       public static String escape(String s){
+               if(s==null)
+                       return null;
+        StringBuffer sb = new StringBuffer();
+        escape(s, sb);
+        return sb.toString();
+    }
+
+    /**
+     * @param s - Must not be null.
+     * @param sb
+     */
+    static void escape(String s, StringBuffer sb) {
+       final int len = s.length();
+               for(int i=0;i<len;i++){
+                       char ch=s.charAt(i);
+                       switch(ch){
+                       case '"':
+                               sb.append("\\\"");
+                               break;
+                       case '\\':
+                               sb.append("\\\\");
+                               break;
+                       case '\b':
+                               sb.append("\\b");
+                               break;
+                       case '\f':
+                               sb.append("\\f");
+                               break;
+                       case '\n':
+                               sb.append("\\n");
+                               break;
+                       case '\r':
+                               sb.append("\\r");
+                               break;
+                       case '\t':
+                               sb.append("\\t");
+                               break;
+                       case '/':
+                               sb.append("\\/");
+                               break;
+                       default:
+                //Reference: http://www.unicode.org/versions/Unicode5.1.0/
+                               if((ch>='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')){
+                                       String ss=Integer.toHexString(ch);
+                                       sb.append("\\u");
+                                       for(int k=0;k<4-ss.length();k++){
+                                               sb.append('0');
+                                       }
+                                       sb.append(ss.toUpperCase());
+                               }
+                               else{
+                                       sb.append(ch);
+                               }
+                       }
+               }//for
+       }
+
+}
diff --git a/src2/org/json/simple/README.txt b/src2/org/json/simple/README.txt
new file mode 100644 (file)
index 0000000..43b3a6c
--- /dev/null
@@ -0,0 +1,4 @@
+https://github.com/SwingJS/json-simple.git
+forked 6/23/2018 from https://github.com/fangyidong/json-simple/tree/master/src/main/java/org/json/simple
+Bob Hanson
+hansonr@stolaf.edu
\ No newline at end of file
diff --git a/src2/org/json/simple/parser/ContainerFactory.java b/src2/org/json/simple/parser/ContainerFactory.java
new file mode 100644 (file)
index 0000000..0bb7baf
--- /dev/null
@@ -0,0 +1,23 @@
+package org.json.simple.parser;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Container factory for creating containers for JSON object and JSON array.
+ * 
+ * @see org.json.simple.parser.JSONParser#parse(java.io.Reader, ContainerFactory)
+ * 
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public interface ContainerFactory {
+       /**
+        * @return A Map instance to store JSON object, or null if you want to use org.json.simple.JSONObject.
+        */
+       Map createObjectContainer();
+       
+       /**
+        * @return A List instance to store JSON array, or null if you want to use org.json.simple.JSONArray. 
+        */
+       List creatArrayContainer();
+}
diff --git a/src2/org/json/simple/parser/ContentHandler.java b/src2/org/json/simple/parser/ContentHandler.java
new file mode 100644 (file)
index 0000000..056a85c
--- /dev/null
@@ -0,0 +1,110 @@
+package org.json.simple.parser;
+
+import java.io.IOException;
+
+/**
+ * A simplified and stoppable SAX-like content handler for stream processing of JSON text. 
+ * 
+ * @see org.xml.sax.ContentHandler
+ * @see org.json.simple.parser.JSONParser#parse(java.io.Reader, ContentHandler, boolean)
+ * 
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public interface ContentHandler {
+       /**
+        * Receive notification of the beginning of JSON processing.
+        * The parser will invoke this method only once.
+     * 
+        * @throws ParseException 
+        *                      - JSONParser will stop and throw the same exception to the caller when receiving this exception.
+        */
+       void startJSON() throws ParseException, IOException;
+       
+       /**
+        * Receive notification of the end of JSON processing.
+        * 
+        * @throws ParseException
+        */
+       void endJSON() throws ParseException, IOException;
+       
+       /**
+        * Receive notification of the beginning of a JSON object.
+        * 
+        * @return false if the handler wants to stop parsing after return.
+        * @throws ParseException
+     *          - JSONParser will stop and throw the same exception to the caller when receiving this exception.
+     * @see #endJSON
+        */
+       boolean startObject() throws ParseException, IOException;
+       
+       /**
+        * Receive notification of the end of a JSON object.
+        * 
+        * @return false if the handler wants to stop parsing after return.
+        * @throws ParseException
+     * 
+     * @see #startObject
+        */
+       boolean endObject() throws ParseException, IOException;
+       
+       /**
+        * Receive notification of the beginning of a JSON object entry.
+        * 
+        * @param key - Key of a JSON object entry. 
+        * 
+        * @return false if the handler wants to stop parsing after return.
+        * @throws ParseException
+     * 
+     * @see #endObjectEntry
+        */
+       boolean startObjectEntry(String key) throws ParseException, IOException;
+       
+       /**
+        * Receive notification of the end of the value of previous object entry.
+        * 
+        * @return false if the handler wants to stop parsing after return.
+        * @throws ParseException
+     * 
+     * @see #startObjectEntry
+        */
+       boolean endObjectEntry() throws ParseException, IOException;
+       
+       /**
+        * Receive notification of the beginning of a JSON array.
+        * 
+        * @return false if the handler wants to stop parsing after return.
+        * @throws ParseException
+     * 
+     * @see #endArray
+        */
+       boolean startArray() throws ParseException, IOException;
+       
+       /**
+        * Receive notification of the end of a JSON array.
+        * 
+        * @return false if the handler wants to stop parsing after return.
+        * @throws ParseException
+     * 
+     * @see #startArray
+        */
+       boolean endArray() throws ParseException, IOException;
+       
+       /**
+        * Receive notification of the JSON primitive values:
+        *      java.lang.String,
+        *      java.lang.Number,
+        *      java.lang.Boolean
+        *      null
+        * 
+        * @param value - Instance of the following:
+        *                      java.lang.String,
+        *                      java.lang.Number,
+        *                      java.lang.Boolean
+        *                      null
+        * 
+        * @return false if the handler wants to stop parsing after return.
+        * @throws ParseException
+        */
+       boolean primitive(Object value) throws ParseException, IOException;
+               
+}
diff --git a/src2/org/json/simple/parser/JSONParser.java b/src2/org/json/simple/parser/JSONParser.java
new file mode 100644 (file)
index 0000000..70e04cc
--- /dev/null
@@ -0,0 +1,611 @@
+/*
+ * $Id: JSONParser.java,v 1.1 2006/04/15 14:10:48 platform Exp $
+ * Created on 2006-4-15
+ */
+package org.json.simple.parser;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+
+/**
+ * Parser for JSON text. Please note that JSONParser is NOT thread-safe.
+ * 
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public class JSONParser
+{
+  public static final int S_INIT = 0;
+
+  public static final int S_IN_FINISHED_VALUE = 1;// string,number,boolean,null,object,array
+
+  public static final int S_IN_OBJECT = 2;
+
+  public static final int S_IN_ARRAY = 3;
+
+  public static final int S_PASSED_PAIR_KEY = 4;
+
+  public static final int S_IN_PAIR_VALUE = 5;
+
+  public static final int S_END = 6;
+
+  public static final int S_IN_ERROR = -1;
+
+  private LinkedList handlerStatusStack;
+
+  private Yylex lexer = new Yylex((Reader) null);
+
+  private Yytoken token = null;
+
+  private int status = S_INIT;
+
+  private int peekStatus(LinkedList statusStack)
+  {
+    if (statusStack.size() == 0)
+      return -1;
+    Integer status = (Integer) statusStack.getFirst();
+    return status.intValue();
+  }
+
+  /**
+   * Reset the parser to the initial state without resetting the underlying
+   * reader.
+   *
+   */
+  public void reset()
+  {
+    token = null;
+    status = S_INIT;
+    handlerStatusStack = null;
+  }
+
+  /**
+   * Reset the parser to the initial state with a new character reader.
+   * 
+   * @param in
+   *          - The new character reader.
+   * @throws IOException
+   * @throws ParseException
+   */
+  public void reset(Reader in)
+  {
+    lexer.yyreset(in);
+    reset();
+  }
+
+  /**
+   * @return The position of the beginning of the current token.
+   */
+  public int getPosition()
+  {
+    return lexer.getPosition();
+  }
+
+  public Object parse(String s) throws ParseException
+  {
+    return parse(s, (ContainerFactory) null);
+  }
+
+  public Object parse(String s, ContainerFactory containerFactory)
+          throws ParseException
+  {
+    StringReader in = new StringReader(s);
+    try
+    {
+      return parse(in, containerFactory);
+    } catch (IOException ie)
+    {
+      /*
+       * Actually it will never happen.
+       */
+      throw new ParseException(-1,
+              ParseException.ERROR_UNEXPECTED_EXCEPTION, ie);
+    }
+  }
+
+  public Object parse(Reader in) throws IOException, ParseException
+  {
+    return parse(in, (ContainerFactory) null);
+  }
+
+  /**
+   * Parse JSON text into java object from the input source.
+   * 
+   * @param in
+   * @param containerFactory
+   *          - Use this factory to createyour own JSON object and JSON array
+   *          containers.
+   * @return Instance of the following: org.json.simple.JSONObject,
+   *         org.json.simple.JSONArray, java.lang.String, java.lang.Number,
+   *         java.lang.Boolean, null
+   * 
+   * @throws IOException
+   * @throws ParseException
+   */
+  public Object parse(Reader in, ContainerFactory containerFactory)
+          throws IOException, ParseException
+  {
+    reset(in);
+    LinkedList statusStack = new LinkedList();
+    LinkedList valueStack = new LinkedList();
+
+    try
+    {
+      do
+      {
+        nextToken();
+        switch (status)
+        {
+        case S_INIT:
+          switch (token.type)
+          {
+          case Yytoken.TYPE_VALUE:
+            status = S_IN_FINISHED_VALUE;
+            statusStack.addFirst(new Integer(status));
+            valueStack.addFirst(token.value);
+            break;
+          case Yytoken.TYPE_LEFT_BRACE:
+            status = S_IN_OBJECT;
+            statusStack.addFirst(new Integer(status));
+            valueStack.addFirst(createObjectContainer(containerFactory));
+            break;
+          case Yytoken.TYPE_LEFT_SQUARE:
+            status = S_IN_ARRAY;
+            statusStack.addFirst(new Integer(status));
+            valueStack.addFirst(createArrayContainer(containerFactory));
+            break;
+          default:
+            status = S_IN_ERROR;
+          }// inner switch
+          break;
+
+        case S_IN_FINISHED_VALUE:
+          if (token.type == Yytoken.TYPE_EOF)
+            return valueStack.removeFirst();
+          else
+            throw new ParseException(getPosition(),
+                    ParseException.ERROR_UNEXPECTED_TOKEN, token);
+
+        case S_IN_OBJECT:
+          switch (token.type)
+          {
+          case Yytoken.TYPE_COMMA:
+            break;
+          case Yytoken.TYPE_VALUE:
+            if (token.value instanceof String)
+            {
+              String key = (String) token.value;
+              valueStack.addFirst(key);
+              status = S_PASSED_PAIR_KEY;
+              statusStack.addFirst(new Integer(status));
+            }
+            else
+            {
+              status = S_IN_ERROR;
+            }
+            break;
+          case Yytoken.TYPE_RIGHT_BRACE:
+            if (valueStack.size() > 1)
+            {
+              statusStack.removeFirst();
+              valueStack.removeFirst();
+              status = peekStatus(statusStack);
+            }
+            else
+            {
+              status = S_IN_FINISHED_VALUE;
+            }
+            break;
+          default:
+            status = S_IN_ERROR;
+            break;
+          }// inner switch
+          break;
+
+        case S_PASSED_PAIR_KEY:
+          switch (token.type)
+          {
+          case Yytoken.TYPE_COLON:
+            break;
+          case Yytoken.TYPE_VALUE:
+            statusStack.removeFirst();
+            String key = (String) valueStack.removeFirst();
+            Map parent = (Map) valueStack.getFirst();
+            parent.put(key, token.value);
+            status = peekStatus(statusStack);
+            break;
+          case Yytoken.TYPE_LEFT_SQUARE:
+            statusStack.removeFirst();
+            key = (String) valueStack.removeFirst();
+            parent = (Map) valueStack.getFirst();
+            List newArray = createArrayContainer(containerFactory);
+            parent.put(key, newArray);
+            status = S_IN_ARRAY;
+            statusStack.addFirst(new Integer(status));
+            valueStack.addFirst(newArray);
+            break;
+          case Yytoken.TYPE_LEFT_BRACE:
+            statusStack.removeFirst();
+            key = (String) valueStack.removeFirst();
+            parent = (Map) valueStack.getFirst();
+            Map newObject = createObjectContainer(containerFactory);
+            parent.put(key, newObject);
+            status = S_IN_OBJECT;
+            statusStack.addFirst(new Integer(status));
+            valueStack.addFirst(newObject);
+            break;
+          default:
+            status = S_IN_ERROR;
+          }
+          break;
+
+        case S_IN_ARRAY:
+          switch (token.type)
+          {
+          case Yytoken.TYPE_COMMA:
+            break;
+          case Yytoken.TYPE_VALUE:
+            List val = (List) valueStack.getFirst();
+            val.add(token.value);
+            break;
+          case Yytoken.TYPE_RIGHT_SQUARE:
+            if (valueStack.size() > 1)
+            {
+              statusStack.removeFirst();
+              valueStack.removeFirst();
+              status = peekStatus(statusStack);
+            }
+            else
+            {
+              status = S_IN_FINISHED_VALUE;
+            }
+            break;
+          case Yytoken.TYPE_LEFT_BRACE:
+            val = (List) valueStack.getFirst();
+            Map newObject = createObjectContainer(containerFactory);
+            val.add(newObject);
+            status = S_IN_OBJECT;
+            statusStack.addFirst(new Integer(status));
+            valueStack.addFirst(newObject);
+            break;
+          case Yytoken.TYPE_LEFT_SQUARE:
+            val = (List) valueStack.getFirst();
+            List newArray = createArrayContainer(containerFactory);
+            val.add(newArray);
+            status = S_IN_ARRAY;
+            statusStack.addFirst(new Integer(status));
+            valueStack.addFirst(newArray);
+            break;
+          default:
+            status = S_IN_ERROR;
+          }// inner switch
+          break;
+        case S_IN_ERROR:
+          throw new ParseException(getPosition(),
+                  ParseException.ERROR_UNEXPECTED_TOKEN, token);
+        }// switch
+        if (status == S_IN_ERROR)
+        {
+          throw new ParseException(getPosition(),
+                  ParseException.ERROR_UNEXPECTED_TOKEN, token);
+        }
+      } while (token.type != Yytoken.TYPE_EOF);
+    } catch (IOException ie)
+    {
+      throw ie;
+    }
+
+    throw new ParseException(getPosition(),
+            ParseException.ERROR_UNEXPECTED_TOKEN, token);
+  }
+
+  private void nextToken() throws ParseException, IOException
+  {
+    token = lexer.yylex();
+    if (token == null)
+      token = new Yytoken(Yytoken.TYPE_EOF, null);
+  }
+
+  private Map createObjectContainer(ContainerFactory containerFactory)
+  {
+    if (containerFactory == null)
+      return new JSONObject();
+    Map m = containerFactory.createObjectContainer();
+
+    if (m == null)
+      return new JSONObject();
+    return m;
+  }
+
+  private List createArrayContainer(ContainerFactory containerFactory)
+  {
+    if (containerFactory == null)
+      return new JSONArray();
+    List l = containerFactory.creatArrayContainer();
+
+    if (l == null)
+      return new JSONArray();
+    return l;
+  }
+
+  public void parse(String s, ContentHandler contentHandler)
+          throws ParseException
+  {
+    parse(s, contentHandler, false);
+  }
+
+  public void parse(String s, ContentHandler contentHandler,
+          boolean isResume) throws ParseException
+  {
+    StringReader in = new StringReader(s);
+    try
+    {
+      parse(in, contentHandler, isResume);
+    } catch (IOException ie)
+    {
+      /*
+       * Actually it will never happen.
+       */
+      throw new ParseException(-1,
+              ParseException.ERROR_UNEXPECTED_EXCEPTION, ie);
+    }
+  }
+
+  public void parse(Reader in, ContentHandler contentHandler)
+          throws IOException, ParseException
+  {
+    parse(in, contentHandler, false);
+  }
+
+  /**
+   * Stream processing of JSON text.
+   * 
+   * @see ContentHandler
+   * 
+   * @param in
+   * @param contentHandler
+   * @param isResume
+   *          - Indicates if it continues previous parsing operation. If set to
+   *          true, resume parsing the old stream, and parameter 'in' will be
+   *          ignored. If this method is called for the first time in this
+   *          instance, isResume will be ignored.
+   * 
+   * @throws IOException
+   * @throws ParseException
+   */
+  public void parse(Reader in, ContentHandler contentHandler,
+          boolean isResume) throws IOException, ParseException
+  {
+    if (!isResume)
+    {
+      reset(in);
+      handlerStatusStack = new LinkedList();
+    }
+    else
+    {
+      if (handlerStatusStack == null)
+      {
+        isResume = false;
+        reset(in);
+        handlerStatusStack = new LinkedList();
+      }
+    }
+
+    LinkedList statusStack = handlerStatusStack;
+
+    try
+    {
+      do
+      {
+        switch (status)
+        {
+        case S_INIT:
+          contentHandler.startJSON();
+          nextToken();
+          switch (token.type)
+          {
+          case Yytoken.TYPE_VALUE:
+            status = S_IN_FINISHED_VALUE;
+            statusStack.addFirst(new Integer(status));
+            if (!contentHandler.primitive(token.value))
+              return;
+            break;
+          case Yytoken.TYPE_LEFT_BRACE:
+            status = S_IN_OBJECT;
+            statusStack.addFirst(new Integer(status));
+            if (!contentHandler.startObject())
+              return;
+            break;
+          case Yytoken.TYPE_LEFT_SQUARE:
+            status = S_IN_ARRAY;
+            statusStack.addFirst(new Integer(status));
+            if (!contentHandler.startArray())
+              return;
+            break;
+          default:
+            status = S_IN_ERROR;
+          }// inner switch
+          break;
+
+        case S_IN_FINISHED_VALUE:
+          nextToken();
+          if (token.type == Yytoken.TYPE_EOF)
+          {
+            contentHandler.endJSON();
+            status = S_END;
+            return;
+          }
+          else
+          {
+            status = S_IN_ERROR;
+            throw new ParseException(getPosition(),
+                    ParseException.ERROR_UNEXPECTED_TOKEN, token);
+          }
+
+        case S_IN_OBJECT:
+          nextToken();
+          switch (token.type)
+          {
+          case Yytoken.TYPE_COMMA:
+            break;
+          case Yytoken.TYPE_VALUE:
+            if (token.value instanceof String)
+            {
+              String key = (String) token.value;
+              status = S_PASSED_PAIR_KEY;
+              statusStack.addFirst(new Integer(status));
+              if (!contentHandler.startObjectEntry(key))
+                return;
+            }
+            else
+            {
+              status = S_IN_ERROR;
+            }
+            break;
+          case Yytoken.TYPE_RIGHT_BRACE:
+            if (statusStack.size() > 1)
+            {
+              statusStack.removeFirst();
+              status = peekStatus(statusStack);
+            }
+            else
+            {
+              status = S_IN_FINISHED_VALUE;
+            }
+            if (!contentHandler.endObject())
+              return;
+            break;
+          default:
+            status = S_IN_ERROR;
+            break;
+          }// inner switch
+          break;
+
+        case S_PASSED_PAIR_KEY:
+          nextToken();
+          switch (token.type)
+          {
+          case Yytoken.TYPE_COLON:
+            break;
+          case Yytoken.TYPE_VALUE:
+            statusStack.removeFirst();
+            status = peekStatus(statusStack);
+            if (!contentHandler.primitive(token.value))
+              return;
+            if (!contentHandler.endObjectEntry())
+              return;
+            break;
+          case Yytoken.TYPE_LEFT_SQUARE:
+            statusStack.removeFirst();
+            statusStack.addFirst(new Integer(S_IN_PAIR_VALUE));
+            status = S_IN_ARRAY;
+            statusStack.addFirst(new Integer(status));
+            if (!contentHandler.startArray())
+              return;
+            break;
+          case Yytoken.TYPE_LEFT_BRACE:
+            statusStack.removeFirst();
+            statusStack.addFirst(new Integer(S_IN_PAIR_VALUE));
+            status = S_IN_OBJECT;
+            statusStack.addFirst(new Integer(status));
+            if (!contentHandler.startObject())
+              return;
+            break;
+          default:
+            status = S_IN_ERROR;
+          }
+          break;
+
+        case S_IN_PAIR_VALUE:
+          /*
+           * S_IN_PAIR_VALUE is just a marker to indicate the end of an object entry, it doesn't proccess any token,
+           * therefore delay consuming token until next round.
+           */
+          statusStack.removeFirst();
+          status = peekStatus(statusStack);
+          if (!contentHandler.endObjectEntry())
+            return;
+          break;
+
+        case S_IN_ARRAY:
+          nextToken();
+          switch (token.type)
+          {
+          case Yytoken.TYPE_COMMA:
+            break;
+          case Yytoken.TYPE_VALUE:
+            if (!contentHandler.primitive(token.value))
+              return;
+            break;
+          case Yytoken.TYPE_RIGHT_SQUARE:
+            if (statusStack.size() > 1)
+            {
+              statusStack.removeFirst();
+              status = peekStatus(statusStack);
+            }
+            else
+            {
+              status = S_IN_FINISHED_VALUE;
+            }
+            if (!contentHandler.endArray())
+              return;
+            break;
+          case Yytoken.TYPE_LEFT_BRACE:
+            status = S_IN_OBJECT;
+            statusStack.addFirst(new Integer(status));
+            if (!contentHandler.startObject())
+              return;
+            break;
+          case Yytoken.TYPE_LEFT_SQUARE:
+            status = S_IN_ARRAY;
+            statusStack.addFirst(new Integer(status));
+            if (!contentHandler.startArray())
+              return;
+            break;
+          default:
+            status = S_IN_ERROR;
+          }// inner switch
+          break;
+
+        case S_END:
+          return;
+
+        case S_IN_ERROR:
+          throw new ParseException(getPosition(),
+                  ParseException.ERROR_UNEXPECTED_TOKEN, token);
+        }// switch
+        if (status == S_IN_ERROR)
+        {
+          throw new ParseException(getPosition(),
+                  ParseException.ERROR_UNEXPECTED_TOKEN, token);
+        }
+      } while (token.type != Yytoken.TYPE_EOF);
+    } catch (IOException ie)
+    {
+      status = S_IN_ERROR;
+      throw ie;
+    } catch (ParseException pe)
+    {
+      status = S_IN_ERROR;
+      throw pe;
+    } catch (RuntimeException re)
+    {
+      status = S_IN_ERROR;
+      throw re;
+    } catch (Error e)
+    {
+      status = S_IN_ERROR;
+      throw e;
+    }
+
+    status = S_IN_ERROR;
+    throw new ParseException(getPosition(),
+            ParseException.ERROR_UNEXPECTED_TOKEN, token);
+  }
+}
diff --git a/src2/org/json/simple/parser/ParseException.java b/src2/org/json/simple/parser/ParseException.java
new file mode 100644 (file)
index 0000000..09b1fd4
--- /dev/null
@@ -0,0 +1,90 @@
+package org.json.simple.parser;
+
+/**
+ * ParseException explains why and where the error occurs in source JSON text.
+ * 
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ *
+ */
+public class ParseException extends Exception {
+       private static final long serialVersionUID = -7880698968187728547L;
+       
+       public static final int ERROR_UNEXPECTED_CHAR = 0;
+       public static final int ERROR_UNEXPECTED_TOKEN = 1;
+       public static final int ERROR_UNEXPECTED_EXCEPTION = 2;
+
+       private int errorType;
+       private Object unexpectedObject;
+       private int position;
+       
+       public ParseException(int errorType){
+               this(-1, errorType, null);
+       }
+       
+       public ParseException(int errorType, Object unexpectedObject){
+               this(-1, errorType, unexpectedObject);
+       }
+       
+       public ParseException(int position, int errorType, Object unexpectedObject){
+               this.position = position;
+               this.errorType = errorType;
+               this.unexpectedObject = unexpectedObject;
+       }
+       
+       public int getErrorType() {
+               return errorType;
+       }
+       
+       public void setErrorType(int errorType) {
+               this.errorType = errorType;
+       }
+       
+       /**
+        * @see org.json.simple.parser.JSONParser#getPosition()
+        * 
+        * @return The character position (starting with 0) of the input where the error occurs.
+        */
+       public int getPosition() {
+               return position;
+       }
+       
+       public void setPosition(int position) {
+               this.position = position;
+       }
+       
+       /**
+        * @see org.json.simple.parser.Yytoken
+        * 
+        * @return One of the following base on the value of errorType:
+        *                      ERROR_UNEXPECTED_CHAR           java.lang.Character
+        *                      ERROR_UNEXPECTED_TOKEN          org.json.simple.parser.Yytoken
+        *                      ERROR_UNEXPECTED_EXCEPTION      java.lang.Exception
+        */
+       public Object getUnexpectedObject() {
+               return unexpectedObject;
+       }
+       
+       public void setUnexpectedObject(Object unexpectedObject) {
+               this.unexpectedObject = unexpectedObject;
+       }
+       
+       public String getMessage() {
+               StringBuffer sb = new StringBuffer();
+               
+               switch(errorType){
+               case ERROR_UNEXPECTED_CHAR:
+                       sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append(".");
+                       break;
+               case ERROR_UNEXPECTED_TOKEN:
+                       sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append(".");
+                       break;
+               case ERROR_UNEXPECTED_EXCEPTION:
+                       sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject);
+                       break;
+               default:
+                       sb.append("Unkown error at position ").append(position).append(".");
+                       break;
+               }
+               return sb.toString();
+       }
+}
diff --git a/src2/org/json/simple/parser/Yylex.java b/src2/org/json/simple/parser/Yylex.java
new file mode 100644 (file)
index 0000000..41569d6
--- /dev/null
@@ -0,0 +1,758 @@
+/* The following code was generated by JFlex 1.4.2 */
+
+package org.json.simple.parser;
+
+class Yylex {
+
+  /** This character denotes the end of file */
+  public static final int YYEOF = -1;
+
+  /** initial size of the lookahead buffer */
+  private static final int ZZ_BUFFERSIZE = 16384;
+
+  /** lexical states */
+  public static final int YYINITIAL = 0;
+  public static final int STRING_BEGIN = 2;
+
+  /**
+   * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
+   * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
+   *                  at the beginning of a line
+   * l is of the form l = 2*k, k a non negative integer
+   */
+  private static final int ZZ_LEXSTATE[] = { 
+     0,  0,  1, 1
+  };
+
+  /** 
+   * Translates characters to character classes
+   */
+  private static final String ZZ_CMAP_PACKED = 
+    "\11\0\1\7\1\7\2\0\1\7\22\0\1\7\1\0\1\11\10\0"+
+    "\1\6\1\31\1\2\1\4\1\12\12\3\1\32\6\0\4\1\1\5"+
+    "\1\1\24\0\1\27\1\10\1\30\3\0\1\22\1\13\2\1\1\21"+
+    "\1\14\5\0\1\23\1\0\1\15\3\0\1\16\1\24\1\17\1\20"+
+    "\5\0\1\25\1\0\1\26\uff82\0";
+
+  /** 
+   * Translates characters to character classes
+   */
+  private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
+
+  /** 
+   * Translates DFA states to action switch labels.
+   */
+  private static final int [] ZZ_ACTION = zzUnpackAction();
+
+  private static final String ZZ_ACTION_PACKED_0 =
+    "\2\0\2\1\1\2\1\3\1\4\3\1\1\5\1\6"+
+    "\1\7\1\10\1\11\1\12\1\13\1\14\1\15\5\0"+
+    "\1\14\1\16\1\17\1\20\1\21\1\22\1\23\1\24"+
+    "\1\0\1\25\1\0\1\25\4\0\1\26\1\27\2\0"+
+    "\1\30";
+
+  private static int [] zzUnpackAction() {
+    int [] result = new int[45];
+    int offset = 0;
+    offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
+    return result;
+  }
+
+  private static int zzUnpackAction(String packed, int offset, int [] result) {
+    int i = 0;       /* index in packed string  */
+    int j = offset;  /* index in unpacked array */
+    int l = packed.length();
+    while (i < l) {
+      int count = packed.charAt(i++);
+      int value = packed.charAt(i++);
+      do result[j++] = value; while (--count > 0);
+    }
+    return j;
+  }
+
+
+  /** 
+   * Translates a state to a row index in the transition table
+   */
+  private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
+
+  private static final String ZZ_ROWMAP_PACKED_0 =
+    "\0\0\0\33\0\66\0\121\0\154\0\207\0\66\0\242"+
+    "\0\275\0\330\0\66\0\66\0\66\0\66\0\66\0\66"+
+    "\0\363\0\u010e\0\66\0\u0129\0\u0144\0\u015f\0\u017a\0\u0195"+
+    "\0\66\0\66\0\66\0\66\0\66\0\66\0\66\0\66"+
+    "\0\u01b0\0\u01cb\0\u01e6\0\u01e6\0\u0201\0\u021c\0\u0237\0\u0252"+
+    "\0\66\0\66\0\u026d\0\u0288\0\66";
+
+  private static int [] zzUnpackRowMap() {
+    int [] result = new int[45];
+    int offset = 0;
+    offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
+    return result;
+  }
+
+  private static int zzUnpackRowMap(String packed, int offset, int [] result) {
+    int i = 0;  /* index in packed string  */
+    int j = offset;  /* index in unpacked array */
+    int l = packed.length();
+    while (i < l) {
+      int high = packed.codePointAt(i++) << 16;
+      result[j++] = high | packed.codePointAt(i++);
+    }
+    return j;
+  }
+
+  /** 
+   * The transition table of the DFA
+   */
+  private static final int ZZ_TRANS [] = {
+    2, 2, 3, 4, 2, 2, 2, 5, 2, 6, 
+    2, 2, 7, 8, 2, 9, 2, 2, 2, 2, 
+    2, 10, 11, 12, 13, 14, 15, 16, 16, 16, 
+    16, 16, 16, 16, 16, 17, 18, 16, 16, 16, 
+    16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 
+    16, 16, 16, 16, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, 4, 19, 20, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, 20, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, 5, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    21, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    23, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, 16, 16, 16, 16, 16, 16, 16, 
+    16, -1, -1, 16, 16, 16, 16, 16, 16, 16, 
+    16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 
+    -1, -1, -1, -1, -1, -1, -1, -1, 24, 25, 
+    26, 27, 28, 29, 30, 31, 32, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    33, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, 34, 35, -1, -1, 
+    34, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    36, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, 37, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, 38, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, 39, -1, 39, -1, 39, -1, -1, 
+    -1, -1, -1, 39, 39, -1, -1, -1, -1, 39, 
+    39, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, 33, -1, 20, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, 20, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, 35, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, 38, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, 40, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, 41, -1, -1, -1, -1, -1, 
+    -1, -1, -1, -1, -1, 42, -1, 42, -1, 42, 
+    -1, -1, -1, -1, -1, 42, 42, -1, -1, -1, 
+    -1, 42, 42, -1, -1, -1, -1, -1, -1, -1, 
+    -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, 
+    -1, -1, 43, 43, -1, -1, -1, -1, 43, 43, 
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, 
+    -1, 44, -1, 44, -1, -1, -1, -1, -1, 44, 
+    44, -1, -1, -1, -1, 44, 44, -1, -1, -1, 
+    -1, -1, -1, -1, -1, 
+  };
+
+  /* error codes */
+  private static final int ZZ_UNKNOWN_ERROR = 0;
+  private static final int ZZ_NO_MATCH = 1;
+  private static final int ZZ_PUSHBACK_2BIG = 2;
+
+  /* error messages for the codes above */
+  private static final String ZZ_ERROR_MSG[] = {
+    "Unkown internal scanner error",
+    "Error: could not match input",
+    "Error: pushback value was too large"
+  };
+
+  /**
+   * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
+   */
+  private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
+
+  private static final String ZZ_ATTRIBUTE_PACKED_0 =
+    "\2\0\1\11\3\1\1\11\3\1\6\11\2\1\1\11"+
+    "\5\0\10\11\1\0\1\1\1\0\1\1\4\0\2\11"+
+    "\2\0\1\11";
+
+  private static int [] zzUnpackAttribute() {
+    int [] result = new int[45];
+    int offset = 0;
+    offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
+    return result;
+  }
+
+  private static int zzUnpackAttribute(String packed, int offset, int [] result) {
+    int i = 0;       /* index in packed string  */
+    int j = offset;  /* index in unpacked array */
+    int l = packed.length();
+    while (i < l) {
+      int count = packed.charAt(i++);
+      int value = packed.charAt(i++);
+      do result[j++] = value; while (--count > 0);
+    }
+    return j;
+  }
+
+  /** the input device */
+  private java.io.Reader zzReader;
+
+  /** the current state of the DFA */
+  private int zzState;
+
+  /** the current lexical state */
+  private int zzLexicalState = YYINITIAL;
+
+  /** this buffer contains the current text to be matched and is
+      the source of the yytext() string */
+  private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
+
+  /** the textposition at the last accepting state */
+  private int zzMarkedPos;
+
+  /** the current text position in the buffer */
+  private int zzCurrentPos;
+
+  /** startRead marks the beginning of the yytext() string in the buffer */
+  private int zzStartRead;
+
+  /** endRead marks the last character in the buffer, that has been read
+      from input */
+  private int zzEndRead;
+
+  /** number of newlines encountered up to the start of the matched text */
+  private int yyline;
+
+  /** the number of characters up to the start of the matched text */
+  private int yychar;
+
+  /**
+   * the number of characters from the last newline up to the start of the 
+   * matched text
+   */
+  private int yycolumn;
+
+  /** 
+   * zzAtBOL == true <=> the scanner is currently at the beginning of a line
+   */
+  private boolean zzAtBOL = true;
+
+  /** zzAtEOF == true <=> the scanner is at the EOF */
+  private boolean zzAtEOF;
+
+  /* user code: */
+private StringBuffer sb=new StringBuffer();
+
+int getPosition(){
+       return yychar;
+}
+
+
+
+  /**
+   * Creates a new scanner
+   * There is also a java.io.InputStream version of this constructor.
+   *
+   * @param   in  the java.io.Reader to read input from.
+   */
+  Yylex(java.io.Reader in) {
+    this.zzReader = in;
+  }
+
+  /**
+   * Creates a new scanner.
+   * There is also java.io.Reader version of this constructor.
+   *
+   * @param   in  the java.io.Inputstream to read input from.
+   */
+  Yylex(java.io.InputStream in) {
+    this(new java.io.InputStreamReader(in));
+  }
+
+  /** 
+   * Unpacks the compressed character translation table.
+   *
+   * @param packed   the packed character translation table
+   * @return         the unpacked character translation table
+   */
+  private static char [] zzUnpackCMap(String packed) {
+    char [] map = new char[0x10000];
+    int i = 0;  /* index in packed string  */
+    int j = 0;  /* index in unpacked array */
+    while (i < 90) {
+      int  count = packed.charAt(i++);
+      char value = packed.charAt(i++);
+      do map[j++] = value; while (--count > 0);
+    }
+    return map;
+  }
+
+
+  /**
+   * Refills the input buffer.
+   *
+   * @return      <code>false</code>, iff there was new input.
+   * 
+   * @exception   java.io.IOException  if any I/O-Error occurs
+   */
+  private boolean zzRefill() throws java.io.IOException {
+
+    /* first: make room (if you can) */
+    if (zzStartRead > 0) {
+      System.arraycopy(zzBuffer, zzStartRead,
+                       zzBuffer, 0,
+                       zzEndRead-zzStartRead);
+
+      /* translate stored positions */
+      zzEndRead-= zzStartRead;
+      zzCurrentPos-= zzStartRead;
+      zzMarkedPos-= zzStartRead;
+      zzStartRead = 0;
+    }
+
+    /* is the buffer big enough? */
+    if (zzCurrentPos >= zzBuffer.length) {
+      /* if not: blow it up */
+      char newBuffer[] = new char[zzCurrentPos*2];
+      System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
+      zzBuffer = newBuffer;
+    }
+
+    /* finally: fill the buffer with new input */
+    int numRead = zzReader.read(zzBuffer, zzEndRead,
+                                            zzBuffer.length-zzEndRead);
+
+    if (numRead > 0) {
+      zzEndRead+= numRead;
+      return false;
+    }
+    // unlikely but not impossible: read 0 characters, but not at end of stream    
+    if (numRead == 0) {
+      int c = zzReader.read();
+      if (c == -1) {
+        return true;
+      } else {
+        zzBuffer[zzEndRead++] = (char) c;
+        return false;
+      }     
+    }
+
+       // numRead < 0
+    return true;
+  }
+
+    
+  /**
+   * Closes the input stream.
+   */
+  public final void yyclose() throws java.io.IOException {
+    zzAtEOF = true;            /* indicate end of file */
+    zzEndRead = zzStartRead;  /* invalidate buffer    */
+
+    if (zzReader != null)
+      zzReader.close();
+  }
+
+
+  /**
+   * Resets the scanner to read from a new input stream.
+   * Does not close the old reader.
+   *
+   * All internal variables are reset, the old input stream 
+   * <b>cannot</b> be reused (internal buffer is discarded and lost).
+   * Lexical state is set to <tt>ZZ_INITIAL</tt>.
+   *
+   * @param reader   the new input stream 
+   */
+  public final void yyreset(java.io.Reader reader) {
+    zzReader = reader;
+    zzAtBOL  = true;
+    zzAtEOF  = false;
+    zzEndRead = zzStartRead = 0;
+    zzCurrentPos = zzMarkedPos = 0;
+    yyline = yychar = yycolumn = 0;
+    zzLexicalState = YYINITIAL;
+  }
+
+
+  /**
+   * Returns the current lexical state.
+   */
+  public final int yystate() {
+    return zzLexicalState;
+  }
+
+
+  /**
+   * Enters a new lexical state
+   *
+   * @param newState the new lexical state
+   */
+  public final void yybegin(int newState) {
+    zzLexicalState = newState;
+  }
+
+
+  /**
+   * Returns the text matched by the current regular expression.
+   */
+  public final String yytext() {
+    return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
+  }
+
+
+  /**
+   * Returns the character at position <tt>pos</tt> from the 
+   * matched text. 
+   * 
+   * It is equivalent to yytext().charAt(pos), but faster
+   *
+   * @param pos the position of the character to fetch. 
+   *            A value from 0 to yylength()-1.
+   *
+   * @return the character at position pos
+   */
+  public final char yycharat(int pos) {
+    return zzBuffer[zzStartRead+pos];
+  }
+
+
+  /**
+   * Returns the length of the matched text region.
+   */
+  public final int yylength() {
+    return zzMarkedPos-zzStartRead;
+  }
+
+
+  /**
+   * Reports an error that occured while scanning.
+   *
+   * In a wellformed scanner (no or only correct usage of 
+   * yypushback(int) and a match-all fallback rule) this method 
+   * will only be called with things that "Can't Possibly Happen".
+   * If this method is called, something is seriously wrong
+   * (e.g. a JFlex bug producing a faulty scanner etc.).
+   *
+   * Usual syntax/scanner level error handling should be done
+   * in error fallback rules.
+   *
+   * @param   errorCode  the code of the errormessage to display
+   */
+  private void zzScanError(int errorCode) {
+    String message;
+    try {
+      message = ZZ_ERROR_MSG[errorCode];
+    }
+    catch (ArrayIndexOutOfBoundsException e) {
+      message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
+    }
+
+    throw new Error(message);
+  } 
+
+
+  /**
+   * Pushes the specified amount of characters back into the input stream.
+   *
+   * They will be read again by then next call of the scanning method
+   *
+   * @param number  the number of characters to be read again.
+   *                This number must not be greater than yylength()!
+   */
+  public void yypushback(int number)  {
+    if ( number > yylength() )
+      zzScanError(ZZ_PUSHBACK_2BIG);
+
+    zzMarkedPos -= number;
+  }
+
+
+  /**
+   * Resumes scanning until the next regular expression is matched, the end of
+   * input is encountered or an I/O-Error occurs.
+   *
+   * @return the next token
+   * @exception java.io.IOException
+   *              if any I/O-Error occurs
+   */
+  public Yytoken yylex() throws java.io.IOException, ParseException
+  {
+    int zzInput;
+    int zzAction;
+
+    // cached fields:
+    int zzCurrentPosL;
+    int zzMarkedPosL;
+    int zzEndReadL = zzEndRead;
+    char[] zzBufferL = zzBuffer;
+    char[] zzCMapL = ZZ_CMAP;
+
+    int[] zzTransL = ZZ_TRANS;
+    int[] zzRowMapL = ZZ_ROWMAP;
+    int[] zzAttrL = ZZ_ATTRIBUTE;
+
+    while (true)
+    {
+      zzMarkedPosL = zzMarkedPos;
+
+      yychar += zzMarkedPosL - zzStartRead;
+
+      zzAction = -1;
+
+      zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
+
+      zzState = ZZ_LEXSTATE[zzLexicalState];
+
+      zzForAction:
+      {
+        while (true)
+        {
+
+          if (zzCurrentPosL < zzEndReadL)
+            zzInput = zzBufferL[zzCurrentPosL++];
+          else if (zzAtEOF)
+          {
+            zzInput = YYEOF;
+            break zzForAction;
+          }
+          else
+          {
+            // store back cached positions
+            zzCurrentPos = zzCurrentPosL;
+            zzMarkedPos = zzMarkedPosL;
+            boolean eof = zzRefill();
+            // get translated positions and possibly new buffer
+            zzCurrentPosL = zzCurrentPos;
+            zzMarkedPosL = zzMarkedPos;
+            zzBufferL = zzBuffer;
+            zzEndReadL = zzEndRead;
+            if (eof)
+            {
+              zzInput = YYEOF;
+              break zzForAction;
+            }
+            else
+            {
+              zzInput = zzBufferL[zzCurrentPosL++];
+            }
+          }
+          int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]];
+          if (zzNext == -1)
+            break zzForAction;
+          zzState = zzNext;
+
+          int zzAttributes = zzAttrL[zzState];
+          if ((zzAttributes & 1) == 1)
+          {
+            zzAction = zzState;
+            zzMarkedPosL = zzCurrentPosL;
+            if ((zzAttributes & 8) == 8)
+              break zzForAction;
+          }
+
+        }
+      }
+
+      // store back cached position
+      zzMarkedPos = zzMarkedPosL;
+      switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction])
+      {
+      case 11:
+      {
+        sb.append(yytext());
+      }
+      case 25:
+        break;
+      case 4:
+      {
+        sb = null;
+        sb = new StringBuffer();
+        yybegin(STRING_BEGIN);
+      }
+      case 26:
+        break;
+      case 16:
+      {
+        sb.append('\b');
+      }
+      case 27:
+        break;
+      case 6:
+      {
+        return new Yytoken(Yytoken.TYPE_RIGHT_BRACE, null);
+      }
+      case 28:
+        break;
+      case 23:
+      {
+        Boolean val = Boolean.valueOf(yytext());
+        return new Yytoken(Yytoken.TYPE_VALUE, val);
+      }
+      case 29:
+        break;
+      case 22:
+      {
+        return new Yytoken(Yytoken.TYPE_VALUE, null);
+      }
+      case 30:
+        break;
+      case 13:
+      {
+        yybegin(YYINITIAL);
+        return new Yytoken(Yytoken.TYPE_VALUE, sb.toString());
+      }
+      case 31:
+        break;
+      case 12:
+      {
+        sb.append('\\');
+      }
+      case 32:
+        break;
+      case 21:
+      {
+        Double val = Double.valueOf(yytext());
+        return new Yytoken(Yytoken.TYPE_VALUE, val);
+      }
+      case 33:
+        break;
+      case 1:
+      {
+        throw new ParseException(yychar,
+                ParseException.ERROR_UNEXPECTED_CHAR,
+                new Character(yycharat(0)));
+      }
+      case 34:
+        break;
+      case 8:
+      {
+        return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE, null);
+      }
+      case 35:
+        break;
+      case 19:
+      {
+        sb.append('\r');
+      }
+      case 36:
+        break;
+      case 15:
+      {
+        sb.append('/');
+      }
+      case 37:
+        break;
+      case 10:
+      {
+        return new Yytoken(Yytoken.TYPE_COLON, null);
+      }
+      case 38:
+        break;
+      case 14:
+      {
+        sb.append('"');
+      }
+      case 39:
+        break;
+      case 5:
+      {
+        return new Yytoken(Yytoken.TYPE_LEFT_BRACE, null);
+      }
+      case 40:
+        break;
+      case 17:
+      {
+        sb.append('\f');
+      }
+      case 41:
+        break;
+      case 24:
+      {
+        try
+        {
+          int ch = Integer.parseInt(yytext().substring(2), 16);
+          sb.append((char) ch);
+        } catch (Exception e)
+        {
+          throw new ParseException(yychar,
+                  ParseException.ERROR_UNEXPECTED_EXCEPTION, e);
+        }
+      }
+      case 42:
+        break;
+      case 20:
+      {
+        sb.append('\t');
+      }
+      case 43:
+        break;
+      case 7:
+      {
+        return new Yytoken(Yytoken.TYPE_LEFT_SQUARE, null);
+      }
+      case 44:
+        break;
+      case 2:
+      {
+        Long val = Long.valueOf(yytext());
+        return new Yytoken(Yytoken.TYPE_VALUE, val);
+      }
+      case 45:
+        break;
+      case 18:
+      {
+        sb.append('\n');
+      }
+      case 46:
+        break;
+      case 9:
+      {
+        return new Yytoken(Yytoken.TYPE_COMMA, null);
+      }
+      case 47:
+        break;
+      case 3:
+      {
+      }
+      case 48:
+        break;
+      default:
+        if (zzInput == YYEOF && zzStartRead == zzCurrentPos)
+        {
+          zzAtEOF = true;
+          return null;
+        }
+        else
+        {
+          zzScanError(ZZ_NO_MATCH);
+        }
+      }
+    }
+  }
+
+
+}
diff --git a/src2/org/json/simple/parser/Yytoken.java b/src2/org/json/simple/parser/Yytoken.java
new file mode 100644 (file)
index 0000000..9d7e7e7
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * $Id: Yytoken.java,v 1.1 2006/04/15 14:10:48 platform Exp $
+ * Created on 2006-4-15
+ */
+package org.json.simple.parser;
+
+/**
+ * @author FangYidong<fangyidong@yahoo.com.cn>
+ */
+public class Yytoken {
+       public static final int TYPE_VALUE=0;//JSON primitive value: string,number,boolean,null
+       public static final int TYPE_LEFT_BRACE=1;
+       public static final int TYPE_RIGHT_BRACE=2;
+       public static final int TYPE_LEFT_SQUARE=3;
+       public static final int TYPE_RIGHT_SQUARE=4;
+       public static final int TYPE_COMMA=5;
+       public static final int TYPE_COLON=6;
+       public static final int TYPE_EOF=-1;//end of file
+       
+       public int type=0;
+       public Object value=null;
+       
+       public Yytoken(int type,Object value){
+               this.type=type;
+               this.value=value;
+       }
+       
+       public String toString(){
+               StringBuffer sb = new StringBuffer();
+               switch(type){
+               case TYPE_VALUE:
+                       sb.append("VALUE(").append(value).append(")");
+                       break;
+               case TYPE_LEFT_BRACE:
+                       sb.append("LEFT BRACE({)");
+                       break;
+               case TYPE_RIGHT_BRACE:
+                       sb.append("RIGHT BRACE(})");
+                       break;
+               case TYPE_LEFT_SQUARE:
+                       sb.append("LEFT SQUARE([)");
+                       break;
+               case TYPE_RIGHT_SQUARE:
+                       sb.append("RIGHT SQUARE(])");
+                       break;
+               case TYPE_COMMA:
+                       sb.append("COMMA(,)");
+                       break;
+               case TYPE_COLON:
+                       sb.append("COLON(:)");
+                       break;
+               case TYPE_EOF:
+                       sb.append("END OF FILE");
+                       break;
+               }
+               return sb.toString();
+       }
+}
diff --git a/srcjar2/README_SWINGJS.txt b/srcjar2/README_SWINGJS.txt
new file mode 100644 (file)
index 0000000..5dfd949
--- /dev/null
@@ -0,0 +1,7 @@
+The srcjar2 directory just holds Java source for third-party dependency
+jar files used by the Java version of Jalview that are not used in JavaScript 
+or at least have not been used yet. 
+
+org.apache.log4j -- minimal implementation already in jalview/javascript
+
+BH 2018.07.20
\ No newline at end of file
index ae9a580..f45850b 100644 (file)
@@ -1,13 +1,8 @@
-see 
+The swingjs directory contains the current transpiler (net.sf.j2s.core.jar) 
+and the run-time core site files (SwingJS-site.zip)
 
-https://github.com/BobHanson/java2script/blob/master/sources/net.sf.j2s.core/src/net/sf/j2s/core/astvisitors/Java2ScriptVisitor.java
+In addition are version directories -- for example, ver/3.1.1 and ver/3.2.1
 
-for full list of changes
+The second of these, ver/3.2.1, adds Java 8 functionality.
 
-recent changes in June 2018:
 
-// BH 6/25/2018 -- synchronized(a = new Object()) {...} ---> ...; only if an assignment or not a simple function call to Object.getTreeLock()
-// BH 6/23/2018 -- synchronized(a = new Object()) {...} ---> if(!(a = new Object()) {throw new NullPointerException()}else{...}
-// BH 6/21/2018 -- CharSequence.subSequence() should be defined both subSequence$I$I and subSequence
-// BH 6/20/2018 -- fixes for (int var : new int[] {3,4,5}) becoming for var var
-// BH 6/19/2018 -- adds .j2s j2s.class.replacements=org.apache.log4j.->jalview.javascript.log4j.;
index 447678e..c1dfcb3 100644 (file)
Binary files a/swingjs/SwingJS-site.zip and b/swingjs/SwingJS-site.zip differ
index 1872708..2a700c4 100644 (file)
Binary files a/swingjs/net.sf.j2s.core.jar and b/swingjs/net.sf.j2s.core.jar differ
diff --git a/swingjs/ver/3.1.1/SwingJS-site.zip b/swingjs/ver/3.1.1/SwingJS-site.zip
new file mode 100644 (file)
index 0000000..447678e
Binary files /dev/null and b/swingjs/ver/3.1.1/SwingJS-site.zip differ
diff --git a/swingjs/ver/3.2.1/SwingJS-site.zip b/swingjs/ver/3.2.1/SwingJS-site.zip
new file mode 100644 (file)
index 0000000..c1dfcb3
Binary files /dev/null and b/swingjs/ver/3.2.1/SwingJS-site.zip differ
index 1872708..2a700c4 100644 (file)
Binary files a/swingjs/ver/3.2.1/net.sf.j2s.core_3.2.1.jar and b/swingjs/ver/3.2.1/net.sf.j2s.core_3.2.1.jar differ