From 1f1e85c452a1feb9e2d672fe8849b9a50eb55c35 Mon Sep 17 00:00:00 2001 From: wjrl Date: Mon, 27 Feb 2017 23:22:08 -0800 Subject: [PATCH] Revert "Sprint2" --- .gitignore | 20 +- README.md | 6 +- src/.gitignore | 1 - src/org/.gitignore | 1 - .../biofabric/analysis/CycleFinder.java | 160 - .../biofabric/analysis/GraphSearcher.java | 1060 ---- .../biofabric/analysis/NIDLink.java | 99 - .../biofabric/analysis/NetworkAlignment.java | 3363 ------------- .../biofabric/app/BioFabricWindow.java | 498 -- .../biofabric/cmd/CommandSet.java | 4344 ---------------- .../biofabric/layouts/ControlTopLayout.java | 440 -- .../biofabric/layouts/DefaultEdgeLayout.java | 416 -- .../biofabric/layouts/DefaultLayout.java | 321 -- .../biofabric/layouts/ElementRatios.java | 190 - .../biofabric/layouts/GluOleNodeOrder.java | 344 -- .../biofabric/layouts/HierDAGLayout.java | 384 -- .../biofabric/layouts/NodeClusterLayout.java | 653 --- .../layouts/ProcessWorldBankCSV.java | 277 -- .../biofabric/layouts/WordLinkComm.java | 494 -- .../ui/dialogs/BreadthFirstLayoutDialog.java | 180 - .../ui/dialogs/ClusterLayoutSetupDialog.java | 314 -- .../ui/dialogs/LinkGroupingSetupDialog.java | 359 -- .../ui/dialogs/NetworkAlignmentDialog.java | 484 -- .../ui/display/BioFabricNavAndControl.java | 292 -- .../biofabric/ui/display/FabricNavTool.java | 918 ---- .../ui/display/MouseOverViewPanel.java | 320 -- .../systemsbiology/biofabric/util/NID.java | 187 - .../biofabric/util/TrueObjChoiceContent.java | 96 - src/org/systemsbiology/biotapestry/.gitignore | 1 - .../analysis/Link.java | 25 +- .../biotapestry/biofabric/.gitignore | 1 - .../biofabric}/AttributeLoader.java | 75 +- .../biofabric}/BioFabric.properties | 54 +- .../biofabric}/BioFabricApplication.java | 161 +- .../biofabric/BioFabricNavAndControl.java | 182 + .../biofabric}/BioFabricNetwork.java | 2120 ++++---- .../biofabric}/BioFabricOverview.java | 425 +- .../biofabric}/BioFabricPanel.java | 655 ++- .../biofabric/BioFabricWindow.java | 552 +++ .../biofabric}/BrowserLauncher.java | 24 +- .../biofabric}/BufBuildDrawer.java | 2 +- .../biofabric}/BufferBuilder.java | 268 +- .../biofabric/ClusteredLayout.java} | 769 ++- .../ClusteredLayoutParamsDialog.java} | 33 +- .../biofabric}/CompareNodesSetupDialog.java | 152 +- .../biofabric/DeadFabricGoose.java | 194 + .../biofabric}/FabricColorGenerator.java | 55 +- .../biotapestry/biofabric/FabricCommands.java | 4385 ++++++++++++++++- .../biofabric}/FabricDisplayOptions.java | 167 +- .../FabricDisplayOptionsDialog.java | 56 +- .../FabricDisplayOptionsManager.java | 15 +- .../biofabric}/FabricFactory.java | 44 +- .../biotapestry/biofabric/FabricGoose.java | 695 +++ .../biofabric/FabricGooseInterface.java | 133 + .../biofabric/FabricGooseManager.java} | 136 +- .../biofabric}/FabricLink.java | 179 +- .../biofabric}/FabricLocation.java | 17 +- .../biofabric}/FabricMagnifier.java | 89 +- .../biofabric}/FabricMagnifyingTool.java | 223 +- .../biotapestry/biofabric/FabricNavTool.java | 513 ++ .../biofabric}/FabricSIFLoader.java | 98 +- .../biofabric}/FabricSearchDialog.java | 28 +- .../biofabric}/ImageCache.java | 44 +- .../biofabric/InboundConnectionOp.java | 57 + .../biofabric/InboundGaggleOp.java | 65 + .../biofabric/InboundNetworkOp.java | 72 + .../biofabric/InboundSelectionOp.java | 62 + .../biofabric/LinkGroupingSetupDialog.java | 295 ++ .../biofabric}/PaintCache.java | 375 +- .../biofabric}/PopupMenuControl.java | 56 +- .../biofabric}/RelationDirectionDialog.java | 141 +- .../biofabric}/ReorderLayoutParamsDialog.java | 21 +- .../biofabric/SelectionSupport.java | 381 ++ .../biofabric}/UpdateJavaDialog.java | 4 +- .../biofabric/images/About24.gif | Bin .../biofabric/images/Back24.gif | Bin .../biofabric/images/BioFab16White.gif | Bin .../biofabric/images/C24.gif | Bin .../images/ClearFabricSelected24.gif | Bin .../biofabric/images/D24.gif | Bin .../biofabric/images/Find24.gif | Bin .../biofabric/images/Forward24.gif | Bin .../biofabric/images/H24.gif | Bin .../biofabric/images/L24.gif | Bin .../biofabric/images/MacBlank.gif | Bin .../biofabric/images/MacC.gif | Bin .../biofabric/images/MacD.gif | Bin .../biofabric/images/MacGT.gif | Bin .../biofabric/images/MacL.gif | Bin .../biofabric/images/MacLT.gif | Bin .../biofabric/images/MacN.gif | Bin .../biofabric/images/MacR.gif | Bin .../biofabric/images/MacS.gif | Bin .../biofabric/images/MacU.gif | Bin .../biofabric/images/MacZ.gif | Bin .../biofabric/images/N24.gif | Bin .../biofabric/images/P24.gif | Bin .../biofabric/images/P24Selected.gif | Bin .../biofabric/images/PlusOneDeg24.gif | Bin .../biofabric/images/Print24.gif | Bin .../biofabric/images/PropagateSelected24.gif | Bin .../biofabric/images/S24.gif | Bin .../biofabric/images/Save24.gif | Bin .../biofabric/images/SaveAs24.gif | Bin .../biofabric/images/Stop24.gif | Bin .../biofabric/images/U24.gif | Bin .../biofabric/images/U24Selected.gif | Bin .../biofabric/images/ZoomIn24.gif | Bin .../biofabric/images/ZoomOut24.gif | Bin .../biofabric/images/ZoomToAllFabric24.gif | Bin .../images/ZoomToAllFabricSelected24.gif | Bin .../biofabric/images/ZoomToFabricRect24.gif | Bin .../images/ZoomToFabricSelected24.gif | Bin .../biofabric/license/LICENSE | 0 .../biofabric/license/LICENSE-SUN | 0 .../biofabric/license/about.html | 0 .../cmd/BTUndoCmd.java | 2 +- .../cmd/CompoundPostEventCmd2.java | 36 +- .../cmd/CompoundPreEventCmd.java | 28 +- .../cmd/ZoomChangeTracker.java | 2 +- .../cmd/ZoomCommandSupport.java | 61 +- .../cmd/ZoomTarget.java | 18 +- .../db/ColorGenerator.java | 54 +- .../db/GlobalChange.java | 10 +- .../db/SimpleWorkspaceSource.java | 2 +- .../db/Workspace.java | 12 +- .../event/ChangeEvent.java | 2 +- .../event/EventManager.java | 128 +- .../biotapestry/event/GeneralChangeEvent.java | 97 + .../event/GeneralChangeListener.java | 43 + .../event/LayoutChangeEvent.java | 2 +- .../event/LayoutChangeListener.java | 2 +- .../biotapestry/event/ModelChangeEvent.java | 204 + .../event/ModelChangeListener.java | 50 + .../event/OverlayDisplayChangeEvent.java | 96 + .../event/OverlayDisplayChangeListener.java | 43 + .../event/SelectionChangeEvent.java | 2 +- .../event/SelectionChangeListener.java | 2 +- .../images/CrossCursor32.gif | Bin .../images/ErrorCursor32.gif | Bin .../parser/AbstractFactoryClient.java | 28 +- .../parser/GlueStick.java | 2 +- .../parser/ParserClient.java | 4 +- .../parser/SUParser.java | 30 +- .../ui/BasicZoomTargetSupport.java | 43 +- .../ui/CursorManager.java | 6 +- .../ui/ImageExporter.java | 18 +- .../ui/NamedColor.java | 4 +- .../ui/ZoomPresentation.java | 9 +- .../ui/dialogs/ExceptionDialog.java | 21 +- .../ui/dialogs/ExportSettingsDialog.java | 46 +- .../dialogs/ExportSettingsPublishDialog.java | 12 +- .../dialogs/utils/BTStashResultsDialog.java | 16 +- .../ui/dialogs/utils/DialogSupport.java | 18 +- .../ui/dialogs/utils/EditableTable.java | 463 +- .../biotapestry/util/AffineCombination.java | 639 +++ .../util/AsynchExitRequestException.java | 2 +- .../util/AttributeExtractor.java | 2 +- .../util/BTProgressMonitor.java | 2 +- .../util/BackgroundWorker.java | 2 +- .../util/BackgroundWorkerClient.java | 4 +- .../util/BackgroundWorkerControlManager.java | 2 +- .../util/BackgroundWorkerOwner.java | 2 +- .../util/CharacterEntityMapper.java | 7 +- .../util/ChoiceContent.java | 2 +- .../util/ColorLabel.java | 2 +- .../util/ColorListRenderer.java | 2 +- .../util/ComboBoxEditor.java | 2 +- .../util/ComboBoxEditorTracker.java | 2 +- .../util/ComboFinishedTracker.java | 2 +- .../util/DataUtil.java | 10 +- .../util/DoubMinMax.java | 2 +- .../util/DoubleEditor.java | 2 +- .../util/EditableComboBoxEditor.java | 22 +- .../util/EditableComboBoxEditorTracker.java | 2 +- .../util/EnumCell.java | 47 +- .../util/ExceptionHandler.java | 4 +- .../util/FactoryUtilWhiteboard.java | 4 +- .../util/FileExtensionFilters.java | 2 +- .../util/FixedJButton.java | 12 +- .../util/FixedJComboBox.java | 2 +- .../util/GoodnessChart.java | 2 +- .../util/Indenter.java | 2 +- .../util/IntegerEditor.java | 2 +- .../util/InvalidInputException.java | 2 +- .../util/MinMax.java | 26 +- .../util/NumberEditor.java | 2 +- .../util/NumberEditorTracker.java | 2 +- .../util/ObjChoiceContent.java | 2 +- .../util/ProtoDouble.java | 2 +- .../util/ProtoInteger.java | 2 +- .../util/ResourceManager.java | 32 +- .../util/TaggedSet.java | 6 +- .../util/TextEditor.java | 2 +- .../util/TextEditorTracker.java | 2 +- .../util/TextFinishedTracker.java | 2 +- .../util/TrackingUnit.java | 2 +- .../util/UiUtil.java | 7 +- .../util/UndoSupport.java | 10 +- .../util/UniqueLabeller.java | 10 +- .../util/Vector2D.java | 2 +- 201 files changed, 12186 insertions(+), 20652 deletions(-) delete mode 100644 src/.gitignore delete mode 100644 src/org/.gitignore delete mode 100644 src/org/systemsbiology/biofabric/analysis/CycleFinder.java delete mode 100644 src/org/systemsbiology/biofabric/analysis/GraphSearcher.java delete mode 100644 src/org/systemsbiology/biofabric/analysis/NIDLink.java delete mode 100644 src/org/systemsbiology/biofabric/analysis/NetworkAlignment.java delete mode 100644 src/org/systemsbiology/biofabric/app/BioFabricWindow.java delete mode 100644 src/org/systemsbiology/biofabric/cmd/CommandSet.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/ControlTopLayout.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/DefaultEdgeLayout.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/DefaultLayout.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/ElementRatios.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/GluOleNodeOrder.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/HierDAGLayout.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/NodeClusterLayout.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/ProcessWorldBankCSV.java delete mode 100644 src/org/systemsbiology/biofabric/layouts/WordLinkComm.java delete mode 100644 src/org/systemsbiology/biofabric/ui/dialogs/BreadthFirstLayoutDialog.java delete mode 100644 src/org/systemsbiology/biofabric/ui/dialogs/ClusterLayoutSetupDialog.java delete mode 100644 src/org/systemsbiology/biofabric/ui/dialogs/LinkGroupingSetupDialog.java delete mode 100644 src/org/systemsbiology/biofabric/ui/dialogs/NetworkAlignmentDialog.java delete mode 100644 src/org/systemsbiology/biofabric/ui/display/BioFabricNavAndControl.java delete mode 100644 src/org/systemsbiology/biofabric/ui/display/FabricNavTool.java delete mode 100644 src/org/systemsbiology/biofabric/ui/display/MouseOverViewPanel.java delete mode 100644 src/org/systemsbiology/biofabric/util/NID.java delete mode 100644 src/org/systemsbiology/biofabric/util/TrueObjChoiceContent.java delete mode 100644 src/org/systemsbiology/biotapestry/.gitignore rename src/org/systemsbiology/{biofabric => biotapestry}/analysis/Link.java (84%) delete mode 100644 src/org/systemsbiology/biotapestry/biofabric/.gitignore rename src/org/systemsbiology/{biofabric/io => biotapestry/biofabric}/AttributeLoader.java (68%) rename src/org/systemsbiology/{biofabric/props => biotapestry/biofabric}/BioFabric.properties (91%) rename src/org/systemsbiology/{biofabric/app => biotapestry/biofabric}/BioFabricApplication.java (69%) create mode 100644 src/org/systemsbiology/biotapestry/biofabric/BioFabricNavAndControl.java rename src/org/systemsbiology/{biofabric/model => biotapestry/biofabric}/BioFabricNetwork.java (50%) rename src/org/systemsbiology/{biofabric/ui/display => biotapestry/biofabric}/BioFabricOverview.java (51%) rename src/org/systemsbiology/{biofabric/ui/display => biotapestry/biofabric}/BioFabricPanel.java (82%) create mode 100644 src/org/systemsbiology/biotapestry/biofabric/BioFabricWindow.java rename src/org/systemsbiology/{biofabric/ui => biotapestry/biofabric}/BrowserLauncher.java (84%) rename src/org/systemsbiology/{biofabric/ui/render => biotapestry/biofabric}/BufBuildDrawer.java (96%) rename src/org/systemsbiology/{biofabric/ui/render => biotapestry/biofabric}/BufferBuilder.java (62%) rename src/org/systemsbiology/{biofabric/layouts/NodeSimilarityLayout.java => biotapestry/biofabric/ClusteredLayout.java} (50%) rename src/org/systemsbiology/{biofabric/ui/dialogs/NodeSimilarityLayoutSetupDialog.java => biotapestry/biofabric/ClusteredLayoutParamsDialog.java} (86%) rename src/org/systemsbiology/{biofabric/ui/dialogs => biotapestry/biofabric}/CompareNodesSetupDialog.java (58%) create mode 100644 src/org/systemsbiology/biotapestry/biofabric/DeadFabricGoose.java rename src/org/systemsbiology/{biofabric/ui => biotapestry/biofabric}/FabricColorGenerator.java (85%) mode change 100755 => 100644 src/org/systemsbiology/biotapestry/biofabric/FabricCommands.java rename src/org/systemsbiology/{biofabric/ui => biotapestry/biofabric}/FabricDisplayOptions.java (72%) rename src/org/systemsbiology/{biofabric/ui/dialogs => biotapestry/biofabric}/FabricDisplayOptionsDialog.java (84%) rename src/org/systemsbiology/{biofabric/ui => biotapestry/biofabric}/FabricDisplayOptionsManager.java (92%) rename src/org/systemsbiology/{biofabric/io => biotapestry/biofabric}/FabricFactory.java (78%) create mode 100644 src/org/systemsbiology/biotapestry/biofabric/FabricGoose.java create mode 100644 src/org/systemsbiology/biotapestry/biofabric/FabricGooseInterface.java rename src/org/systemsbiology/{biofabric/ui/display/MouseOverView.java => biotapestry/biofabric/FabricGooseManager.java} (54%) rename src/org/systemsbiology/{biofabric/model => biotapestry/biofabric}/FabricLink.java (55%) rename src/org/systemsbiology/{biofabric/ui/display => biotapestry/biofabric}/FabricLocation.java (85%) rename src/org/systemsbiology/{biofabric/ui/display => biotapestry/biofabric}/FabricMagnifier.java (84%) rename src/org/systemsbiology/{biofabric/ui/display => biotapestry/biofabric}/FabricMagnifyingTool.java (78%) create mode 100644 src/org/systemsbiology/biotapestry/biofabric/FabricNavTool.java rename src/org/systemsbiology/{biofabric/io => biotapestry/biofabric}/FabricSIFLoader.java (62%) rename src/org/systemsbiology/{biofabric/ui/dialogs => biotapestry/biofabric}/FabricSearchDialog.java (91%) rename src/org/systemsbiology/{biofabric/ui/render => biotapestry/biofabric}/ImageCache.java (86%) create mode 100644 src/org/systemsbiology/biotapestry/biofabric/InboundConnectionOp.java create mode 100644 src/org/systemsbiology/biotapestry/biofabric/InboundGaggleOp.java create mode 100644 src/org/systemsbiology/biotapestry/biofabric/InboundNetworkOp.java create mode 100644 src/org/systemsbiology/biotapestry/biofabric/InboundSelectionOp.java create mode 100644 src/org/systemsbiology/biotapestry/biofabric/LinkGroupingSetupDialog.java rename src/org/systemsbiology/{biofabric/ui/render => biotapestry/biofabric}/PaintCache.java (64%) rename src/org/systemsbiology/{biofabric/ui => biotapestry/biofabric}/PopupMenuControl.java (83%) rename src/org/systemsbiology/{biofabric/ui/dialogs => biotapestry/biofabric}/RelationDirectionDialog.java (64%) rename src/org/systemsbiology/{biofabric/ui/dialogs => biotapestry/biofabric}/ReorderLayoutParamsDialog.java (88%) create mode 100644 src/org/systemsbiology/biotapestry/biofabric/SelectionSupport.java rename src/org/systemsbiology/{biofabric/ui/dialogs => biotapestry/biofabric}/UpdateJavaDialog.java (97%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/About24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/Back24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/BioFab16White.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/C24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/ClearFabricSelected24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/D24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/Find24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/Forward24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/H24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/L24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacBlank.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacC.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacD.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacGT.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacL.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacLT.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacN.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacR.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacS.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacU.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/MacZ.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/N24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/P24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/P24Selected.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/PlusOneDeg24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/Print24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/PropagateSelected24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/S24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/Save24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/SaveAs24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/Stop24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/U24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/U24Selected.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/ZoomIn24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/ZoomOut24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/ZoomToAllFabric24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/ZoomToAllFabricSelected24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/ZoomToFabricRect24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/images/ZoomToFabricSelected24.gif (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/license/LICENSE (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/license/LICENSE-SUN (100%) rename src/org/systemsbiology/{ => biotapestry}/biofabric/license/about.html (100%) rename src/org/systemsbiology/{biofabric => biotapestry}/cmd/BTUndoCmd.java (94%) rename src/org/systemsbiology/{biofabric => biotapestry}/cmd/CompoundPostEventCmd2.java (70%) rename src/org/systemsbiology/{biofabric => biotapestry}/cmd/CompoundPreEventCmd.java (73%) rename src/org/systemsbiology/{biofabric => biotapestry}/cmd/ZoomChangeTracker.java (94%) rename src/org/systemsbiology/{biofabric => biotapestry}/cmd/ZoomCommandSupport.java (90%) rename src/org/systemsbiology/{biofabric => biotapestry}/cmd/ZoomTarget.java (80%) rename src/org/systemsbiology/{biofabric => biotapestry}/db/ColorGenerator.java (92%) rename src/org/systemsbiology/{biofabric => biotapestry}/db/GlobalChange.java (81%) rename src/org/systemsbiology/{biofabric => biotapestry}/db/SimpleWorkspaceSource.java (97%) rename src/org/systemsbiology/{biofabric => biotapestry}/db/Workspace.java (97%) rename src/org/systemsbiology/{biofabric => biotapestry}/event/ChangeEvent.java (94%) rename src/org/systemsbiology/{biofabric => biotapestry}/event/EventManager.java (56%) create mode 100644 src/org/systemsbiology/biotapestry/event/GeneralChangeEvent.java create mode 100644 src/org/systemsbiology/biotapestry/event/GeneralChangeListener.java rename src/org/systemsbiology/{biofabric => biotapestry}/event/LayoutChangeEvent.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/event/LayoutChangeListener.java (95%) create mode 100644 src/org/systemsbiology/biotapestry/event/ModelChangeEvent.java create mode 100644 src/org/systemsbiology/biotapestry/event/ModelChangeListener.java create mode 100644 src/org/systemsbiology/biotapestry/event/OverlayDisplayChangeEvent.java create mode 100644 src/org/systemsbiology/biotapestry/event/OverlayDisplayChangeListener.java rename src/org/systemsbiology/{biofabric => biotapestry}/event/SelectionChangeEvent.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/event/SelectionChangeListener.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/images/CrossCursor32.gif (100%) rename src/org/systemsbiology/{biofabric => biotapestry}/images/ErrorCursor32.gif (100%) rename src/org/systemsbiology/{biofabric => biotapestry}/parser/AbstractFactoryClient.java (89%) rename src/org/systemsbiology/{biofabric => biotapestry}/parser/GlueStick.java (96%) rename src/org/systemsbiology/{biofabric => biotapestry}/parser/ParserClient.java (96%) rename src/org/systemsbiology/{biofabric => biotapestry}/parser/SUParser.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/BasicZoomTargetSupport.java (91%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/CursorManager.java (96%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/ImageExporter.java (97%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/NamedColor.java (97%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/ZoomPresentation.java (90%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/dialogs/ExceptionDialog.java (89%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/dialogs/ExportSettingsDialog.java (90%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/dialogs/ExportSettingsPublishDialog.java (96%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/dialogs/utils/BTStashResultsDialog.java (96%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/dialogs/utils/DialogSupport.java (96%) rename src/org/systemsbiology/{biofabric => biotapestry}/ui/dialogs/utils/EditableTable.java (80%) create mode 100644 src/org/systemsbiology/biotapestry/util/AffineCombination.java rename src/org/systemsbiology/{biofabric => biotapestry}/util/AsynchExitRequestException.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/AttributeExtractor.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/BTProgressMonitor.java (97%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/BackgroundWorker.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/BackgroundWorkerClient.java (94%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/BackgroundWorkerControlManager.java (94%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/BackgroundWorkerOwner.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/CharacterEntityMapper.java (97%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ChoiceContent.java (97%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ColorLabel.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ColorListRenderer.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ComboBoxEditor.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ComboBoxEditorTracker.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ComboFinishedTracker.java (93%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/DataUtil.java (99%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/DoubMinMax.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/DoubleEditor.java (96%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/EditableComboBoxEditor.java (85%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/EditableComboBoxEditorTracker.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/EnumCell.java (86%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ExceptionHandler.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/FactoryUtilWhiteboard.java (93%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/FileExtensionFilters.java (99%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/FixedJButton.java (96%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/FixedJComboBox.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/GoodnessChart.java (99%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/Indenter.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/IntegerEditor.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/InvalidInputException.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/MinMax.java (89%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/NumberEditor.java (94%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/NumberEditorTracker.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ObjChoiceContent.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ProtoDouble.java (94%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ProtoInteger.java (94%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/ResourceManager.java (79%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/TaggedSet.java (97%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/TextEditor.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/TextEditorTracker.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/TextFinishedTracker.java (93%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/TrackingUnit.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/UiUtil.java (99%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/UndoSupport.java (95%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/UniqueLabeller.java (98%) rename src/org/systemsbiology/{biofabric => biotapestry}/util/Vector2D.java (99%) diff --git a/.gitignore b/.gitignore index 83bcc69..a9299dd 100644 --- a/.gitignore +++ b/.gitignore @@ -2,22 +2,4 @@ /dist/ /build/ /manifest.mf -/nbbuild.xml -/bin/ -/BioFabric-1.0.0.jar -/installInMVN.sh -/.project -/.DS_Store -/.classpath -.idea/ -BioFabric Fork.iml -BioFabric.iml -out/ -src/META-INF/ -.gitignore -org/.gitignore -org/systemsbiology/.DS_Store -org/systemsbiology/biofabric/ -org/systemsbiology/biotapestry/.gitignore -org/systemsbiology/biotapestry/biofabric/.gitignore - +/nbbuild.xml \ No newline at end of file diff --git a/README.md b/README.md index 44d1868..219f1ea 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ BioFabric ========= -The new development branch is in an experimental stage. It uses the new package organization. - - +BioFabric is an open-source network visualization tool that uses a new approach: nodes are represented as horizontal lines instead of as points: +![Les Miserables Network](http://www.biofabric.org/gallery/images/LesMiz1024.png) +[Super-Quick Demo D3 Animation](http://www.biofabric.org/gallery/pages/SuperQuickBioFabric.html) diff --git a/src/.gitignore b/src/.gitignore deleted file mode 100644 index 9bb88d3..0000000 --- a/src/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/.DS_Store diff --git a/src/org/.gitignore b/src/org/.gitignore deleted file mode 100644 index 9bb88d3..0000000 --- a/src/org/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/.DS_Store diff --git a/src/org/systemsbiology/biofabric/analysis/CycleFinder.java b/src/org/systemsbiology/biofabric/analysis/CycleFinder.java deleted file mode 100644 index 1fd9f71..0000000 --- a/src/org/systemsbiology/biofabric/analysis/CycleFinder.java +++ /dev/null @@ -1,160 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.analysis; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.HashSet; -import java.util.Iterator; - -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.NID; - -/**************************************************************************** -** -** A Class -*/ - -public class CycleFinder { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE VARIABLES - // - //////////////////////////////////////////////////////////////////////////// - - private Set nodes_; - private Set links_; - private HashMap> linksForNode_; - private Integer white_; - private Integer grey_; - private Integer black_; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public CycleFinder(Set nodes, Set links) { - nodes_ = nodes; - links_ = links; - linksForNode_ = new HashMap>(); - Iterator lit = links_.iterator(); - while (lit.hasNext()) { - FabricLink link = lit.next(); - Set linksForSrc = linksForNode_.get(link.getSrcID()); - if (linksForSrc == null) { - linksForSrc = new HashSet(); - linksForNode_.put(link.getSrcID(), linksForSrc); - } - linksForSrc.add(link); - } - white_ = new Integer(0); - grey_ = new Integer(1); - black_ = new Integer(2); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Answer if there is a cycle - */ - - public boolean hasACycle() { - - // - // Color vertices white: - // - - HashMap colors = new HashMap(); - Iterator vit = nodes_.iterator(); - while (vit.hasNext()) { - NID.WithName node = vit.next(); - colors.put(node, white_); - } - - // - // Visit each white vertex: - // - - vit = nodes_.iterator(); - while (vit.hasNext()) { - NID.WithName node = vit.next(); - Integer color = colors.get(node); - if (color.equals(white_)) { - if (visit(node, colors)) { - return (true); - } - } - } - - return (false); - } - - /*************************************************************************** - ** - ** Visit a node. Return true if a cycle - */ - - private boolean visit(NID.WithName vertex, Map colors) { - colors.put(vertex, grey_); - Set linksForVertex = linksForNode_.get(vertex); - if (linksForVertex != null) { - Iterator lit = linksForVertex.iterator(); - while (lit.hasNext()) { - FabricLink link = lit.next(); - Integer targColor = colors.get(link.getTrgID()); - if (targColor.equals(grey_)) { - return (true); - } else if (targColor.equals(white_)) { - if (visit(link.getTrgID(), colors)) { - return (true); - } - } - } - } - colors.put(vertex, black_); - return (false); - } -} diff --git a/src/org/systemsbiology/biofabric/analysis/GraphSearcher.java b/src/org/systemsbiology/biofabric/analysis/GraphSearcher.java deleted file mode 100644 index d249cfd..0000000 --- a/src/org/systemsbiology/biofabric/analysis/GraphSearcher.java +++ /dev/null @@ -1,1060 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.analysis; - -import java.util.HashMap; -import java.util.Map; -import java.util.HashSet; -import java.util.Set; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Iterator; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.NID; - -/**************************************************************************** -** -** A Class -*/ - -public class GraphSearcher { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE VARIABLES - // - //////////////////////////////////////////////////////////////////////////// - - private HashSet allNodes_; - private HashSet allEdges_; - private ArrayList nodeOrder_; - private ArrayList edgeOrder_; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public GraphSearcher(Set nodes, Set links) { - - allNodes_ = new HashSet(); - allEdges_ = new HashSet(); - edgeOrder_ = null; - nodeOrder_ = null; - - Iterator ni = nodes.iterator(); - Iterator li = links.iterator(); - - while (ni.hasNext()) { - allNodes_.add(ni.next()); - } - - while (li.hasNext()) { - FabricLink link = li.next(); - allEdges_.add(link.clone()); - } - } - - /*************************************************************************** - ** - ** Constructor. Used to create a depth-first order that - ** retains original sibling order. If link appears multiple - ** times, the order is based on first appearance. - */ - - public GraphSearcher(List nodes, List links) { - - allNodes_ = new HashSet(); - allEdges_ = new HashSet(); - edgeOrder_ = new ArrayList(); - nodeOrder_ = new ArrayList(); - - Iterator li = links.iterator(); - - nodeOrder_.addAll(nodes); - allNodes_.addAll(nodes); - - while (li.hasNext()) { - FabricLink link = li.next(); - if (!allEdges_.contains(link)) { - edgeOrder_.add(link.clone()); - } - allEdges_.add(link.clone()); - } - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Map of node degree - */ - - public Map nodeDegree(boolean inOnly) { - return (nodeDegree(inOnly, allEdges_)); - } - - /*************************************************************************** - ** - ** Map of node degree - */ - - public static Map nodeDegree(boolean inOnly, Set edges) { - - HashMap retval = new HashMap(); - - Iterator li = edges.iterator(); - while (li.hasNext()) { - FabricLink link = li.next(); - NID.WithName src = link.getSrcID(); - NID.WithName trg = link.getTrgID(); - if (!inOnly) { - Integer deg = retval.get(src); - if (deg == null) { - retval.put(src, new Integer(1)); - } else { - retval.put(src, new Integer(deg.intValue() + 1)); - } - } - Integer deg = retval.get(trg); - if (deg == null) { - retval.put(trg, new Integer(1)); - } else { - retval.put(trg, new Integer(deg.intValue() + 1)); - } - } - return (retval); - } - - - /*************************************************************************** - ** - ** Sorted set of node degree - */ - - public SortedSet nodeDegreeSet() { - - TreeSet retval = new TreeSet(); - - Map nds = nodeDegree(false); - - Iterator li = nds.keySet().iterator(); - while (li.hasNext()) { - NID.WithName node = li.next(); - NodeDegree ndeg = new NodeDegree(node, nds.get(node).intValue()); - retval.add(ndeg); - } - return (retval); - } - - /*************************************************************************** - ** - ** Sorted set of node degree - */ - - public static SortedSet nodeDegreeSet(Set edges) { - - TreeSet retval = new TreeSet(); - - Map nds = nodeDegree(false, edges); - - Iterator li = nds.keySet().iterator(); - while (li.hasNext()) { - NID.WithName node = li.next(); - NodeDegree ndeg = new NodeDegree(node, nds.get(node).intValue()); - retval.add(ndeg); - } - return (retval); - } - - /*************************************************************************** - ** - ** Sorted set of node degree - */ - - public static List nodesByDegree(Set nodes, SortedSet nds) { - - ArrayList retval = new ArrayList(); - - Iterator li = nds.iterator(); - while (li.hasNext()) { - NodeDegree nd = li.next(); - NID.WithName node = nd.getNode(); - if (nodes.contains(node)) { - retval.add(node); - } - } - return (retval); - } - - /*************************************************************************** - ** - ** Sorted set of node degree - */ - - public SortedSet nodeDegreeSetWithSource(List sourceOrder) { - - HashMap> allSrcs = new HashMap>(); - Iterator lit = allEdges_.iterator(); - while (lit.hasNext()) { - FabricLink nextLink = lit.next(); - NID.WithName trg = nextLink.getTrgID(); - Set trgSources = allSrcs.get(trg); - if (trgSources == null) { - trgSources = new HashSet(); - allSrcs.put(trg, trgSources); - } - trgSources.add(nextLink.getSrcID()); - } - - TreeSet retval = new TreeSet(); - - Iterator li = allSrcs.keySet().iterator(); - while (li.hasNext()) { - NID.WithName node = li.next(); - Set trgSources = allSrcs.get(node); - SourcedNodeDegree ndeg = new SourcedNodeDegree(node, sourceOrder, trgSources); - retval.add(ndeg); - } - return (retval); - } - - - /*************************************************************************** - ** - ** Sorted list of nodes by degree - */ - - public List nodeDegreeOrder() { - - ArrayList retval = new ArrayList(); - SortedSet nds = nodeDegreeSet(); - Iterator li = nds.iterator(); - while (li.hasNext()) { - NodeDegree ndeg = li.next(); - retval.add(ndeg.getNode()); - } - return (retval); - } - - /*************************************************************************** - ** - ** Topo sort - */ - - public Map topoSort(boolean compress) { - - if (edgeOrder_ != null) { - throw new IllegalStateException(); - } - - // - // Assign all roots to level 0, add them to return list at that level. - // Delete them and edges from them. Recalulate root list and continue. - // - - HashMap retval = new HashMap(); - Set currentNodes = new HashSet(allNodes_); - // - // Deep copy: - // - Set currentEdges = new HashSet(); - Iterator li = allEdges_.iterator(); - while (li.hasNext()) { - FabricLink link = li.next(); - currentEdges.add(link.clone()); - } - - Map> outEdges = calcOutboundEdges(currentEdges); - Set rootNodes = buildRootList(currentNodes, currentEdges); - - int level = 0; - while (!rootNodes.isEmpty()) { - Integer ilevel = new Integer(level++); - Iterator rit = rootNodes.iterator(); - while (rit.hasNext()) { - NID.WithName nodeID = rit.next(); - retval.put(nodeID, ilevel); - outEdges.remove(nodeID); - currentNodes.remove(nodeID); - } - currentEdges = invertOutboundEdges(outEdges); - rootNodes = buildRootList(currentNodes, currentEdges); - } - - if (compress) { - contractTopoSort(retval); - } - return (retval); - } - - /*************************************************************************** - ** - ** Depth-First Search - */ - - public List depthSearch() { - // - // Do until roots are exhausted - // - HashSet visited = new HashSet(); - - Set rootNodes = buildRootList(allNodes_, allEdges_); - Map> outEdges = calcOutboundEdges(allEdges_); - - List retval = new ArrayList(); - if (edgeOrder_ != null) { - HashSet seenRoots = new HashSet(); - Iterator nit = nodeOrder_.iterator(); - while (nit.hasNext()) { - NID.WithName currNode = nit.next(); - if (!rootNodes.contains(currNode)) { - continue; - } - boolean gottaLink = false; - Iterator eit = edgeOrder_.iterator(); - while (eit.hasNext()) { - FabricLink link = eit.next(); - NID.WithName src = link.getSrcID(); - if (!currNode.equals(src)) { - continue; - } - if (seenRoots.contains(src)) { - continue; - } - seenRoots.add(src); - gottaLink = true; - searchGutsDepth(src, visited, outEdges, 0, edgeOrder_, retval); - } - if (!gottaLink) { - visited.add(currNode); - retval.add(new QueueEntry(0, currNode)); - } - } - } else { - Iterator rit = rootNodes.iterator(); - while (rit.hasNext()) { - searchGutsDepth(rit.next(), visited, outEdges, 0, null, retval); - } - } - return (retval); - } - - /*************************************************************************** - ** - ** Breadth-First Search, ordered by degree - */ - - public List breadthSearch(List startNodes) { - - if (edgeOrder_ != null) { - throw new IllegalStateException(); - } - - List byDeg = nodeDegreeOrder(); - Collections.reverse(byDeg); - ArrayList toProcess = new ArrayList(byDeg); - - if ((startNodes != null) && !startNodes.isEmpty()) { - toProcess.removeAll(startNodes); - ArrayList useDeg = new ArrayList(startNodes); - useDeg.addAll(toProcess); - toProcess = useDeg; - } - - // - // Do until everybody is visited - // - HashSet visited = new HashSet(); - ArrayList queue = new ArrayList(); - List retval = new ArrayList(); - Map> outEdges = calcOutboundEdges(allEdges_); - - - while (!toProcess.isEmpty()) { - queue.add(new QueueEntry(0, toProcess.get(0))); - searchGutsBreadth(visited, queue, outEdges, retval, null, byDeg); - toProcess.removeAll(visited); - } - return (retval); - } - - - /*************************************************************************** - ** - ** Breadth-First Search - */ - - public List breadthSearchUntilStopped(Set startNodes, CriteriaJudge judge) { - - if (edgeOrder_ != null) { - throw new IllegalStateException(); - } - - // - // Do until roots are exhausted - // - - HashSet visited = new HashSet(); - ArrayList queue = new ArrayList(); - List retval = new ArrayList(); - - Map> outEdges = calcOutboundEdges(allEdges_); - - Iterator rit = startNodes.iterator(); - while (rit.hasNext()) { - queue.add(new QueueEntry(0, rit.next())); - } - searchGutsBreadth(visited, queue, outEdges, retval, judge, null); - return (retval); - } - - /*************************************************************************** - ** - ** A topo sort map gives column for each node. Invert that to give a list - ** of nodes for each column. - */ - - public int invertTopoSort(Map topoSort, Map> invert) { - - Iterator kit = topoSort.keySet().iterator(); - int maxLevel = -1; - while (kit.hasNext()) { - NID.WithName key = kit.next(); - Integer level = topoSort.get(key); - int currLev = level.intValue(); - if (currLev > maxLevel) { - maxLevel = currLev; - } - List nodeList = invert.get(level); - if (nodeList == null) { - nodeList = new ArrayList(); - invert.put(level, nodeList); - } - nodeList.add(key); - } - return (maxLevel); - } - - /*************************************************************************** - ** - ** Take a sort to a simple listing - */ - - public List topoSortToPartialOrdering(Map topoSort) { - - ArrayList retval = new ArrayList(); - TreeMap> invert = new TreeMap>(); - - invertTopoSort(topoSort, invert); - Iterator> kit = invert.values().iterator(); - while (kit.hasNext()) { - List listForLevel = kit.next(); - // Want reproducibility between VfA and Vfg layouts. This is required. - Collections.sort(listForLevel); - retval.addAll(listForLevel); - } - return (retval); - } - - /*************************************************************************** - ** - ** Take a sort to a simple listing - */ - - public List topoSortToPartialOrdering(Map topoSort, Set allLinks) { - - ArrayList retval = new ArrayList(); - TreeMap> invert = new TreeMap>(); - - SortedSet nds = nodeDegreeSet(allLinks); - - invertTopoSort(topoSort, invert); - Iterator> kit = invert.values().iterator(); - while (kit.hasNext()) { - List listForLevel = kit.next(); - List l4lbyDeg = nodesByDegree(new HashSet(listForLevel), nds); - Collections.reverse(l4lbyDeg); - retval.addAll(l4lbyDeg); - } - return (retval); - } - - - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CLASS METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** With a given topo sort, force the given moveID to one end - */ - - public static Map topoSortReposition(Map origSort, String moveID, boolean moveMin) { - - Integer origCol = origSort.get(moveID); - if (origCol == null) { - return (new HashMap(origSort)); - } - - int colVal = origCol.intValue(); - boolean colDup = false; - int minVal = Integer.MAX_VALUE; - int maxVal = Integer.MIN_VALUE; - Iterator oskit = origSort.keySet().iterator(); - while (oskit.hasNext()) { - String key = oskit.next(); - if (key.equals(moveID)) { - continue; - } - Integer checkCol = origSort.get(key); - int chekVal = checkCol.intValue(); - if (chekVal < minVal) { - minVal = chekVal; - } - if (chekVal > maxVal) { - maxVal = chekVal; - } - if (chekVal == colVal) { - colDup = true; - } - } - - int minMove; - int maxMove; - int moveCol; - int inc; - if (moveMin) { - if (colDup) { // to front, everybody up - moveCol = minVal; - minMove = minVal; - maxMove = maxVal; - inc = 1; - } else { // to front, guys below move up - moveCol = (colVal < minVal) ? colVal : minVal; - minMove = minVal; - maxMove = colVal - 1; - inc = 1; - } - } else { - if (colDup) { // to end, nobody moves - moveCol = maxVal + 1; - minMove = minVal - 1; - maxMove = minVal - 1; - inc = 0; - } else { // to end, guys above move down - moveCol = (colVal > maxVal) ? colVal : maxVal; - minMove = minVal - 1; - maxMove = minVal - 1; - inc = 0; - } - } - - HashMap retval = new HashMap(); - - oskit = origSort.keySet().iterator(); - while (oskit.hasNext()) { - String key = oskit.next(); - if (key.equals(moveID)) { - retval.put(moveID, new Integer(moveCol)); - } else { - Integer checkCol = origSort.get(key); - int chekVal = checkCol.intValue(); - if ((chekVal >= minMove) && (chekVal <= maxMove)) { - retval.put(key, new Integer(chekVal + inc)); - } else { - retval.put(key, checkCol); - } - } - } - return (retval); - } - - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC INNER CLASSES - // - //////////////////////////////////////////////////////////////////////////// - - public class QueueEntry { - public int depth; - public NID.WithName name; - - QueueEntry(int depth, NID.WithName name) { - this.depth = depth; - this.name = name; - } - - public String toString() { - return (name + " depth = " + depth); - } - - } - - /*************************************************************************** - ** - ** Tell us when to stop looking - */ - - public static interface CriteriaJudge { - public boolean stopHere(NID.WithName nodeID); - } - - /**************************************************************************** - ** - ** A Class - */ - - public static class NodeDegree implements Comparable { - - private NID.WithName node_; - private int degree_; - - public NodeDegree(NID.WithName node, int degree) { - node_ = node; - degree_ = degree; - } - - public NID.WithName getNode() { - return (node_); - } - - @Override - public int hashCode() { - return (node_.hashCode() + degree_); - } - - @Override - public String toString() { - return (" node = " + node_ + " degree = " + degree_); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof NodeDegree)) { - return (false); - } - NodeDegree otherDeg = (NodeDegree)other; - if (this.degree_ != otherDeg.degree_) { - return (false); - } - return ((this.node_ == null) ? (otherDeg.node_ == null) : this.node_.equals(otherDeg.node_)); - } - - public int compareTo(NodeDegree otherDeg) { - if (this.degree_ != otherDeg.degree_) { - return (this.degree_ - otherDeg.degree_); - } - if (this.node_ == null) { - return ((otherDeg.node_ == null) ? 0 : -1); - } - return (this.node_.compareTo(otherDeg.node_)); - } - } - - /**************************************************************************** - ** - ** A Class - */ - - public static class SourcedNodeDegree implements Comparable { - - private NID.WithName node_; - private int degree_; - private boolean[] srcs_; - - public SourcedNodeDegree(NID.WithName node, List srcOrder, Set mySrcs) { - node_ = node; - degree_ = mySrcs.size(); - int numSrc = srcOrder.size(); - srcs_ = new boolean[numSrc]; - for (int i = 0; i < numSrc; i++) { - if (mySrcs.contains(srcOrder.get(i))) { - srcs_[i] = true; - } - } - } - - public NID.WithName getNode() { - return (node_); - } - - @Override - public int hashCode() { - return (node_.hashCode() + degree_); - } - - @Override - public String toString() { - return (" node = " + node_ + " degree = " + degree_); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof SourcedNodeDegree)) { - return (false); - } - SourcedNodeDegree otherDeg = (SourcedNodeDegree)other; - if (this.degree_ != otherDeg.degree_) { - return (false); - } - return ((this.node_ == null) ? (otherDeg.node_ == null) : this.node_.equals(otherDeg.node_)); - } - - public int compareTo(SourcedNodeDegree otherDeg) { - if (this.degree_ != otherDeg.degree_) { - // Higher degree is first: - return (otherDeg.degree_ - this.degree_); - } - - boolean iAmBigger = false; - boolean heIsBigger = false; - for (int i = 0; i < this.srcs_.length; i++) { - - if (this.srcs_[i]) { - if (otherDeg.srcs_[i] == false) { - iAmBigger = true; - heIsBigger = false; - break; - } - } - if (otherDeg.srcs_[i]) { - if (this.srcs_[i] == false) { - iAmBigger = false; - heIsBigger = true; - break; - } - } - } - if (iAmBigger) { - return (-1); - } else if (heIsBigger) { - return (1); - } - if (this.node_ == null) { - return ((otherDeg.node_ == null) ? 0 : -1); - } - return (this.node_.compareTo(otherDeg.node_)); - } - } - - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Build map from node to outbound edges - */ - - private Map> calcOutboundEdges(Set edges) { - - HashMap> retval = new HashMap>(); - Iterator li = edges.iterator(); - - while (li.hasNext()) { - FabricLink link = li.next(); - addaLink(link, link.getSrcID(), retval); - if (!link.isDirected()) { - addaLink(link, link.getTrgID(), retval); - } - } - return (retval); - } - - /*************************************************************************** - ** - ** Add a link to a bin - */ - - private void addaLink(FabricLink link, NID.WithName bin, Map> collect) { - Set forBin = collect.get(bin); - if (forBin == null) { - forBin = new HashSet(); - collect.put(bin, forBin); - } - forBin.add(link); - return; - } - - /*************************************************************************** - ** - ** Build a root list - */ - - private Set buildRootList(Set nodes, Set edges) { - - HashSet retval = new HashSet(); - retval.addAll(nodes); - - Iterator ei = edges.iterator(); - while (ei.hasNext()) { - FabricLink link = ei.next(); - NID.WithName trg = link.getTrgID(); - retval.remove(trg); - } - return (retval); - } - - /*************************************************************************** - ** - ** Invert - */ - - private Set invertOutboundEdges(Map> outEdges) { - - HashSet retval = new HashSet(); - Iterator ki = outEdges.keySet().iterator(); - - while (ki.hasNext()) { - NID.WithName src = ki.next(); - Set links = outEdges.get(src); - Iterator sit = links.iterator(); - while (sit.hasNext()) { - FabricLink lnk = sit.next(); - if (lnk.isFeedback()) { - retval.add(lnk.clone()); - } else { - retval.add(lnk.flipped()); - } - } - } - return (retval); - } - - /*************************************************************************** - ** - ** Depth-First Search guts - */ - - private void searchGutsDepth(NID.WithName vertexID, HashSet visited, - Map> edgesFromSrc, - int depth, List edgeOrder, List results) { - - if (visited.contains(vertexID)) { - return; - } - visited.add(vertexID); - results.add(new QueueEntry(depth, vertexID)); - Set outEdges = edgesFromSrc.get(vertexID); - if (outEdges == null) { - return; - } - - if (edgeOrder != null) { - Iterator eit = edgeOrder.iterator(); - while (eit.hasNext()) { - FabricLink link = eit.next(); - if (!vertexID.equals(link.getSrcID())) { - continue; - } - NID.WithName targ = link.getTrgID(); - if (!visited.contains(targ)) { - searchGutsDepth(targ, visited, edgesFromSrc, depth + 1, edgeOrder, results); - } - } - } else { - Iterator eit = outEdges.iterator(); - while (eit.hasNext()) { - FabricLink link = eit.next(); - NID.WithName targ = link.getTrgID(); - if (!visited.contains(targ)) { - searchGutsDepth(targ, visited, edgesFromSrc, depth + 1, edgeOrder, results); - } - } - } - return; - } - - /*************************************************************************** - ** - ** Breadth-First Search guts - */ - - private void searchGutsBreadth(HashSet visited, ArrayList queue, Map> edgesFromSrc, - List results, CriteriaJudge judge, List byDegree) { - - while (queue.size() > 0) { - QueueEntry curr = queue.remove(0); - if (visited.contains(curr.name)) { - continue; - } - visited.add(curr.name); - results.add(curr); - - if (judge != null) { - if (judge.stopHere(curr.name)) { - continue; - } - } - - Set outEdges = edgesFromSrc.get(curr.name); - if (outEdges == null) { - continue; - } - - if (byDegree != null) { - HashSet fltrg = new HashSet(); - for (FabricLink fl : outEdges) { - if (fl.isDirected()) { - fltrg.add(fl.getTrgID()); - } else { - NID.WithName flSrc = fl.getSrcID(); - fltrg.add((curr.name.equals(flSrc)) ? fl.getTrgID() : flSrc); - } - } - Iterator bdit = byDegree.iterator(); - while (bdit.hasNext()) { - NID.WithName trg = bdit.next(); - if (fltrg.contains(trg)) { - queue.add(new QueueEntry(curr.depth + 1, trg)); - } - } - - } else { - Iterator oit = outEdges.iterator(); - while (oit.hasNext()) { - FabricLink flink = oit.next(); - } - } - } - return; - } - - /*************************************************************************** - ** - ** Contract the topo sort by moving nodes as far downstream as possible without - ** breaking the partial ordering. - */ - - private void contractTopoSort(Map topoSort) { - - // - // Make a list of nodes for each level. Starting at the highest level, - // get a node, and go through all the outbound links from that node. - // Get the minimum level of all targets, and then move the node to - // level min - 1. - // - // Iterate this process until no more changes can occur. - // - - HashMap> nodesAtLevel = new HashMap>(); - int maxLevel = invertTopoSort(topoSort, nodesAtLevel); - - if (maxLevel == -1) { // nothing to do - return; - } - - Map> outEdges = calcOutboundEdges(allEdges_); - - while (true) { - boolean changed = false; - for (int i = maxLevel; i >= 0; i--) { - List nodeList = nodesAtLevel.get(Integer.valueOf(i)); - List listCopy = new ArrayList(nodeList); - int numNodes = nodeList.size(); - for (int j = 0; j < numNodes; j++) { - NID.WithName currNode = listCopy.get(j); - Set linksForNode = outEdges.get(currNode); - HashSet targsForNode = new HashSet(); - Iterator lfnit = linksForNode.iterator(); - while (lfnit.hasNext()) { - FabricLink link = lfnit.next(); - NID.WithName targ = link.getTrgID(); - targsForNode.add(targ); - } - int min = getMinLevel(targsForNode, topoSort, i, maxLevel); - if (min > i + 1) { - List higherNodeList = nodesAtLevel.get(Integer.valueOf(min - 1)); - higherNodeList.add(currNode); - nodeList.remove(currNode); - topoSort.put(currNode, Integer.valueOf(min - 1)); - changed = true; - } - } - } - if (!changed) { - return; - } - } - } - - /*************************************************************************** - ** - ** Get the minimum level of all the target nodes - */ - - private int getMinLevel(Set targs, Map topoSort, int currLevel, int maxLevel) { - if (targs == null) { - return (currLevel); - } - int min = maxLevel; - Iterator trgit = targs.iterator(); - while (trgit.hasNext()) { - NID.WithName trg = trgit.next(); - Integer level = topoSort.get(trg); - int currLev = level.intValue(); - if (min > currLev) { - min = currLev; - } - } - return (min); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INNER CLASSES - // - //////////////////////////////////////////////////////////////////////////// -} diff --git a/src/org/systemsbiology/biofabric/analysis/NIDLink.java b/src/org/systemsbiology/biofabric/analysis/NIDLink.java deleted file mode 100644 index 06065ee..0000000 --- a/src/org/systemsbiology/biofabric/analysis/NIDLink.java +++ /dev/null @@ -1,99 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.analysis; - -import org.systemsbiology.biofabric.util.NID; - -/**************************************************************************** -** -** A Class -*/ - -public class NIDLink implements Cloneable, Comparable { - protected NID.WithName src_; - protected NID.WithName trg_; - - public NIDLink(NID.WithName src, NID.WithName trg) { - if ((src == null) || (trg == null)) { - throw new IllegalArgumentException(); - } - this.src_ = src; - this.trg_ = trg; - } - - public NIDLink(NIDLink other) { - this.src_ = other.src_; - this.trg_ = other.trg_; - } - - @Override - public NIDLink clone() { - try { - return ((NIDLink)super.clone()); - } catch (CloneNotSupportedException cnse) { - throw new IllegalStateException(); - } - } - - public NID.WithName getTrg() { - return (trg_); - } - - public NID.WithName getSrc() { - return (src_); - } - - @Override - public int hashCode() { - return (src_.hashCode() + trg_.hashCode()); - } - - @Override - public String toString() { - return ("src = " + src_ + " trg = " + trg_); - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return (false); - } - if (other == this) { - return (true); - } - if (!(other instanceof NIDLink)) { - return (false); - } - NIDLink otherLink = (NIDLink)other; - return (this.src_.equals(otherLink.src_) && this.trg_.equals(otherLink.trg_)); - } - - public int compareTo(NIDLink otherLink) { - if (this == otherLink) { - return (0); - } - - if (!this.src_.equals(otherLink.src_)) { - return (this.src_.compareTo(otherLink.src_)); - } - - return (this.trg_.compareTo(otherLink.trg_)); - } -} diff --git a/src/org/systemsbiology/biofabric/analysis/NetworkAlignment.java b/src/org/systemsbiology/biofabric/analysis/NetworkAlignment.java deleted file mode 100644 index 5fd81e8..0000000 --- a/src/org/systemsbiology/biofabric/analysis/NetworkAlignment.java +++ /dev/null @@ -1,3363 +0,0 @@ -/* -** Copyright (C) 2003-2014 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.analysis; - -import org.systemsbiology.biofabric.util.ExceptionHandler; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.TreeMap; -import java.util.TreeSet; - -public class NetworkAlignment { - - private GraphNA small_, large_; - private AlignmentNA align_; - - public NetworkAlignment(NetworkAlignInfo nai) { - - this.small_ = new GraphNA(nai.small); - this.large_ = new GraphNA(nai.large); - this.align_ = new AlignmentNA(nai.align); - - synthesize(); - } - - private void synthesize() { - - Map smallNames = new TreeMap(); - Map largeNames = new TreeMap(); - - for (Map.Entry entry : align_.nodeToNode_.entrySet()) { - - String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; - - smallNames.put(x, xy); - largeNames.put(y, xy); - -// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH - } - - this.small_.updateNames(smallNames); - this.large_.updateNames(largeNames); - } - - @Override - public String toString() { - String ret; - ret = "G1: " + small_ + '\n' + "G2: " + large_; - - return ret; - } - - public GraphNA getSmall() { - return new GraphNA(small_); - } - - public GraphNA getLarge() { - return new GraphNA(large_); - } - - - public static class GraphNA { // needs to implement cloneable in future - - private Map> edges_; - private Map names_; - private int size_; - - private GraphNA() { - } - - public GraphNA(GraphNA graphNA) { - this.size_ = graphNA.getSize(); - this.names_ = graphNA.getNames(); - this.edges_ = graphNA.getEdges(); - } - - public static GraphNA readGraphGWFile(File file) { - GraphNA ret = new GraphNA(); - ret.edges_ = new TreeMap>(); - ret.names_ = new TreeMap(); - - try { - BufferedReader br = new BufferedReader(new FileReader(file)); - - for (int i = 0; i < 4; i++) { - br.readLine(); - } - - ret.size_ = Integer.parseInt(br.readLine()); - - for (int i = 1; i <= ret.size_; i++) { - String name = br.readLine().trim(); - name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" - - ret.addNode(i, name); - } - - final int edges = Integer.parseInt(br.readLine()); - - for (int i = 1; i <= edges; i++) { - StringTokenizer st = new StringTokenizer(br.readLine()); - int node1 = Integer.parseInt(st.nextToken()); - int node2 = Integer.parseInt(st.nextToken()); - - ret.addEdge(node1, node2); - } - - br.close(); - } catch (IOException ioe) { - ExceptionHandler.getHandler().displayException(ioe); - } - - return ret; - } - - private void addNode(int nodeNum, String nodeName) { - if (edges_.get(nodeName) == null) { - edges_.put(nodeName, new TreeSet()); - } - if (names_.get(nodeNum) == null) { - names_.put(nodeNum, nodeName); - } - } - - private void addEdge(int node1, int node2) { - if (node1 == node2) { - ExceptionHandler.getHandler().displayException(new IllegalArgumentException("node1 == node2")); - } - - edges_.get(names_.get(node1)).add(names_.get(node2)); - edges_.get(names_.get(node2)).add(names_.get(node1)); - } - - void updateNames(Map newNames) { - - Map> newEdges = new TreeMap>(); - - for (Map.Entry> entry : edges_.entrySet()) { - String key = entry.getKey(); - String x = (newNames.get(key) == null) ? key : newNames.get(key); - - Set newSet = new TreeSet(); - for (String str : entry.getValue()) { - String y = (newNames.get(str) == null) ? str : newNames.get(str); - newSet.add(y); - } - - newEdges.put(x, newSet); - } - - edges_ = newEdges; - } - - @Override - public String toString() { - - int linkNum = 0; - for (Map.Entry> entry : edges_.entrySet()) { - linkNum += entry.getValue().size(); - } - linkNum /= 2; - - return String.format("(V, E) = (%d, %d)", size_, linkNum); - } - - public int getSize() { - return size_; - } - - public Map getNames() { - return new TreeMap(names_); - } - - public Map> getEdges() { - return new TreeMap>(edges_); - } - - } - - public static class AlignmentNA { - - private Map nodeToNode_; - - private AlignmentNA() { - } - - public AlignmentNA(AlignmentNA alignmentNA) { - this.nodeToNode_ = alignmentNA.getNodeToNodeMapping(); - } - - public static AlignmentNA readAlignFile(File file) { - AlignmentNA ret = new AlignmentNA(); - ret.nodeToNode_ = new TreeMap(); - - try { - BufferedReader br = new BufferedReader(new FileReader(file)); - - String line; - while ((line = br.readLine()) != null) { - StringTokenizer st = new StringTokenizer(line); - - ret.nodeToNode_.put(st.nextToken(), st.nextToken()); - } - br.close(); - } catch (IOException ioe) { - ExceptionHandler.getHandler().displayException(ioe); - } - - return ret; - } - - public Map getNodeToNodeMapping() { - return new TreeMap(nodeToNode_); - } - - public int getSize() { - return nodeToNode_.size(); - } - - } - - public static class NetworkAlignInfo { - - final GraphNA small, large; - final AlignmentNA align; - - public NetworkAlignInfo(GraphNA small, GraphNA large, AlignmentNA align) { - this.small = small; - this.large = large; - this.align = align; - } - - } - -} - - -//package org.systemsbiology.biofabric.analysis; -// -// import org.systemsbiology.biofabric.util.ExceptionHandler; -// -// import java.io.BufferedReader; -// import java.io.File; -// import java.io.FileReader; -// import java.io.IOException; -// import java.util.*; -// -//public class NetworkAlignment { -// -// private GraphNA small_, large_; -// private AlignmentNA align_; -// -// public NetworkAlignment(NetworkAlignInfo nai) { -// -// this.small_ = nai.small; -// this.large_ = nai.large; -// this.align_ = nai.align; -// -// synthesize(); -// -// -// } -// -// private void synthesize() { -// -// Map smallNames = new TreeMap(); -// Map largeNames = new TreeMap(); -// -// for (Map.Entry entry : align_.nodeToNode_.entrySet()) { -// -// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -// -// smallNames.put(x, xy); -// largeNames.put(y, xy); -// -//// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -// } -// -// this.small_.updateNames(smallNames); -// this.large_.updateNames(largeNames); -// } -// -// @Override -// public String toString() { -// String ret; -// ret = "G1: " + small + '\n' + "G2: " + large; -// -// return ret; -// } -// -// public GraphNA getSmall() { -// return new GraphNA(small_); -// } -// -// public GraphNA getLarge() { -// return new GraphNA(large_); -// } -// -// -// public static class GraphNA { // needs to implement cloneable in future -// -// private Map> edges_; -// private Map names_; -// private int size_; -// -// private GraphNA() { -// } -// -// public GraphNA(GraphNA graphNA) { -// this.size_ = graphNA.getSize(); -// this.names_ = graphNA.getNames(); -// this.edges_ = graphNA.getEdges(); -// } -// -// public static GraphNA readGraphGWFile(File file) { -// GraphNA ret = new GraphNA(); -// ret.edges_ = new TreeMap>(); -// ret.names_ = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// for (int i = 0; i < 4; i++) { -// br.readLine(); -// } -// -// ret.size_ = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= ret.size_; i++) { -// String name = br.readLine().trim(); -// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -// -// ret.addNode(i, name); -// } -// -// final int edges = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= edges; i++) { -// StringTokenizer st = new StringTokenizer(br.readLine()); -// int node1 = Integer.parseInt(st.nextToken()); -// int node2 = Integer.parseInt(st.nextToken()); -// -// ret.addEdge(node1, node2); -// } -// -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// return ret; -// } -// -// private void addNode(int nodeNum, String nodeName) { -// if (edges_.get(nodeName) == null) { -// edges_.put(nodeName, new TreeSet()); -// } -// if (names_.get(nodeNum) == null) { -// names_.put(nodeNum, nodeName); -// } -// } -// -// private void addEdge(int node1, int node2) { -// if (node1 == node2) { -// ExceptionHandler.getHandler().displayException(new IllegalArgumentException("node1 == node2")); -// } -// -// edges_.get(names_.get(node1)).add(names_.get(node2)); -// edges_.get(names_.get(node2)).add(names_.get(node1)); -// } -// -// void updateNames(Map newNames) { -// -// Map> newEdges = new TreeMap>(); -// -// for (Map.Entry> entry : edges_.entrySet()) { -// String key = entry.getKey(); -// String x = (newNames.get(key) == null) ? key : newNames.get(key); -// -// Set newSet = new TreeSet(); -// for (String str : entry.getValue()) { -// String y = (newNames.get(str) == null) ? str : newNames.get(str); -// newSet.add(y); -// } -// -// newEdges.put(x, newSet); -// } -// -// edges_ = newEdges; -// } -// -// @Override -// public String toString() { -// -// int linkNum = 0; -// for (Map.Entry> entry : edges_.entrySet()) { -// linkNum += entry.getValue().size(); -// } -// linkNum /= 2; -// -// return String.format("(V, E) = (%d, %d)", size_, linkNum); -// } -// -// public int getSize() { -// return size_; -// } -// -// public Map getNames() { -// return new TreeMap(names_); -// } -// -// public Map> getEdges() { -// return new TreeMap>(edges_); -// } -// -// } -// -// public static class AlignmentNA { -// -// private Map nodeToNode_; -// -// private AlignmentNA() { -// } -// -// public static AlignmentNA readAlignFile(File file) { -// AlignmentNA ret = new AlignmentNA(); -// ret.nodeToNode_ = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// ret.nodeToNode_.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// return ret; -// } -// -// // private void synthesize(GraphNA small, GraphNA large) { -//// -//// this.small = new GraphNA(small); -//// this.large = new GraphNA(large); -//// -//// Map smallNames = new TreeMap(); -//// Map largeNames = new TreeMap(); -//// -//// for (Map.Entry entry : nodeToNode.entrySet()) { -//// -//// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -//// -//// smallNames.put(x, xy); -//// largeNames.put(y, xy); -//// -////// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -//// } -//// -//// this.small.updateNames(smallNames); -//// this.large.updateNames(largeNames); -//// } -//// -//// @Override -//// public String toString() { -//// String ret; -//// ret = "G1: " + small + '\n' + "G2: " + large; -//// -//// return ret; -//// } -// public Map getNodeToNodeMapping() { -// return new TreeMap(nodeToNode_); -// } -// -// public int getSize() { -// return nodeToNode_.size(); -// } -// -// } -// -// public static class NetworkAlignInfo { -// -// final GraphNA small, large; -// final AlignmentNA align; -// -// public NetworkAlignInfo(GraphNA small, GraphNA large, AlignmentNA align) { -// this.small = small; -// this.large = large; -// this.align = align; -// } -// -// } -// -//} - -///* -//** Copyright (C) 2003-2014 Institute for Systems Biology -//** Seattle, Washington, USA. -//** -//** This library is free software; you can redistribute it and/or -//** modify it under the terms of the GNU Lesser General Public -//** License as published by the Free Software Foundation; either -//** version 2.1 of the License, or (at your option) any later version. -//** -//** This library is distributed in the hope that it will be useful, -//** but WITHOUT ANY WARRANTY; without even the implied warranty of -//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -//** Lesser General Public License for more details. -//** -//** You should have received a copy of the GNU Lesser General Public -//** License along with this library; if not, write to the Free Software -//** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//*/ -// -//package org.systemsbiology.biofabric.analysis; -// -// import org.systemsbiology.biofabric.util.ExceptionHandler; -// -// import java.io.BufferedReader; -// import java.io.File; -// import java.io.FileReader; -// import java.io.IOException; -// import java.util.*; -// -//public class NetworkAlignment { -// -// private GraphNA small, large; -// private AlignmentNA align; -// -// public NetworkAlignment(NetworkAlignInfo nai) { -// -// this.small = nai.small; -// this.large = nai.large; -// this.align = nai.align; -// -// } -// -// public static class GraphNA { // needs to implement cloneable in future -// -// Map> edges_; -// private Map names_; -// private int size_; -// -//// public GraphNA(File dir) { -//// -//// this.edges_ = new TreeMap>(); -//// this.names_ = new TreeMap(); -//// -//// try { -//// BufferedReader br = new BufferedReader(new FileReader(dir)); -//// -//// for (int i = 0; i < 4; i++) { -//// br.readLine(); -//// } -//// -//// this.size_ = Integer.parseInt(br.readLine()); -//// -//// for (int i = 1; i <= size_; i++) { -//// String name = br.readLine().trim(); -//// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -//// -//// this.addNode(i, name); -//// } -//// -//// final int edges = Integer.parseInt(br.readLine()); -//// -//// for (int i = 1; i <= edges; i++) { -//// StringTokenizer st = new StringTokenizer(br.readLine()); -//// int node1 = Integer.parseInt(st.nextToken()); -//// int node2 = Integer.parseInt(st.nextToken()); -//// -//// this.addEdge(node1, node2); -//// } -//// -//// br.close(); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// } -// -// private GraphNA() { -// } -// -// public GraphNA(GraphNA graphNA) { -// this.size_ = graphNA.getSize(); -// this.names_ = graphNA.getNames(); -// this.edges_ = graphNA.getEdges(); -// } -// -// public static GraphNA readGraphGWFile(File file) { -// GraphNA ret = new GraphNA(); -// ret.edges_ = new TreeMap>(); -// ret.names_ = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// for (int i = 0; i < 4; i++) { -// br.readLine(); -// } -// -// ret.size_ = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= ret.size_; i++) { -// String name = br.readLine().trim(); -// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -// -// ret.addNode(i, name); -// } -// -// final int edges = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= edges; i++) { -// StringTokenizer st = new StringTokenizer(br.readLine()); -// int node1 = Integer.parseInt(st.nextToken()); -// int node2 = Integer.parseInt(st.nextToken()); -// -// ret.addEdge(node1, node2); -// } -// -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// return ret; -// } -// -// private void addNode(int node, String name) { -// if (edges_.get(name) == null) { -// edges_.put(name, new TreeSet()); -// } -// if (names_.get(node) == null) { -// names_.put(node, name); -// } -// // edges.putIfAbsent(name, new TreeSet()); -// // names.putIfAbsent(node, name); -// } -// -// private void addEdge(int node1, int node2) { -// if (node1 == node2) { -// ExceptionHandler.getHandler().displayException(new IllegalArgumentException("node1 == node2")); -// } -// -// edges_.get(names_.get(node1)).add(names_.get(node2)); -// edges_.get(names_.get(node2)).add(names_.get(node1)); -// } -// -// void updateNames(Map names) { -// -// Map> newEdges = new TreeMap>(); -// -// for (Map.Entry> entry : edges_.entrySet()) { -// String key = entry.getKey(); -// String x = (names.get(key) == null) ? key : names.get(key); -// -// Set newSet = new TreeSet(); -// for (String str : entry.getValue()) { -// String y = (names.get(str) == null) ? str : names.get(str); -// newSet.add(y); -// } -// -// newEdges.put(x, newSet); -// } -// -// edges_ = newEdges; -// } -// -//// public void extractNode(Set set, String seed) throws IOException { -//// -////// Queue queue = new LinkedList<>(); -////// -////// int level = 0, count = 0; -////// queue.add(seed); -////// while (! queue.isEmpty()) { -////// String node = queue.poll(); -////// count = edges.get(node).size(); -////// -////// level++; -////// -////// if (level > maxLevel) break; -////// -////// for (String s : edges.get(node)) { -////// queue.add(s); -////// String[] arr = Parser.sort(node, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// -////// } -////// -////// for (String s : set) { -////// set.add(s); -////// } -//// -//// Set lvl_1 = edges.get(seed), lvl_2 = new TreeSet(); -//// -//// for (String n : lvl_1) { -//// for (String s : edges.get(n)) { -//// lvl_2.add(s); -//// String[] arr = Parser.sort(n, s); -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -////// for (String n : lvl_2) { -////// for (String s : edges.get(n)) { -////// String[] arr = Parser.sort(n, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// } -//// -//// -//// } -// -//// public void toSIF(String dir, String tag) throws IOException { -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// String link = arr[0] + " " + tag + " " + arr[1]; -//// -//// set.add(link); -//// } -//// } -//// -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// for (String s : set) { -//// pw.println(s); -//// } -//// -//// pw.close(); -//// } -// -// @Override -// public String toString() { -// -// int linkNum = 0; -// for (Map.Entry> entry : edges_.entrySet()) { -// linkNum += entry.getValue().size(); -// } -// linkNum /= 2; -// -// return String.format("(V, E) = (%d, %d)", size_, linkNum); -// } -// -// public int getSize() { -// return size_; -// } -// -// public Map getNames() { -// return new TreeMap(names_); -// } -// -// public Map> getEdges() { -// return new TreeMap>(edges_); -// } -// -// } -// -// public static class AlignmentNA { -// -// Map nodeToNode; -// Set nodes; -// GraphNA small_A, large_A; -// -//// public AlignmentNA(File file) { -//// try { -//// BufferedReader br = new BufferedReader(new FileReader(file)); -//// -//// String line; -//// while ((line = br.readLine()) != null) { -//// StringTokenizer st = new StringTokenizer(line); -//// -//// nodeToNode.put(st.nextToken(), st.nextToken()); -//// } -//// br.close(); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// } -// -// private AlignmentNA() { -// } -// -//// public AlignmentNA(File dir, GraphNA small_A, GraphNA large_A) { -//// this.small_A = small_A; -//// this.large_A = large_A; -//// this.nodes = new TreeSet(); -//// -//// nodeToNode = new TreeMap(); -//// -//// try { -//// BufferedReader br = new BufferedReader(new FileReader(dir)); -//// -//// String line; -//// while ((line = br.readLine()) != null) { -//// StringTokenizer st = new StringTokenizer(line); -//// -//// nodeToNode.put(st.nextToken(), st.nextToken()); -//// } -//// br.close(); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// -//// Map smallNames = new TreeMap(); -//// Map largeNames = new TreeMap(); -//// -//// for (Map.Entry entry : nodeToNode.entrySet()) { -//// -//// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -//// -//// smallNames.put(x, xy); -//// largeNames.put(y, xy); -//// -//// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -//// } -//// -//// this.small_A.updateNames(smallNames); -//// this.large_A.updateNames(largeNames); -//// } -// -// public static AlignmentNA readAlignFile(File file) { -// AlignmentNA ret = new AlignmentNA(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// ret.nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// return ret; -// } -// -// private void provide(GraphNA small_A, GraphNA large_A) { -// Map smallNames = new TreeMap(); -// Map largeNames = new TreeMap(); -// -// for (Map.Entry entry : nodeToNode.entrySet()) { -// -// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -// -// smallNames.put(x, xy); -// largeNames.put(y, xy); -// -// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -// } -// -// this.small_A.updateNames(smallNames); -// this.large_A.updateNames(largeNames); -// } -// -//// public void toFiles(String alignDir, String ordDir, String tagS, String tagL) throws IOException { -//// large_A.toSIF(ordDir, "xx"); -//// Parser.toAlignmentSIF(alignDir, this, tagS, tagL); -//// } -// -// @Override -// public String toString() { -// String ret; -// ret = "G1: " + small_A + '\n' + "G2: " + large_A; -// -// return ret; -// } -// -//// public static List writeEdges(Graph G) { -//// -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : G.edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -//// List ret = new ArrayList(); -//// for (String s : set) { -//// ret.add(s); -//// } -//// -//// return ret; -//// } -// -// } -// -// public static class NetworkAlignInfo { -// -// GraphNA small, large; -// AlignmentNA align; -// -// public NetworkAlignInfo(GraphNA small, GraphNA large, AlignmentNA align) { -// this.small = small; -// this.large = large; -// this.align = align; -// } -// -// } -// -// private static class Parser { // FIX ME: THIS CLASS NEEDS TO REMOVED AFTER THE METHODS -// // ARE IMPLEMENTED INSIDE GRAPH, ALIGNMENT, OR NETWORKALIGNMENT, OR NOT AT ALL -// -//// public static void toAlignmentSIF(String dir, Alignment align, String tagS, String tagL) -//// throws IOException { -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// -//// List Sall = Alignment.writeEdges(align.small_A); -//// List Lall = Alignment.writeEdges(align.large_A); -//// -//// Collections.sort(Sall); -//// Collections.sort(Lall); -//// -//// List CC = new ArrayList(); -//// for (String x : Sall) { -//// if (Collections.binarySearch(Lall, x) >= 0) { -//// CC.add(x); -//// } -//// } -//// -//// for (String s : Sall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagS + " " + arr[1]); -//// } -//// -//// for (String s : Lall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagL + " " + arr[1]); -//// } -//// -//// for (String s : CC) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + "CC" + " " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// /** -// * splits parameter by space -// */ -// public static String[] split(String twoNodes) { -// StringTokenizer st = new StringTokenizer(twoNodes); -// return new String[]{st.nextToken(), st.nextToken()}; -// } -// -// /** -// * splits parameter by dash -// */ -// public static String[] splice(String edge) { -// return edge.split("-"); -// } -// -// /** -// * sorts two strings in array -// */ -// public static String[] sort(String a, String b) { -// String[] ret = {a, b}; -// Arrays.sort(ret); -// -// return ret; -// } -// -// /** -// * true if two parts are equal; split by dash -// */ -// public static boolean sameNode(String node) { -// String[] arr = node.split("-"); -// return arr[0].equals(arr[1]); -// } -// -//// public static void write(String filename, Set set) throws IOException { -//// PrintWriter pw = new PrintWriter(new File(filename)); -//// for (String s : set) { -//// String[] arr = Parser.split(s); -//// pw.println(arr[0] + " pp " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// } -// -//} - -///* -//** Copyright (C) 2003-2014 Institute for Systems Biology -//** Seattle, Washington, USA. -//** -//** This library is free software; you can redistribute it and/or -//** modify it under the terms of the GNU Lesser General Public -//** License as published by the Free Software Foundation; either -//** version 2.1 of the License, or (at your option) any later version. -//** -//** This library is distributed in the hope that it will be useful, -//** but WITHOUT ANY WARRANTY; without even the implied warranty of -//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -//** Lesser General Public License for more details. -//** -//** You should have received a copy of the GNU Lesser General Public -//** License along with this library; if not, write to the Free Software -//** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//*/ -// -//package org.systemsbiology.biofabric.analysis; -// -// import org.systemsbiology.biofabric.util.ExceptionHandler; -// -// import java.io.BufferedReader; -// import java.io.File; -// import java.io.FileReader; -// import java.io.IOException; -// import java.util.*; -// -//public class NetworkAlignment { -// -// private GraphNA small, large; -// private AlignmentNA align; -// -// public NetworkAlignment(NetworkAlignInfo nai) { -// -//// GraphNA A = null, B = null; -//// try { -//// A = new GraphNA(nai.small); -//// B = new GraphNA(nai.large); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// -//// if (A == null || B == null) { -//// -//// } -//// -//// if (A.edges.size() >= B.edges.size()) { -//// large = A; -//// small = B; -//// } else { -//// large = B; -//// small = A; -//// } -//// -//// try { -//// align = new AlignmentNA(alignment, small, large); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -// -// this.small = nai.small; -// this.large = nai.large; -// this.align = nai.align; -// -// } -// -// public static class GraphNA { // needs to implement cloneable in future -// -// Map> edges_; -// private Map names_; -// private int size_; -// -// public GraphNA(File dir) { -// this.edges_ = new TreeMap>(); -// this.names_ = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(dir)); -// -// for (int i = 0; i < 4; i++) { -// br.readLine(); -// } -// -// this.size_ = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= size_; i++) { -// String name = br.readLine().trim(); -// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -// -// this.addNode(i, name); -// } -// -// final int edges = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= edges; i++) { -// StringTokenizer st = new StringTokenizer(br.readLine()); -// int node1 = Integer.parseInt(st.nextToken()); -// int node2 = Integer.parseInt(st.nextToken()); -// -// this.addEdge(node1, node2); -// } -// -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// } -// -// public GraphNA(GraphNA graphNA) { -// this.size_ = graphNA.getSize(); -// this.names_ = graphNA.getNames(); -// this.edges_ = graphNA.getEdges(); -// } -// -// private void addNode(int node, String name) { -// if (edges_.get(name) == null) { -// edges_.put(name, new TreeSet()); -// } -// if (names_.get(node) == null) { -// names_.put(node, name); -// } -// // edges.putIfAbsent(name, new TreeSet()); -// // names.putIfAbsent(node, name); -// } -// -// private void addEdge(int node1, int node2) { -// if (node1 == node2) { -// ExceptionHandler.getHandler().displayException(new IllegalArgumentException("node1 == node2")); -// } -// -// edges_.get(names_.get(node1)).add(names_.get(node2)); -// edges_.get(names_.get(node2)).add(names_.get(node1)); -// } -// -// void updateNames(Map names) { -// -// Map> newEdges = new TreeMap>(); -// -// for (Map.Entry> entry : edges_.entrySet()) { -// String key = entry.getKey(); -// String x = (names.get(key) == null) ? key : names.get(key); -// -// Set newSet = new TreeSet(); -// for (String str : entry.getValue()) { -// String y = (names.get(str) == null) ? str : names.get(str); -// newSet.add(y); -// } -// -// newEdges.put(x, newSet); -// } -// -// edges_ = newEdges; -// } -// -//// public void extractNode(Set set, String seed) throws IOException { -//// -////// Queue queue = new LinkedList<>(); -////// -////// int level = 0, count = 0; -////// queue.add(seed); -////// while (! queue.isEmpty()) { -////// String node = queue.poll(); -////// count = edges.get(node).size(); -////// -////// level++; -////// -////// if (level > maxLevel) break; -////// -////// for (String s : edges.get(node)) { -////// queue.add(s); -////// String[] arr = Parser.sort(node, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// -////// } -////// -////// for (String s : set) { -////// set.add(s); -////// } -//// -//// Set lvl_1 = edges.get(seed), lvl_2 = new TreeSet(); -//// -//// for (String n : lvl_1) { -//// for (String s : edges.get(n)) { -//// lvl_2.add(s); -//// String[] arr = Parser.sort(n, s); -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -////// for (String n : lvl_2) { -////// for (String s : edges.get(n)) { -////// String[] arr = Parser.sort(n, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// } -//// -//// -//// } -// -//// public void toSIF(String dir, String tag) throws IOException { -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// String link = arr[0] + " " + tag + " " + arr[1]; -//// -//// set.add(link); -//// } -//// } -//// -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// for (String s : set) { -//// pw.println(s); -//// } -//// -//// pw.close(); -//// } -// -// @Override -// public String toString() { -// -// int linkNum = 0; -// for (Map.Entry> entry : edges_.entrySet()) { -// linkNum += entry.getValue().size(); -// } -// linkNum /= 2; -// -// return String.format("(V, E) = (%d, %d)", size_, linkNum); -// } -// -// public int getSize() { -// return size_; -// } -// -// public Map getNames() { -// return new TreeMap(names_); -// } -// -// public Map> getEdges() { -// return new TreeMap>(edges_); -// } -// -// } -// -// -// public static class AlignmentNA { -// -// Map nodeToNode; -// Set nodes; -// GraphNA small_A, large_A; -// -// public AlignmentNA(File file) { -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// } -// -// public AlignmentNA(File dir, GraphNA small_A, GraphNA large_A) { -// this.small_A = small_A; -// this.large_A = large_A; -// this.nodes = new TreeSet(); -// -// nodeToNode = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(dir)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// Map smallNames = new TreeMap(); -// Map largeNames = new TreeMap(); -// -// for (Map.Entry entry : nodeToNode.entrySet()) { -// -// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -// -// smallNames.put(x, xy); -// largeNames.put(y, xy); -// -// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -// } -// -// this.small_A.updateNames(smallNames); -// this.large_A.updateNames(largeNames); -// } -// -//// public void toFiles(String alignDir, String ordDir, String tagS, String tagL) throws IOException { -//// large_A.toSIF(ordDir, "xx"); -//// Parser.toAlignmentSIF(alignDir, this, tagS, tagL); -//// } -// -// @Override -// public String toString() { -// String ret; -// ret = "G1: " + small_A + '\n' + "G2: " + large_A; -// -// return ret; -// } -// -//// public static List writeEdges(Graph G) { -//// -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : G.edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -//// List ret = new ArrayList(); -//// for (String s : set) { -//// ret.add(s); -//// } -//// -//// return ret; -//// } -// -// } -// -// public static class NetworkAlignInfo { -// -// GraphNA small, large; -// AlignmentNA align; -// -// public NetworkAlignInfo(GraphNA small, GraphNA large, AlignmentNA align) { -// this.small = small; -// this.large = large; -// this.align = align; -// } -// -// } -// -// private static class Parser { // FIX ME: THIS CLASS NEEDS TO REMOVED AFTER THE METHODS -// // ARE IMPLEMENTED INSIDE GRAPH, ALIGNMENT, OR NETWORKALIGNMENT, OR NOT AT ALL -// -//// public static void toAlignmentSIF(String dir, Alignment align, String tagS, String tagL) -//// throws IOException { -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// -//// List Sall = Alignment.writeEdges(align.small_A); -//// List Lall = Alignment.writeEdges(align.large_A); -//// -//// Collections.sort(Sall); -//// Collections.sort(Lall); -//// -//// List CC = new ArrayList(); -//// for (String x : Sall) { -//// if (Collections.binarySearch(Lall, x) >= 0) { -//// CC.add(x); -//// } -//// } -//// -//// for (String s : Sall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagS + " " + arr[1]); -//// } -//// -//// for (String s : Lall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagL + " " + arr[1]); -//// } -//// -//// for (String s : CC) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + "CC" + " " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// /** -// * splits parameter by space -// */ -// public static String[] split(String twoNodes) { -// StringTokenizer st = new StringTokenizer(twoNodes); -// return new String[]{st.nextToken(), st.nextToken()}; -// } -// -// /** -// * splits parameter by dash -// */ -// public static String[] splice(String edge) { -// return edge.split("-"); -// } -// -// /** -// * sorts two strings in array -// */ -// public static String[] sort(String a, String b) { -// String[] ret = {a, b}; -// Arrays.sort(ret); -// -// return ret; -// } -// -// /** -// * true if two parts are equal; split by dash -// */ -// public static boolean sameNode(String node) { -// String[] arr = node.split("-"); -// return arr[0].equals(arr[1]); -// } -// -//// public static void write(String filename, Set set) throws IOException { -//// PrintWriter pw = new PrintWriter(new File(filename)); -//// for (String s : set) { -//// String[] arr = Parser.split(s); -//// pw.println(arr[0] + " pp " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// } -// -//} - - -///* -//** Copyright (C) 2003-2014 Institute for Systems Biology -//** Seattle, Washington, USA. -//** -//** This library is free software; you can redistribute it and/or -//** modify it under the terms of the GNU Lesser General Public -//** License as published by the Free Software Foundation; either -//** version 2.1 of the License, or (at your option) any later version. -//** -//** This library is distributed in the hope that it will be useful, -//** but WITHOUT ANY WARRANTY; without even the implied warranty of -//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -//** Lesser General Public License for more details. -//** -//** You should have received a copy of the GNU Lesser General Public -//** License along with this library; if not, write to the Free Software -//** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//*/ -// -//package org.systemsbiology.biofabric.analysis; -// -// import org.systemsbiology.biofabric.util.ExceptionHandler; -// -// import java.io.BufferedReader; -// import java.io.File; -// import java.io.FileReader; -// import java.io.IOException; -// import java.util.*; -// -//public class NetworkAlignment { -// -// private GraphNA small, large; -// private AlignmentNA align; -// -// public NetworkAlignment(NetworkAlignInfo nai) { -// -//// GraphNA A = null, B = null; -//// try { -//// A = new GraphNA(nai.small); -//// B = new GraphNA(nai.large); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// -//// if (A == null || B == null) { -//// -//// } -//// -//// if (A.edges.size() >= B.edges.size()) { -//// large = A; -//// small = B; -//// } else { -//// large = B; -//// small = A; -//// } -//// -//// try { -//// align = new AlignmentNA(alignment, small, large); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -// -// this.small = nai.small; -// this.large = nai.large; -// this.align = nai.align; -// -// } -// -// public static class GraphNA { // needs to implement cloneable in future -// -// Map> edges_; -// private Map names_; -// private int size_; -// -// public GraphNA(File dir) { -// this.edges_ = new TreeMap>(); -// this.names_ = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(dir)); -// -// for (int i = 0; i < 4; i++) { -// br.readLine(); -// } -// -// this.size_ = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= size_; i++) { -// String name = br.readLine().trim(); -// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -// -// this.addNode(i, name); -// } -// -// final int edges = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= edges; i++) { -// StringTokenizer st = new StringTokenizer(br.readLine()); -// int node1 = Integer.parseInt(st.nextToken()); -// int node2 = Integer.parseInt(st.nextToken()); -// -// this.addEdge(node1, node2); -// } -// -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// } -// -// public GraphNA(GraphNA graphNA) { -// this.size_ = graphNA.getSize(); -// this.names_ = graphNA.getNames(); -// this.edges_ = graphNA.getEdges(); -// } -// -// private void addNode(int node, String name) { -// if (edges_.get(name) == null) { -// edges_.put(name, new TreeSet()); -// } -// if (names_.get(node) == null) { -// names_.put(node, name); -// } -// // edges.putIfAbsent(name, new TreeSet()); -// // names.putIfAbsent(node, name); -// } -// -// private void addEdge(int node1, int node2) { -// if (node1 == node2) { -// ExceptionHandler.getHandler().displayException(new IllegalArgumentException("node1 == node2")); -// } -// -// edges_.get(names_.get(node1)).add(names_.get(node2)); -// edges_.get(names_.get(node2)).add(names_.get(node1)); -// } -// -// void updateNames(Map names) { -// -// Map> newEdges = new TreeMap>(); -// -// for (Map.Entry> entry : edges_.entrySet()) { -// String key = entry.getKey(); -// String x = (names.get(key) == null) ? key : names.get(key); -// -// Set newSet = new TreeSet(); -// for (String str : entry.getValue()) { -// String y = (names.get(str) == null) ? str : names.get(str); -// newSet.add(y); -// } -// -// newEdges.put(x, newSet); -// } -// -// edges_ = newEdges; -// } -// -//// public void extractNode(Set set, String seed) throws IOException { -//// -////// Queue queue = new LinkedList<>(); -////// -////// int level = 0, count = 0; -////// queue.add(seed); -////// while (! queue.isEmpty()) { -////// String node = queue.poll(); -////// count = edges.get(node).size(); -////// -////// level++; -////// -////// if (level > maxLevel) break; -////// -////// for (String s : edges.get(node)) { -////// queue.add(s); -////// String[] arr = Parser.sort(node, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// -////// } -////// -////// for (String s : set) { -////// set.add(s); -////// } -//// -//// Set lvl_1 = edges.get(seed), lvl_2 = new TreeSet(); -//// -//// for (String n : lvl_1) { -//// for (String s : edges.get(n)) { -//// lvl_2.add(s); -//// String[] arr = Parser.sort(n, s); -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -////// for (String n : lvl_2) { -////// for (String s : edges.get(n)) { -////// String[] arr = Parser.sort(n, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// } -//// -//// -//// } -// -//// public void toSIF(String dir, String tag) throws IOException { -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// String link = arr[0] + " " + tag + " " + arr[1]; -//// -//// set.add(link); -//// } -//// } -//// -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// for (String s : set) { -//// pw.println(s); -//// } -//// -//// pw.close(); -//// } -// -// @Override -// public String toString() { -// -// int linkNum = 0; -// for (Map.Entry> entry : edges_.entrySet()) { -// linkNum += entry.getValue().size(); -// } -// linkNum /= 2; -// -// return String.format("(V, E) = (%d, %d)", size_, linkNum); -// } -// -// public int getSize() { -// return size_; -// } -// -// public Map getNames() { -// return new TreeMap(names_); -// } -// -// public Map> getEdges() { -// return new TreeMap>(edges_); -// } -// -// } -// -// -// public static class AlignmentNA { -// -// Map nodeToNode; -// Set nodes; -// GraphNA small_A, large_A; -// -// public AlignmentNA(File file) { -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// } -// -// public AlignmentNA(File dir, GraphNA small_A, GraphNA large_A) { -// this.small_A = small_A; -// this.large_A = large_A; -// this.nodes = new TreeSet(); -// -// nodeToNode = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(dir)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// Map smallNames = new TreeMap(); -// Map largeNames = new TreeMap(); -// -// for (Map.Entry entry : nodeToNode.entrySet()) { -// -// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -// -// smallNames.put(x, xy); -// largeNames.put(y, xy); -// -// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -// } -// -// this.small_A.updateNames(smallNames); -// this.large_A.updateNames(largeNames); -// } -// -//// public void toFiles(String alignDir, String ordDir, String tagS, String tagL) throws IOException { -//// large_A.toSIF(ordDir, "xx"); -//// Parser.toAlignmentSIF(alignDir, this, tagS, tagL); -//// } -// -// @Override -// public String toString() { -// String ret; -// ret = "G1: " + small_A + '\n' + "G2: " + large_A; -// -// return ret; -// } -// -//// public static List writeEdges(Graph G) { -//// -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : G.edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -//// List ret = new ArrayList(); -//// for (String s : set) { -//// ret.add(s); -//// } -//// -//// return ret; -//// } -// -// } -// -// public static class NetworkAlignInfo { -// -// GraphNA small, large; -// AlignmentNA align; -// -// public NetworkAlignInfo(GraphNA small, GraphNA large, AlignmentNA align) { -// this.small = small; -// this.large = large; -// this.align = align; -// } -// -// } -// -// private static class Parser { // FIX ME: THIS CLASS NEEDS TO REMOVED AFTER THE METHODS -// // ARE IMPLEMENTED INSIDE GRAPH, ALIGNMENT, OR NETWORKALIGNMENT, OR NOT AT ALL -// -//// public static void toAlignmentSIF(String dir, Alignment align, String tagS, String tagL) -//// throws IOException { -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// -//// List Sall = Alignment.writeEdges(align.small_A); -//// List Lall = Alignment.writeEdges(align.large_A); -//// -//// Collections.sort(Sall); -//// Collections.sort(Lall); -//// -//// List CC = new ArrayList(); -//// for (String x : Sall) { -//// if (Collections.binarySearch(Lall, x) >= 0) { -//// CC.add(x); -//// } -//// } -//// -//// for (String s : Sall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagS + " " + arr[1]); -//// } -//// -//// for (String s : Lall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagL + " " + arr[1]); -//// } -//// -//// for (String s : CC) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + "CC" + " " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// /** -// * splits parameter by space -// */ -// public static String[] split(String twoNodes) { -// StringTokenizer st = new StringTokenizer(twoNodes); -// return new String[]{st.nextToken(), st.nextToken()}; -// } -// -// /** -// * splits parameter by dash -// */ -// public static String[] splice(String edge) { -// return edge.split("-"); -// } -// -// /** -// * sorts two strings in array -// */ -// public static String[] sort(String a, String b) { -// String[] ret = {a, b}; -// Arrays.sort(ret); -// -// return ret; -// } -// -// /** -// * true if two parts are equal; split by dash -// */ -// public static boolean sameNode(String node) { -// String[] arr = node.split("-"); -// return arr[0].equals(arr[1]); -// } -// -//// public static void write(String filename, Set set) throws IOException { -//// PrintWriter pw = new PrintWriter(new File(filename)); -//// for (String s : set) { -//// String[] arr = Parser.split(s); -//// pw.println(arr[0] + " pp " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// } -// -//} - - - - - -///* -//** Copyright (C) 2003-2014 Institute for Systems Biology -//** Seattle, Washington, USA. -//** -//** This library is free software; you can redistribute it and/or -//** modify it under the terms of the GNU Lesser General Public -//** License as published by the Free Software Foundation; either -//** version 2.1 of the License, or (at your option) any later version. -//** -//** This library is distributed in the hope that it will be useful, -//** but WITHOUT ANY WARRANTY; without even the implied warranty of -//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -//** Lesser General Public License for more details. -//** -//** You should have received a copy of the GNU Lesser General Public -//** License along with this library; if not, write to the Free Software -//** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//*/ -// -//package org.systemsbiology.biofabric.analysis; -// -// import org.systemsbiology.biofabric.util.ExceptionHandler; -// -// import java.io.BufferedReader; -// import java.io.File; -// import java.io.FileReader; -// import java.io.IOException; -// import java.util.*; -// -//public class NetworkAlignment { -// -// private GraphNA small, large; -// private AlignmentNA align; -// -// public NetworkAlignment(NetworkAlignInfo nai) { -// -// this.small = nai.small; -// this.large = nai.large; -// this.align = nai.align; -// -// } -// -// public static class GraphNA { // needs to implement cloneable in future -// -// Map> edges_; -// private Map names_; -// private int size_; -// -//// public GraphNA(File dir) { -//// -//// this.edges_ = new TreeMap>(); -//// this.names_ = new TreeMap(); -//// -//// try { -//// BufferedReader br = new BufferedReader(new FileReader(dir)); -//// -//// for (int i = 0; i < 4; i++) { -//// br.readLine(); -//// } -//// -//// this.size_ = Integer.parseInt(br.readLine()); -//// -//// for (int i = 1; i <= size_; i++) { -//// String name = br.readLine().trim(); -//// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -//// -//// this.addNode(i, name); -//// } -//// -//// final int edges = Integer.parseInt(br.readLine()); -//// -//// for (int i = 1; i <= edges; i++) { -//// StringTokenizer st = new StringTokenizer(br.readLine()); -//// int node1 = Integer.parseInt(st.nextToken()); -//// int node2 = Integer.parseInt(st.nextToken()); -//// -//// this.addEdge(node1, node2); -//// } -//// -//// br.close(); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// } -// -// private GraphNA() { -// } -// -// public GraphNA(GraphNA graphNA) { -// this.size_ = graphNA.getSize(); -// this.names_ = graphNA.getNames(); -// this.edges_ = graphNA.getEdges(); -// } -// -// public static GraphNA readGraphGWFile(File file) { -// GraphNA ret = new GraphNA(); -// ret.edges_ = new TreeMap>(); -// ret.names_ = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// for (int i = 0; i < 4; i++) { -// br.readLine(); -// } -// -// ret.size_ = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= ret.size_; i++) { -// String name = br.readLine().trim(); -// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -// -// ret.addNode(i, name); -// } -// -// final int edges = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= edges; i++) { -// StringTokenizer st = new StringTokenizer(br.readLine()); -// int node1 = Integer.parseInt(st.nextToken()); -// int node2 = Integer.parseInt(st.nextToken()); -// -// ret.addEdge(node1, node2); -// } -// -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// return ret; -// } -// -// private void addNode(int node, String name) { -// if (edges_.get(name) == null) { -// edges_.put(name, new TreeSet()); -// } -// if (names_.get(node) == null) { -// names_.put(node, name); -// } -// // edges.putIfAbsent(name, new TreeSet()); -// // names.putIfAbsent(node, name); -// } -// -// private void addEdge(int node1, int node2) { -// if (node1 == node2) { -// ExceptionHandler.getHandler().displayException(new IllegalArgumentException("node1 == node2")); -// } -// -// edges_.get(names_.get(node1)).add(names_.get(node2)); -// edges_.get(names_.get(node2)).add(names_.get(node1)); -// } -// -// void updateNames(Map names) { -// -// Map> newEdges = new TreeMap>(); -// -// for (Map.Entry> entry : edges_.entrySet()) { -// String key = entry.getKey(); -// String x = (names.get(key) == null) ? key : names.get(key); -// -// Set newSet = new TreeSet(); -// for (String str : entry.getValue()) { -// String y = (names.get(str) == null) ? str : names.get(str); -// newSet.add(y); -// } -// -// newEdges.put(x, newSet); -// } -// -// edges_ = newEdges; -// } -// -//// public void extractNode(Set set, String seed) throws IOException { -//// -////// Queue queue = new LinkedList<>(); -////// -////// int level = 0, count = 0; -////// queue.add(seed); -////// while (! queue.isEmpty()) { -////// String node = queue.poll(); -////// count = edges.get(node).size(); -////// -////// level++; -////// -////// if (level > maxLevel) break; -////// -////// for (String s : edges.get(node)) { -////// queue.add(s); -////// String[] arr = Parser.sort(node, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// -////// } -////// -////// for (String s : set) { -////// set.add(s); -////// } -//// -//// Set lvl_1 = edges.get(seed), lvl_2 = new TreeSet(); -//// -//// for (String n : lvl_1) { -//// for (String s : edges.get(n)) { -//// lvl_2.add(s); -//// String[] arr = Parser.sort(n, s); -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -////// for (String n : lvl_2) { -////// for (String s : edges.get(n)) { -////// String[] arr = Parser.sort(n, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// } -//// -//// -//// } -// -//// public void toSIF(String dir, String tag) throws IOException { -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// String link = arr[0] + " " + tag + " " + arr[1]; -//// -//// set.add(link); -//// } -//// } -//// -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// for (String s : set) { -//// pw.println(s); -//// } -//// -//// pw.close(); -//// } -// -// @Override -// public String toString() { -// -// int linkNum = 0; -// for (Map.Entry> entry : edges_.entrySet()) { -// linkNum += entry.getValue().size(); -// } -// linkNum /= 2; -// -// return String.format("(V, E) = (%d, %d)", size_, linkNum); -// } -// -// public int getSize() { -// return size_; -// } -// -// public Map getNames() { -// return new TreeMap(names_); -// } -// -// public Map> getEdges() { -// return new TreeMap>(edges_); -// } -// -// } -// -// public static class AlignmentNA { -// -// Map nodeToNode; -// Set nodes; -// GraphNA small_A, large_A; -// -//// public AlignmentNA(File file) { -//// try { -//// BufferedReader br = new BufferedReader(new FileReader(file)); -//// -//// String line; -//// while ((line = br.readLine()) != null) { -//// StringTokenizer st = new StringTokenizer(line); -//// -//// nodeToNode.put(st.nextToken(), st.nextToken()); -//// } -//// br.close(); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// } -// -// private AlignmentNA() { -// } -// -//// public AlignmentNA(File dir, GraphNA small_A, GraphNA large_A) { -//// this.small_A = small_A; -//// this.large_A = large_A; -//// this.nodes = new TreeSet(); -//// -//// nodeToNode = new TreeMap(); -//// -//// try { -//// BufferedReader br = new BufferedReader(new FileReader(dir)); -//// -//// String line; -//// while ((line = br.readLine()) != null) { -//// StringTokenizer st = new StringTokenizer(line); -//// -//// nodeToNode.put(st.nextToken(), st.nextToken()); -//// } -//// br.close(); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// -//// Map smallNames = new TreeMap(); -//// Map largeNames = new TreeMap(); -//// -//// for (Map.Entry entry : nodeToNode.entrySet()) { -//// -//// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -//// -//// smallNames.put(x, xy); -//// largeNames.put(y, xy); -//// -//// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -//// } -//// -//// this.small_A.updateNames(smallNames); -//// this.large_A.updateNames(largeNames); -//// } -// -// public static AlignmentNA readAlignFile(File file) { -// AlignmentNA ret = new AlignmentNA(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// ret.nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// return ret; -// } -// -// private void provide(GraphNA small_A, GraphNA large_A) { -// Map smallNames = new TreeMap(); -// Map largeNames = new TreeMap(); -// -// for (Map.Entry entry : nodeToNode.entrySet()) { -// -// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -// -// smallNames.put(x, xy); -// largeNames.put(y, xy); -// -// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -// } -// -// this.small_A.updateNames(smallNames); -// this.large_A.updateNames(largeNames); -// } -// -//// public void toFiles(String alignDir, String ordDir, String tagS, String tagL) throws IOException { -//// large_A.toSIF(ordDir, "xx"); -//// Parser.toAlignmentSIF(alignDir, this, tagS, tagL); -//// } -// -// @Override -// public String toString() { -// String ret; -// ret = "G1: " + small_A + '\n' + "G2: " + large_A; -// -// return ret; -// } -// -//// public static List writeEdges(Graph G) { -//// -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : G.edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -//// List ret = new ArrayList(); -//// for (String s : set) { -//// ret.add(s); -//// } -//// -//// return ret; -//// } -// -// } -// -// public static class NetworkAlignInfo { -// -// GraphNA small, large; -// AlignmentNA align; -// -// public NetworkAlignInfo(GraphNA small, GraphNA large, AlignmentNA align) { -// this.small = small; -// this.large = large; -// this.align = align; -// } -// -// } -// -// private static class Parser { // FIX ME: THIS CLASS NEEDS TO REMOVED AFTER THE METHODS -// // ARE IMPLEMENTED INSIDE GRAPH, ALIGNMENT, OR NETWORKALIGNMENT, OR NOT AT ALL -// -//// public static void toAlignmentSIF(String dir, Alignment align, String tagS, String tagL) -//// throws IOException { -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// -//// List Sall = Alignment.writeEdges(align.small_A); -//// List Lall = Alignment.writeEdges(align.large_A); -//// -//// Collections.sort(Sall); -//// Collections.sort(Lall); -//// -//// List CC = new ArrayList(); -//// for (String x : Sall) { -//// if (Collections.binarySearch(Lall, x) >= 0) { -//// CC.add(x); -//// } -//// } -//// -//// for (String s : Sall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagS + " " + arr[1]); -//// } -//// -//// for (String s : Lall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagL + " " + arr[1]); -//// } -//// -//// for (String s : CC) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + "CC" + " " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// /** -// * splits parameter by space -// */ -// public static String[] split(String twoNodes) { -// StringTokenizer st = new StringTokenizer(twoNodes); -// return new String[]{st.nextToken(), st.nextToken()}; -// } -// -// /** -// * splits parameter by dash -// */ -// public static String[] splice(String edge) { -// return edge.split("-"); -// } -// -// /** -// * sorts two strings in array -// */ -// public static String[] sort(String a, String b) { -// String[] ret = {a, b}; -// Arrays.sort(ret); -// -// return ret; -// } -// -// /** -// * true if two parts are equal; split by dash -// */ -// public static boolean sameNode(String node) { -// String[] arr = node.split("-"); -// return arr[0].equals(arr[1]); -// } -// -//// public static void write(String filename, Set set) throws IOException { -//// PrintWriter pw = new PrintWriter(new File(filename)); -//// for (String s : set) { -//// String[] arr = Parser.split(s); -//// pw.println(arr[0] + " pp " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// } -// -//} - -///* -//** Copyright (C) 2003-2014 Institute for Systems Biology -//** Seattle, Washington, USA. -//** -//** This library is free software; you can redistribute it and/or -//** modify it under the terms of the GNU Lesser General Public -//** License as published by the Free Software Foundation; either -//** version 2.1 of the License, or (at your option) any later version. -//** -//** This library is distributed in the hope that it will be useful, -//** but WITHOUT ANY WARRANTY; without even the implied warranty of -//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -//** Lesser General Public License for more details. -//** -//** You should have received a copy of the GNU Lesser General Public -//** License along with this library; if not, write to the Free Software -//** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//*/ -// -//package org.systemsbiology.biofabric.analysis; -// -// import org.systemsbiology.biofabric.util.ExceptionHandler; -// -// import java.io.BufferedReader; -// import java.io.File; -// import java.io.FileReader; -// import java.io.IOException; -// import java.util.*; -// -//public class NetworkAlignment { -// -// private GraphNA small, large; -// private AlignmentNA align; -// -// public NetworkAlignment(NetworkAlignInfo nai) { -// -//// GraphNA A = null, B = null; -//// try { -//// A = new GraphNA(nai.small); -//// B = new GraphNA(nai.large); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// -//// if (A == null || B == null) { -//// -//// } -//// -//// if (A.edges.size() >= B.edges.size()) { -//// large = A; -//// small = B; -//// } else { -//// large = B; -//// small = A; -//// } -//// -//// try { -//// align = new AlignmentNA(alignment, small, large); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -// -// this.small = nai.small; -// this.large = nai.large; -// this.align = nai.align; -// -// } -// -// public static class GraphNA { // needs to implement cloneable in future -// -// Map> edges_; -// private Map names_; -// private int size_; -// -// public GraphNA(File dir) { -// this.edges_ = new TreeMap>(); -// this.names_ = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(dir)); -// -// for (int i = 0; i < 4; i++) { -// br.readLine(); -// } -// -// this.size_ = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= size_; i++) { -// String name = br.readLine().trim(); -// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -// -// this.addNode(i, name); -// } -// -// final int edges = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= edges; i++) { -// StringTokenizer st = new StringTokenizer(br.readLine()); -// int node1 = Integer.parseInt(st.nextToken()); -// int node2 = Integer.parseInt(st.nextToken()); -// -// this.addEdge(node1, node2); -// } -// -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// } -// -// public GraphNA(GraphNA graphNA) { -// this.size_ = graphNA.getSize(); -// this.names_ = graphNA.getNames(); -// this.edges_ = graphNA.getEdges(); -// } -// -// private void addNode(int node, String name) { -// if (edges_.get(name) == null) { -// edges_.put(name, new TreeSet()); -// } -// if (names_.get(node) == null) { -// names_.put(node, name); -// } -// // edges.putIfAbsent(name, new TreeSet()); -// // names.putIfAbsent(node, name); -// } -// -// private void addEdge(int node1, int node2) { -// if (node1 == node2) { -// ExceptionHandler.getHandler().displayException(new IllegalArgumentException("node1 == node2")); -// } -// -// edges_.get(names_.get(node1)).add(names_.get(node2)); -// edges_.get(names_.get(node2)).add(names_.get(node1)); -// } -// -// void updateNames(Map names) { -// -// Map> newEdges = new TreeMap>(); -// -// for (Map.Entry> entry : edges_.entrySet()) { -// String key = entry.getKey(); -// String x = (names.get(key) == null) ? key : names.get(key); -// -// Set newSet = new TreeSet(); -// for (String str : entry.getValue()) { -// String y = (names.get(str) == null) ? str : names.get(str); -// newSet.add(y); -// } -// -// newEdges.put(x, newSet); -// } -// -// edges_ = newEdges; -// } -// -//// public void extractNode(Set set, String seed) throws IOException { -//// -////// Queue queue = new LinkedList<>(); -////// -////// int level = 0, count = 0; -////// queue.add(seed); -////// while (! queue.isEmpty()) { -////// String node = queue.poll(); -////// count = edges.get(node).size(); -////// -////// level++; -////// -////// if (level > maxLevel) break; -////// -////// for (String s : edges.get(node)) { -////// queue.add(s); -////// String[] arr = Parser.sort(node, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// -////// } -////// -////// for (String s : set) { -////// set.add(s); -////// } -//// -//// Set lvl_1 = edges.get(seed), lvl_2 = new TreeSet(); -//// -//// for (String n : lvl_1) { -//// for (String s : edges.get(n)) { -//// lvl_2.add(s); -//// String[] arr = Parser.sort(n, s); -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -////// for (String n : lvl_2) { -////// for (String s : edges.get(n)) { -////// String[] arr = Parser.sort(n, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// } -//// -//// -//// } -// -//// public void toSIF(String dir, String tag) throws IOException { -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// String link = arr[0] + " " + tag + " " + arr[1]; -//// -//// set.add(link); -//// } -//// } -//// -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// for (String s : set) { -//// pw.println(s); -//// } -//// -//// pw.close(); -//// } -// -// @Override -// public String toString() { -// -// int linkNum = 0; -// for (Map.Entry> entry : edges_.entrySet()) { -// linkNum += entry.getValue().size(); -// } -// linkNum /= 2; -// -// return String.format("(V, E) = (%d, %d)", size_, linkNum); -// } -// -// public int getSize() { -// return size_; -// } -// -// public Map getNames() { -// return new TreeMap(names_); -// } -// -// public Map> getEdges() { -// return new TreeMap>(edges_); -// } -// -// } -// -// -// public static class AlignmentNA { -// -// Map nodeToNode; -// Set nodes; -// GraphNA small_A, large_A; -// -// public AlignmentNA(File file) { -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// } -// -// public AlignmentNA(File dir, GraphNA small_A, GraphNA large_A) { -// this.small_A = small_A; -// this.large_A = large_A; -// this.nodes = new TreeSet(); -// -// nodeToNode = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(dir)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// Map smallNames = new TreeMap(); -// Map largeNames = new TreeMap(); -// -// for (Map.Entry entry : nodeToNode.entrySet()) { -// -// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -// -// smallNames.put(x, xy); -// largeNames.put(y, xy); -// -// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -// } -// -// this.small_A.updateNames(smallNames); -// this.large_A.updateNames(largeNames); -// } -// -//// public void toFiles(String alignDir, String ordDir, String tagS, String tagL) throws IOException { -//// large_A.toSIF(ordDir, "xx"); -//// Parser.toAlignmentSIF(alignDir, this, tagS, tagL); -//// } -// -// @Override -// public String toString() { -// String ret; -// ret = "G1: " + small_A + '\n' + "G2: " + large_A; -// -// return ret; -// } -// -//// public static List writeEdges(Graph G) { -//// -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : G.edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -//// List ret = new ArrayList(); -//// for (String s : set) { -//// ret.add(s); -//// } -//// -//// return ret; -//// } -// -// } -// -// public static class NetworkAlignInfo { -// -// GraphNA small, large; -// AlignmentNA align; -// -// public NetworkAlignInfo(GraphNA small, GraphNA large, AlignmentNA align) { -// this.small = small; -// this.large = large; -// this.align = align; -// } -// -// } -// -// private static class Parser { // FIX ME: THIS CLASS NEEDS TO REMOVED AFTER THE METHODS -// // ARE IMPLEMENTED INSIDE GRAPH, ALIGNMENT, OR NETWORKALIGNMENT, OR NOT AT ALL -// -//// public static void toAlignmentSIF(String dir, Alignment align, String tagS, String tagL) -//// throws IOException { -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// -//// List Sall = Alignment.writeEdges(align.small_A); -//// List Lall = Alignment.writeEdges(align.large_A); -//// -//// Collections.sort(Sall); -//// Collections.sort(Lall); -//// -//// List CC = new ArrayList(); -//// for (String x : Sall) { -//// if (Collections.binarySearch(Lall, x) >= 0) { -//// CC.add(x); -//// } -//// } -//// -//// for (String s : Sall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagS + " " + arr[1]); -//// } -//// -//// for (String s : Lall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagL + " " + arr[1]); -//// } -//// -//// for (String s : CC) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + "CC" + " " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// /** -// * splits parameter by space -// */ -// public static String[] split(String twoNodes) { -// StringTokenizer st = new StringTokenizer(twoNodes); -// return new String[]{st.nextToken(), st.nextToken()}; -// } -// -// /** -// * splits parameter by dash -// */ -// public static String[] splice(String edge) { -// return edge.split("-"); -// } -// -// /** -// * sorts two strings in array -// */ -// public static String[] sort(String a, String b) { -// String[] ret = {a, b}; -// Arrays.sort(ret); -// -// return ret; -// } -// -// /** -// * true if two parts are equal; split by dash -// */ -// public static boolean sameNode(String node) { -// String[] arr = node.split("-"); -// return arr[0].equals(arr[1]); -// } -// -//// public static void write(String filename, Set set) throws IOException { -//// PrintWriter pw = new PrintWriter(new File(filename)); -//// for (String s : set) { -//// String[] arr = Parser.split(s); -//// pw.println(arr[0] + " pp " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// } -// -//} - - -///* -//** Copyright (C) 2003-2014 Institute for Systems Biology -//** Seattle, Washington, USA. -//** -//** This library is free software; you can redistribute it and/or -//** modify it under the terms of the GNU Lesser General Public -//** License as published by the Free Software Foundation; either -//** version 2.1 of the License, or (at your option) any later version. -//** -//** This library is distributed in the hope that it will be useful, -//** but WITHOUT ANY WARRANTY; without even the implied warranty of -//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -//** Lesser General Public License for more details. -//** -//** You should have received a copy of the GNU Lesser General Public -//** License along with this library; if not, write to the Free Software -//** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//*/ -// -//package org.systemsbiology.biofabric.analysis; -// -// import org.systemsbiology.biofabric.util.ExceptionHandler; -// -// import java.io.BufferedReader; -// import java.io.File; -// import java.io.FileReader; -// import java.io.IOException; -// import java.util.*; -// -//public class NetworkAlignment { -// -// private GraphNA small, large; -// private AlignmentNA align; -// -// public NetworkAlignment(NetworkAlignInfo nai) { -// -//// GraphNA A = null, B = null; -//// try { -//// A = new GraphNA(nai.small); -//// B = new GraphNA(nai.large); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -//// -//// if (A == null || B == null) { -//// -//// } -//// -//// if (A.edges.size() >= B.edges.size()) { -//// large = A; -//// small = B; -//// } else { -//// large = B; -//// small = A; -//// } -//// -//// try { -//// align = new AlignmentNA(alignment, small, large); -//// } catch (IOException ioe) { -//// ExceptionHandler.getHandler().displayException(ioe); -//// } -// -// this.small = nai.small; -// this.large = nai.large; -// this.align = nai.align; -// -// } -// -// public static class GraphNA { // needs to implement cloneable in future -// -// Map> edges_; -// private Map names_; -// private int size_; -// -// public GraphNA(File dir) { -// this.edges_ = new TreeMap>(); -// this.names_ = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(dir)); -// -// for (int i = 0; i < 4; i++) { -// br.readLine(); -// } -// -// this.size_ = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= size_; i++) { -// String name = br.readLine().trim(); -// name = name.substring(2, name.length() - 2); // exclude "|{" and "}|" -// -// this.addNode(i, name); -// } -// -// final int edges = Integer.parseInt(br.readLine()); -// -// for (int i = 1; i <= edges; i++) { -// StringTokenizer st = new StringTokenizer(br.readLine()); -// int node1 = Integer.parseInt(st.nextToken()); -// int node2 = Integer.parseInt(st.nextToken()); -// -// this.addEdge(node1, node2); -// } -// -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// } -// -// public GraphNA(GraphNA graphNA) { -// this.size_ = graphNA.getSize(); -// this.names_ = graphNA.getNames(); -// this.edges_ = graphNA.getEdges(); -// } -// -// private void addNode(int node, String name) { -// if (edges_.get(name) == null) { -// edges_.put(name, new TreeSet()); -// } -// if (names_.get(node) == null) { -// names_.put(node, name); -// } -// // edges.putIfAbsent(name, new TreeSet()); -// // names.putIfAbsent(node, name); -// } -// -// private void addEdge(int node1, int node2) { -// if (node1 == node2) { -// ExceptionHandler.getHandler().displayException(new IllegalArgumentException("node1 == node2")); -// } -// -// edges_.get(names_.get(node1)).add(names_.get(node2)); -// edges_.get(names_.get(node2)).add(names_.get(node1)); -// } -// -// void updateNames(Map names) { -// -// Map> newEdges = new TreeMap>(); -// -// for (Map.Entry> entry : edges_.entrySet()) { -// String key = entry.getKey(); -// String x = (names.get(key) == null) ? key : names.get(key); -// -// Set newSet = new TreeSet(); -// for (String str : entry.getValue()) { -// String y = (names.get(str) == null) ? str : names.get(str); -// newSet.add(y); -// } -// -// newEdges.put(x, newSet); -// } -// -// edges_ = newEdges; -// } -// -//// public void extractNode(Set set, String seed) throws IOException { -//// -////// Queue queue = new LinkedList<>(); -////// -////// int level = 0, count = 0; -////// queue.add(seed); -////// while (! queue.isEmpty()) { -////// String node = queue.poll(); -////// count = edges.get(node).size(); -////// -////// level++; -////// -////// if (level > maxLevel) break; -////// -////// for (String s : edges.get(node)) { -////// queue.add(s); -////// String[] arr = Parser.sort(node, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// -////// } -////// -////// for (String s : set) { -////// set.add(s); -////// } -//// -//// Set lvl_1 = edges.get(seed), lvl_2 = new TreeSet(); -//// -//// for (String n : lvl_1) { -//// for (String s : edges.get(n)) { -//// lvl_2.add(s); -//// String[] arr = Parser.sort(n, s); -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -////// for (String n : lvl_2) { -////// for (String s : edges.get(n)) { -////// String[] arr = Parser.sort(n, s); -////// set.add(arr[0] + " " + arr[1]); -////// } -////// } -//// -//// -//// } -// -//// public void toSIF(String dir, String tag) throws IOException { -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// String link = arr[0] + " " + tag + " " + arr[1]; -//// -//// set.add(link); -//// } -//// } -//// -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// for (String s : set) { -//// pw.println(s); -//// } -//// -//// pw.close(); -//// } -// -// @Override -// public String toString() { -// -// int linkNum = 0; -// for (Map.Entry> entry : edges_.entrySet()) { -// linkNum += entry.getValue().size(); -// } -// linkNum /= 2; -// -// return String.format("(V, E) = (%d, %d)", size_, linkNum); -// } -// -// public int getSize() { -// return size_; -// } -// -// public Map getNames() { -// return new TreeMap(names_); -// } -// -// public Map> getEdges() { -// return new TreeMap>(edges_); -// } -// -// } -// -// -// public static class AlignmentNA { -// -// Map nodeToNode; -// Set nodes; -// GraphNA small_A, large_A; -// -// public AlignmentNA(File file) { -// try { -// BufferedReader br = new BufferedReader(new FileReader(file)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// } -// -// public AlignmentNA(File dir, GraphNA small_A, GraphNA large_A) { -// this.small_A = small_A; -// this.large_A = large_A; -// this.nodes = new TreeSet(); -// -// nodeToNode = new TreeMap(); -// -// try { -// BufferedReader br = new BufferedReader(new FileReader(dir)); -// -// String line; -// while ((line = br.readLine()) != null) { -// StringTokenizer st = new StringTokenizer(line); -// -// nodeToNode.put(st.nextToken(), st.nextToken()); -// } -// br.close(); -// } catch (IOException ioe) { -// ExceptionHandler.getHandler().displayException(ioe); -// } -// -// Map smallNames = new TreeMap(); -// Map largeNames = new TreeMap(); -// -// for (Map.Entry entry : nodeToNode.entrySet()) { -// -// String x = entry.getKey(), y = entry.getValue(), xy = x + '-' + y; -// -// smallNames.put(x, xy); -// largeNames.put(y, xy); -// -// nodes.add(xy); // FIX ME: DOESN'T INCLUDE UNALIGNED NODES FROM LARGE GRAPH -// } -// -// this.small_A.updateNames(smallNames); -// this.large_A.updateNames(largeNames); -// } -// -//// public void toFiles(String alignDir, String ordDir, String tagS, String tagL) throws IOException { -//// large_A.toSIF(ordDir, "xx"); -//// Parser.toAlignmentSIF(alignDir, this, tagS, tagL); -//// } -// -// @Override -// public String toString() { -// String ret; -// ret = "G1: " + small_A + '\n' + "G2: " + large_A; -// -// return ret; -// } -// -//// public static List writeEdges(Graph G) { -//// -//// Set set = new TreeSet(); -//// -//// for (Map.Entry> entry : G.edges.entrySet()) { -//// -//// String x = entry.getKey(); -//// -//// for (String y : entry.getValue()) { -//// -//// String[] arr = Parser.sort(x, y); -//// -//// set.add(arr[0] + " " + arr[1]); -//// } -//// } -//// -//// List ret = new ArrayList(); -//// for (String s : set) { -//// ret.add(s); -//// } -//// -//// return ret; -//// } -// -// } -// -// public static class NetworkAlignInfo { -// -// GraphNA small, large; -// AlignmentNA align; -// -// public NetworkAlignInfo(GraphNA small, GraphNA large, AlignmentNA align) { -// this.small = small; -// this.large = large; -// this.align = align; -// } -// -// } -// -// private static class Parser { // FIX ME: THIS CLASS NEEDS TO REMOVED AFTER THE METHODS -// // ARE IMPLEMENTED INSIDE GRAPH, ALIGNMENT, OR NETWORKALIGNMENT, OR NOT AT ALL -// -//// public static void toAlignmentSIF(String dir, Alignment align, String tagS, String tagL) -//// throws IOException { -//// PrintWriter pw = new PrintWriter(new File(dir)); -//// -//// List Sall = Alignment.writeEdges(align.small_A); -//// List Lall = Alignment.writeEdges(align.large_A); -//// -//// Collections.sort(Sall); -//// Collections.sort(Lall); -//// -//// List CC = new ArrayList(); -//// for (String x : Sall) { -//// if (Collections.binarySearch(Lall, x) >= 0) { -//// CC.add(x); -//// } -//// } -//// -//// for (String s : Sall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagS + " " + arr[1]); -//// } -//// -//// for (String s : Lall) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + tagL + " " + arr[1]); -//// } -//// -//// for (String s : CC) { -//// String[] arr = split(s); -//// -//// pw.println(arr[0] + " " + "CC" + " " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// /** -// * splits parameter by space -// */ -// public static String[] split(String twoNodes) { -// StringTokenizer st = new StringTokenizer(twoNodes); -// return new String[]{st.nextToken(), st.nextToken()}; -// } -// -// /** -// * splits parameter by dash -// */ -// public static String[] splice(String edge) { -// return edge.split("-"); -// } -// -// /** -// * sorts two strings in array -// */ -// public static String[] sort(String a, String b) { -// String[] ret = {a, b}; -// Arrays.sort(ret); -// -// return ret; -// } -// -// /** -// * true if two parts are equal; split by dash -// */ -// public static boolean sameNode(String node) { -// String[] arr = node.split("-"); -// return arr[0].equals(arr[1]); -// } -// -//// public static void write(String filename, Set set) throws IOException { -//// PrintWriter pw = new PrintWriter(new File(filename)); -//// for (String s : set) { -//// String[] arr = Parser.split(s); -//// pw.println(arr[0] + " pp " + arr[1]); -//// } -//// -//// pw.close(); -//// } -// -// } -// -//} - diff --git a/src/org/systemsbiology/biofabric/app/BioFabricWindow.java b/src/org/systemsbiology/biofabric/app/BioFabricWindow.java deleted file mode 100644 index c2877a1..0000000 --- a/src/org/systemsbiology/biofabric/app/BioFabricWindow.java +++ /dev/null @@ -1,498 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.app; - -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.ImageIcon; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; -import javax.swing.JSplitPane; -import javax.swing.JToolBar; -import javax.swing.KeyStroke; - -import org.systemsbiology.biofabric.cmd.CommandSet; -import org.systemsbiology.biofabric.ui.display.BioFabricNavAndControl; -import org.systemsbiology.biofabric.ui.display.BioFabricOverview; -import org.systemsbiology.biofabric.ui.display.BioFabricPanel; -import org.systemsbiology.biofabric.ui.display.FabricMagnifyingTool; -import org.systemsbiology.biofabric.util.BackgroundWorkerControlManager; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.ResourceManager; - -/**************************************************************************** -** -** This is the BioFabric Window! -*/ - -public class BioFabricWindow extends JFrame implements BackgroundWorkerControlManager { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - private BioFabricPanel cp_; - private BioFabricApplication bfa_; - private FabricMagnifyingTool fmt_; - private HashMap actionMap_; - private BioFabricNavAndControl nac_; - private boolean isMain_; - private JPanel hidingPanel_; - private CardLayout myCard_; - private JSplitPane sp_; - private double savedSplitFrac_; - private static final long serialVersionUID = 1L; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public BioFabricWindow(Map args, BioFabricApplication bfa, boolean isMain) { - super((isMain) ? "BioFabric" : "BioFabric: Selected Submodel View"); - bfa_ = bfa; - isMain_ = isMain; - actionMap_ = new HashMap(); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /**************************************************************************** - ** - ** disable - */ - - public void disableControls() { - disableControls(CommandSet.GENERAL_PUSH, true); - return; - } - - /*************************************************************************** - ** - ** Disable the main controls - */ - - public void disableControls(int pushFlags, boolean displayToo) { - CommandSet fc = CommandSet.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); - if (displayToo) { - myCard_.show(hidingPanel_, "Hiding"); - fmt_.enableControls(false); - nac_.getOverview().showView(false); - } - nac_.getNavTool().enableControls(false); - getContentPane().validate(); - fc.pushDisabled(pushFlags); - } - - /**************************************************************************** - ** - ** enable - */ - - public void reenableControls() { - CommandSet fc = CommandSet.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); - fc.popDisabled(); - myCard_.show(hidingPanel_, "SUPanel"); - fmt_.enableControls(true); - nac_.getOverview().showView(true); - nac_.getNavTool().enableControls(true); - getContentPane().validate(); - - // - // Following background thread operations, sometimes we need to - // get keyboard focus back to the network panel: - // - // We make this conditional to keep it from being called in normal operation as - // the genome is changed, which causes the time slider to lose focus EVERY - // TIME IT IS MOVED!!!!!!! - - // if (withFocus) { - // sup_.requestFocus(); - // } - - return; - } - - /**************************************************************************** - ** - ** also redraw.... - */ - - public void redraw() { - cp_.repaint(); - return; - } - - /*************************************************************************** - ** - ** Get it up and running - */ - - public void initWindow(Dimension dim) { - JPanel cpane = (JPanel)getContentPane(); - ((JComponent)cpane).getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ESCAPE"), "BioTapCancel"); - ((JComponent)cpane).getActionMap().put("BioTapCancel", new AbstractAction() { - private static final long serialVersionUID = 1L; - public void actionPerformed(ActionEvent e) { - try { - AbstractAction aa = (AbstractAction)actionMap_.get(Integer.valueOf(CommandSet.CANCEL)); - aa.actionPerformed(null); - return; - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - CommandSet fc = CommandSet.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); - JToolBar toolBar = null; - - menuInstall(fc, isMain_); - toolBar = new JToolBar(); - stockActionMap(fc, isMain_); - stockToolBar(toolBar, isMain_, fc); - nac_ = new BioFabricNavAndControl(isMain_, this); - fmt_ = nac_.getFMT(); - cp_ = new BioFabricPanel(fc.getColorGenerator(), bfa_, fmt_, nac_.getOverview(), nac_.getNavTool(), isMain_, this); - fc.setFabricPanel(cp_); - nac_.setFabricPanel(cp_); - cp_.setFabricLocation(nac_.getFabricLocation(), nac_.getMouseOverView()); - cp_.setBackground(Color.white); - - JScrollPane jsp = new JScrollPane(cp_); - cp_.setScroll(jsp); - // GOTTA USE THIS ON MY LINUX BOX, BUT NOWHERE ELSE!!!! - //jsp.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); - cp_.getZoomController().registerScrollPaneAndZoomTarget(jsp, cp_); - - cpane.setLayout(new BorderLayout()); - - if (toolBar != null) { - cpane.add(toolBar, BorderLayout.NORTH); - } - - hidingPanel_ = new JPanel(); - myCard_ = new CardLayout(); - hidingPanel_.setLayout(myCard_); - hidingPanel_.add(jsp, "SUPanel"); - JPanel blankPanel = new JPanel(); - blankPanel.setBackground(Color.white); - hidingPanel_.add(blankPanel, "Hiding"); - - sp_ = new JSplitPane(JSplitPane.VERTICAL_SPLIT, hidingPanel_, nac_); - sp_.setDividerLocation((int)(dim.height * 0.50)); - sp_.setResizeWeight(1.0); - - - cpane.add(sp_, BorderLayout.CENTER); - // cpane.add(nac_, BorderLayout.SOUTH); - - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/BioFab16White.gif"); - setIconImage(new ImageIcon(ugif).getImage()); - setResizable(true); - fc.checkForChanges(); - return; - } - - /*************************************************************************** - ** - ** Drawing core - */ - - public void stopBufferBuilding() { - cp_.shutdown(); - return; - } - - /*************************************************************************** - ** - ** Drawing core - */ - - public BioFabricApplication getApplication() { - return (bfa_); - } - - /*************************************************************************** - ** - ** Get fabric panel - */ - - public BioFabricPanel getFabricPanel() { - return (cp_); - } - - /*************************************************************************** - ** - ** Get overvoew panel - */ - - public BioFabricOverview getOverview() { - return (nac_.getOverview()); - } - - /*************************************************************************** - ** - ** Hide/show nav and controls - */ - - public void showNavAndControl(boolean show) { - if (show) { - sp_.setEnabled(true); - nac_.setToBlank(!show); - sp_.setDividerLocation(savedSplitFrac_); - } else { - nac_.setToBlank(!show); - int lastLoc = sp_.getDividerLocation(); - savedSplitFrac_ = (double)lastLoc / (double)sp_.getHeight(); - sp_.setDividerLocation(1.0); - sp_.setEnabled(false); - } - return; - } - - /*************************************************************************** - ** - ** Hide/show nav and controls - */ - - public void showTour(boolean show) { - if (nac_.showTour(show)) { - sp_.resetToPreferredSizes(); - } - return; - } - - /*************************************************************************** - ** - ** Menu install - */ - - private void menuInstall(CommandSet fc, boolean isMain) { - ResourceManager rMan = ResourceManager.getManager(); - JMenuBar menuBar = new JMenuBar(); - - if (isMain) { - JMenu fMenu = new JMenu(rMan.getString("command.File")); - fMenu.setMnemonic(rMan.getChar("command.FileMnem")); - menuBar.add(fMenu); - fMenu.add(fc.getAction(CommandSet.LOAD_XML, false, null)); - fMenu.add(fc.getAction(CommandSet.SAVE, false, null)); - fMenu.add(fc.getAction(CommandSet.SAVE_AS, false, null)); - fMenu.add(new JSeparator()); - JMenu importMenu = new JMenu(rMan.getString("command.importMenu")); - importMenu.setMnemonic(rMan.getChar("command.importMenuMnem")); - fMenu.add(importMenu); - importMenu.add(fc.getAction(CommandSet.LOAD, false, null)); - importMenu.add(fc.getAction(CommandSet.LOAD_WITH_NODE_ATTRIBUTES, false, null)); - importMenu.add(fc.getAction(CommandSet.LOAD_WITH_EDGE_WEIGHTS, false, null)); - importMenu.add(fc.getAction(CommandSet.LAYOUT_NETWORK_ALIGNMENT, false, null)); - JMenu exportMenu = new JMenu(rMan.getString("command.exportMenu")); - exportMenu.setMnemonic(rMan.getChar("command.exportMenuMnem")); - fMenu.add(exportMenu); - exportMenu.add(fc.getAction(CommandSet.EXPORT_IMAGE, false, null)); - exportMenu.add(fc.getAction(CommandSet.EXPORT_IMAGE_PUBLISH, false, null)); - exportMenu.add(new JSeparator()); - exportMenu.add(fc.getAction(CommandSet.EXPORT_NODE_ORDER, false, null)); - exportMenu.add(fc.getAction(CommandSet.EXPORT_LINK_ORDER, false, null)); - exportMenu.add(new JSeparator()); - exportMenu.add(fc.getAction(CommandSet.EXPORT_SELECTED_NODES, false, null)); - fMenu.add(new JSeparator()); - fMenu.add(fc.getAction(CommandSet.EMPTY_NETWORK, false, null)); - fMenu.add(new JSeparator()); - fMenu.add(fc.getAction(CommandSet.PRINT, false, null)); - fMenu.add(new JSeparator()); - fMenu.add(fc.getAction(CommandSet.PRINT_PDF, false, null)); - fMenu.add(new JSeparator()); - fMenu.add(fc.getAction(CommandSet.CLOSE, false, null)); - } else { - JMenu fMenu = new JMenu(rMan.getString("command.File")); - fMenu.setMnemonic(rMan.getChar("command.FileMnem")); - menuBar.add(fMenu); - JMenu exportMenu = new JMenu(rMan.getString("command.exportMenu")); - exportMenu.setMnemonic(rMan.getChar("command.exportMenuMnem")); - fMenu.add(exportMenu); - exportMenu.add(fc.getAction(CommandSet.EXPORT_IMAGE, false, null)); - exportMenu.add(fc.getAction(CommandSet.EXPORT_IMAGE_PUBLISH, false, null)); - exportMenu.add(new JSeparator()); - exportMenu.add(fc.getAction(CommandSet.EXPORT_SELECTED_NODES, false, null)); - } - - JMenu eMenu = new JMenu(rMan.getString("command.Edit")); - eMenu.setMnemonic(rMan.getChar("command.EditMnem")); - menuBar.add(eMenu); - eMenu.add(fc.getAction(CommandSet.CLEAR_SELECTIONS, false, null)); - eMenu.add(fc.getAction(CommandSet.ADD_FIRST_NEIGHBORS, false, null)); - if (isMain) { - eMenu.add(fc.getAction(CommandSet.PROPAGATE_DOWN, false, null)); - } - Action bsa = fc.getAction(CommandSet.BUILD_SELECT, false, null); - JCheckBoxMenuItem jcb = new JCheckBoxMenuItem(bsa); - jcb.setSelected(true); - eMenu.add(jcb); - eMenu.add(new JSeparator()); - eMenu.add(fc.getAction(CommandSet.SET_DISPLAY_OPTIONS, false, null)); - - JMenu vMenu = new JMenu(rMan.getString("command.View")); - vMenu.setMnemonic(rMan.getChar("command.ViewMnem")); - menuBar.add(vMenu); - vMenu.add(fc.getAction(CommandSet.ZOOM_OUT, false, null)); - vMenu.add(fc.getAction(CommandSet.ZOOM_IN, false, null)); - vMenu.add(fc.getAction(CommandSet.ZOOM_TO_MODEL, false, null)); - vMenu.add(fc.getAction(CommandSet.ZOOM_TO_RECT, false, null)); - vMenu.add(fc.getAction(CommandSet.ZOOM_TO_CURRENT_MOUSE, false, null)); - vMenu.add(fc.getAction(CommandSet.ZOOM_TO_CURRENT_MAGNIFY, false, null)); - vMenu.add(fc.getAction(CommandSet.ZOOM_TO_SELECTIONS, false, null)); - vMenu.add(new JSeparator()); - vMenu.add(fc.getAction(CommandSet.CENTER_ON_PREVIOUS_SELECTION, false, null)); - vMenu.add(fc.getAction(CommandSet.ZOOM_TO_CURRENT_SELECTION, false, null)); - vMenu.add(fc.getAction(CommandSet.CENTER_ON_NEXT_SELECTION, false, null)); - - // - // Tools Menu - // - - JMenu sMenu = new JMenu(rMan.getString("command.Tools")); - sMenu.setMnemonic(rMan.getChar("command.ToolsMnem")); - menuBar.add(sMenu); - sMenu.add(fc.getAction(CommandSet.SEARCH, false, null)); - sMenu.add(fc.getAction(CommandSet.COMPARE_NODES, false, null)); - - // - // Layout Menu - // - - JMenu lMenu = new JMenu(rMan.getString("command.Layout")); - lMenu.setMnemonic(rMan.getChar("command.LayoutMnem")); - menuBar.add(lMenu); - lMenu.add(fc.getAction(CommandSet.DEFAULT_LAYOUT, false, null)); - lMenu.add(fc.getAction(CommandSet.RELAYOUT_USING_CONNECTIVITY, false, null)); - lMenu.add(fc.getAction(CommandSet.RELAYOUT_USING_SHAPE_MATCH, false, null)); - lMenu.add(fc.getAction(CommandSet.LAYOUT_NODES_VIA_ATTRIBUTES, false, null)); - lMenu.add(fc.getAction(CommandSet.LAYOUT_LINKS_VIA_ATTRIBUTES, false, null)); - lMenu.add(fc.getAction(CommandSet.LAYOUT_VIA_NODE_CLUSTER_ASSIGN, false, null)); - lMenu.add(fc.getAction(CommandSet.LAYOUT_TOP_CONTROL, false, null)); - lMenu.add(fc.getAction(CommandSet.HIER_DAG_LAYOUT, false, null)); - lMenu.add(fc.getAction(CommandSet.WORLD_BANK_LAYOUT, false, null)); - lMenu.add(fc.getAction(CommandSet.SET_LINK_GROUPS, false, null)); - - // - // Windows Menu - // - - JMenu wMenu = new JMenu(rMan.getString("command.Windows")); - wMenu.setMnemonic(rMan.getChar("command.ToolsMnem")); - menuBar.add(wMenu); - JCheckBoxMenuItem jcbS = new JCheckBoxMenuItem(fc.getAction(CommandSet.SHOW_NAV_PANEL, false, null)); - jcbS.setSelected(true); - wMenu.add(jcbS); - JCheckBoxMenuItem jcbT = new JCheckBoxMenuItem(fc.getAction(CommandSet.SHOW_TOUR, false, null)); - jcbT.setSelected(true); - wMenu.add(jcbT); - - JMenu hMenu = new JMenu(rMan.getString("command.Help")); - hMenu.setMnemonic(rMan.getChar("command.HelpMnem")); - menuBar.add(hMenu); - hMenu.add(fc.getAction(CommandSet.ABOUT, false, null)); - - setJMenuBar(menuBar); - return; - } - - /*************************************************************************** - ** - ** Stock the action map - */ - - private void stockActionMap(CommandSet fc, boolean isMain) { - actionMap_.put(Integer.valueOf(CommandSet.SEARCH), fc.getAction(CommandSet.SEARCH, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.ZOOM_OUT), fc.getAction(CommandSet.ZOOM_OUT, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.ZOOM_IN), fc.getAction(CommandSet.ZOOM_IN, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.ADD_FIRST_NEIGHBORS), fc.getAction(CommandSet.ADD_FIRST_NEIGHBORS, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.CLEAR_SELECTIONS), fc.getAction(CommandSet.CLEAR_SELECTIONS, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.ZOOM_TO_MODEL), fc.getAction(CommandSet.ZOOM_TO_MODEL, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.ZOOM_TO_SELECTIONS), fc.getAction(CommandSet.ZOOM_TO_SELECTIONS, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.ZOOM_TO_RECT), fc.getAction(CommandSet.ZOOM_TO_RECT, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.CANCEL), fc.getAction(CommandSet.CANCEL, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.ZOOM_TO_CURRENT_SELECTION), fc.getAction(CommandSet.ZOOM_TO_CURRENT_SELECTION, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.CENTER_ON_NEXT_SELECTION), fc.getAction(CommandSet.CENTER_ON_NEXT_SELECTION, true, null)); - actionMap_.put(Integer.valueOf(CommandSet.CENTER_ON_PREVIOUS_SELECTION), fc.getAction(CommandSet.CENTER_ON_PREVIOUS_SELECTION, true, null)); - - if (isMain) { - actionMap_.put(Integer.valueOf(CommandSet.PROPAGATE_DOWN), fc.getAction(CommandSet.PROPAGATE_DOWN, true, null)); - } - return; - } - - /*************************************************************************** - ** - ** Stock the tool bar - */ - - private void stockToolBar(JToolBar toolBar, boolean isMain, CommandSet fc) { - toolBar.removeAll(); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.ZOOM_OUT))); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.ZOOM_IN))); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.ZOOM_TO_MODEL))); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.ZOOM_TO_RECT))); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.ZOOM_TO_SELECTIONS))); - toolBar.addSeparator(); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.CENTER_ON_PREVIOUS_SELECTION))); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.ZOOM_TO_CURRENT_SELECTION))); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.CENTER_ON_NEXT_SELECTION))); - toolBar.addSeparator(); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.ADD_FIRST_NEIGHBORS))); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.CLEAR_SELECTIONS))); - toolBar.addSeparator(); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.CANCEL))); - toolBar.addSeparator(); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.SEARCH))); - if (isMain) { - toolBar.addSeparator(); - toolBar.add(actionMap_.get(Integer.valueOf(CommandSet.PROPAGATE_DOWN))); - } - return; - } -} diff --git a/src/org/systemsbiology/biofabric/cmd/CommandSet.java b/src/org/systemsbiology/biofabric/cmd/CommandSet.java deleted file mode 100644 index 5db002b..0000000 --- a/src/org/systemsbiology/biofabric/cmd/CommandSet.java +++ /dev/null @@ -1,4344 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.cmd; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Event; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.print.PageFormat; -import java.awt.print.PrinterException; -import java.awt.print.PrinterJob; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.URL; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.SortedMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JEditorPane; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.KeyStroke; -import javax.swing.border.EmptyBorder; -import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; -import javax.swing.filechooser.FileFilter; - -import org.systemsbiology.biofabric.analysis.NetworkAlignment; -//import org.freehep.graphics2d.VectorGraphics; -//import org.freehep.graphicsio.PageConstants; -//import org.freehep.graphicsio.pdf.PDFGraphics2D; -//import org.freehep.graphicsio.ps.PSGraphics2D; -import org.systemsbiology.biofabric.app.BioFabricApplication; -import org.systemsbiology.biofabric.app.BioFabricWindow; -import org.systemsbiology.biofabric.event.EventManager; -import org.systemsbiology.biofabric.event.SelectionChangeEvent; -import org.systemsbiology.biofabric.event.SelectionChangeListener; -import org.systemsbiology.biofabric.io.AttributeLoader; -import org.systemsbiology.biofabric.io.FabricFactory; -import org.systemsbiology.biofabric.io.FabricSIFLoader; -import org.systemsbiology.biofabric.layouts.NodeClusterLayout; -import org.systemsbiology.biofabric.layouts.NodeSimilarityLayout; -import org.systemsbiology.biofabric.layouts.ControlTopLayout; -import org.systemsbiology.biofabric.layouts.DefaultLayout; -import org.systemsbiology.biofabric.layouts.HierDAGLayout; -import org.systemsbiology.biofabric.layouts.ProcessWorldBankCSV; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.parser.ParserClient; -import org.systemsbiology.biofabric.parser.SUParser; -import org.systemsbiology.biofabric.ui.FabricColorGenerator; -import org.systemsbiology.biofabric.ui.FabricDisplayOptionsManager; -import org.systemsbiology.biofabric.ui.ImageExporter; -import org.systemsbiology.biofabric.ui.dialogs.BreadthFirstLayoutDialog; -import org.systemsbiology.biofabric.ui.dialogs.ClusterLayoutSetupDialog; -import org.systemsbiology.biofabric.ui.dialogs.NodeSimilarityLayoutSetupDialog; -import org.systemsbiology.biofabric.ui.dialogs.CompareNodesSetupDialog; -import org.systemsbiology.biofabric.ui.dialogs.ExportSettingsDialog; -import org.systemsbiology.biofabric.ui.dialogs.ExportSettingsPublishDialog; -import org.systemsbiology.biofabric.ui.dialogs.FabricDisplayOptionsDialog; -import org.systemsbiology.biofabric.ui.dialogs.FabricSearchDialog; -import org.systemsbiology.biofabric.ui.dialogs.LinkGroupingSetupDialog; -import org.systemsbiology.biofabric.ui.dialogs.NetworkAlignmentDialog; -import org.systemsbiology.biofabric.ui.dialogs.RelationDirectionDialog; -import org.systemsbiology.biofabric.ui.dialogs.ReorderLayoutParamsDialog; -import org.systemsbiology.biofabric.ui.display.BioFabricPanel; -import org.systemsbiology.biofabric.ui.display.FabricMagnifyingTool; -import org.systemsbiology.biofabric.ui.render.BufferBuilder; -import org.systemsbiology.biofabric.util.AsynchExitRequestException; -import org.systemsbiology.biofabric.util.BackgroundWorker; -import org.systemsbiology.biofabric.util.BackgroundWorkerClient; -import org.systemsbiology.biofabric.util.BackgroundWorkerOwner; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FileExtensionFilters; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.Indenter; -import org.systemsbiology.biofabric.util.InvalidInputException; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; -import org.systemsbiology.biofabric.util.UniqueLabeller; -import org.systemsbiology.biotapestry.biofabric.FabricCommands; - -/**************************************************************************** -** -** Collection of primary commands for the application -*/ - -public class CommandSet implements ZoomChangeTracker, SelectionChangeListener, FabricDisplayOptionsManager.DisplayOptionTracker { - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** For standard file checks - */ - - public static final boolean FILE_MUST_EXIST_DONT_CARE = false; - public static final boolean FILE_MUST_EXIST = true; - - public static final boolean FILE_CAN_CREATE_DONT_CARE = false; - public static final boolean FILE_CAN_CREATE = true; - - public static final boolean FILE_DONT_CHECK_OVERWRITE = false; - public static final boolean FILE_CHECK_OVERWRITE = true; - - public static final boolean FILE_MUST_BE_FILE = false; - public static final boolean FILE_MUST_BE_DIRECTORY = true; - - public static final boolean FILE_CAN_WRITE_DONT_CARE = false; - public static final boolean FILE_CAN_WRITE = true; - - public static final boolean FILE_CAN_READ_DONT_CARE = false; - public static final boolean FILE_CAN_READ = true; - - public static final int EMPTY_NETWORK = 0; - public static final int CLOSE = 1; - public static final int LOAD = 2; - public static final int SEARCH = 3; - public static final int ZOOM_OUT = 4; - public static final int ZOOM_IN = 5; - public static final int CLEAR_SELECTIONS = 6; - public static final int SAVE_AS = 7; - - public static final int ZOOM_TO_MODEL = 8; - public static final int ZOOM_TO_SELECTIONS = 9; - public static final int PROPAGATE_DOWN = 10; - public static final int ZOOM_TO_RECT = 11; - public static final int CANCEL = 12; - public static final int ZOOM_TO_CURRENT_SELECTION = 13; - public static final int ADD_FIRST_NEIGHBORS = 14; - public static final int BUILD_SELECT = 15; - public static final int SET_DISPLAY_OPTIONS = 16; - - // Former Gaggle Commands 17-24 dropped - - public static final int ABOUT = 25; - public static final int CENTER_ON_NEXT_SELECTION = 26; - public static final int CENTER_ON_PREVIOUS_SELECTION = 27; - public static final int LAYOUT_NODES_VIA_ATTRIBUTES = 28; - public static final int LAYOUT_LINKS_VIA_ATTRIBUTES = 29; - public static final int LOAD_WITH_NODE_ATTRIBUTES = 30; - public static final int LOAD_XML = 31; - public static final int RELAYOUT_USING_CONNECTIVITY = 32; - public static final int RELAYOUT_USING_SHAPE_MATCH = 33; - public static final int SET_LINK_GROUPS = 34; - public static final int COMPARE_NODES = 35; - public static final int ZOOM_TO_CURRENT_MOUSE = 36; - public static final int ZOOM_TO_CURRENT_MAGNIFY = 37; - public static final int EXPORT_NODE_ORDER = 38; - public static final int EXPORT_LINK_ORDER = 39; - public static final int EXPORT_IMAGE = 40; - public static final int EXPORT_IMAGE_PUBLISH = 41; - public static final int PRINT = 42; - public static final int DEFAULT_LAYOUT = 43; - public static final int EXPORT_SELECTED_NODES = 44; - public static final int SAVE = 45; - public static final int LAYOUT_VIA_NODE_CLUSTER_ASSIGN = 46; - public static final int PRINT_PDF = 47; - public static final int SHOW_TOUR = 48; - public static final int SHOW_NAV_PANEL = 49; - public static final int LAYOUT_TOP_CONTROL = 50; - public static final int HIER_DAG_LAYOUT = 51; - public static final int WORLD_BANK_LAYOUT = 52; - public static final int LOAD_WITH_EDGE_WEIGHTS = 53; - public static final int LAYOUT_NETWORK_ALIGNMENT = 54; - - - - public static final int GENERAL_PUSH = 0x01; - public static final int ALLOW_NAV_PUSH = 0x02; - - //////////////////////////////////////////////////////////////////////////// - // - // MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - private static HashMap perClass_; - private BioFabricWindow topWindow_; - private BioFabricApplication bfa_; - private BioFabricPanel bfp_; - private File currentFile_; - private boolean isAMac_; - private boolean isForMain_; - private boolean showNav_; - - private HashMap withIcons_; - private HashMap noIcons_; - private FabricColorGenerator colGen_; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Needed for Cytoscape app support - */ - - public BioFabricWindow getBFW() { - return (topWindow_); - } - - /*************************************************************************** - ** - ** Let us know we are on a mac - */ - - public boolean isAMac() { - return (isAMac_); - } - - /*************************************************************************** - ** - ** Notify listener of selection change - */ - - public void selectionHasChanged(SelectionChangeEvent scev) { - checkForChanges(); - return; - } - - /*************************************************************************** - ** - ** Trigger the enabled checks - */ - - public void checkForChanges() { - Iterator wiit = withIcons_.values().iterator(); - while (wiit.hasNext()) { - ChecksForEnabled cfe = wiit.next(); - cfe.checkIfEnabled(); - } - Iterator niit = noIcons_.values().iterator(); - while (niit.hasNext()) { - ChecksForEnabled cfe = niit.next(); - cfe.checkIfEnabled(); - } - return; - } - - /*************************************************************************** - ** - ** Push a disabled condition - */ - - public void pushDisabled(int pushCondition) { - Iterator wiit = withIcons_.values().iterator(); - while (wiit.hasNext()) { - ChecksForEnabled cfe = wiit.next(); - cfe.pushDisabled(pushCondition); - } - Iterator niit = noIcons_.values().iterator(); - while (niit.hasNext()) { - ChecksForEnabled cfe = niit.next(); - cfe.pushDisabled(pushCondition); - } - return; - } - - /*************************************************************************** - ** - ** Pop the disabled condition - */ - - public void popDisabled() { - Iterator wiit = withIcons_.values().iterator(); - while (wiit.hasNext()) { - ChecksForEnabled cfe = wiit.next(); - cfe.popDisabled(); - } - Iterator niit = noIcons_.values().iterator(); - while (niit.hasNext()) { - ChecksForEnabled cfe = niit.next(); - cfe.popDisabled(); - } - - return; - } - - /*************************************************************************** - ** - ** Display options have changed! - */ - - public void optionsHaveChanged(boolean needRebuild, boolean needRecolor) { - if (!needRebuild && !needRecolor) { - bfp_.repaint(); - return; - } - if (needRecolor && !needRebuild) { - NetworkRecolor nb = new NetworkRecolor(); - nb.doNetworkRecolor(isForMain_); - } else if (needRebuild) { - BioFabricNetwork bfn = bfp_.getNetwork(); - if (bfn != null) { - BioFabricNetwork.PreBuiltBuildData rbd = - new BioFabricNetwork.PreBuiltBuildData(bfn, BioFabricNetwork.BuildMode.SHADOW_LINK_CHANGE); - NetworkBuilder nb = new NetworkBuilder(); - nb.doNetworkBuild(rbd, true); - } - } - return; - } - - /*************************************************************************** - ** - ** Get ColorGenerator - */ - - public FabricColorGenerator getColorGenerator() { - return (colGen_); - } - - /*************************************************************************** - ** - ** Command - */ - - public NetworkBuilder getANetworkBuilder() { - return (new NetworkBuilder()); - } - - /*************************************************************************** - ** - ** Get an action - */ - - public Action getAction(int actionKey, boolean withIcon, Object[] optionArgs) { - HashMap useMap = (withIcon) ? withIcons_ : noIcons_; - Integer actionKeyObject = Integer.valueOf(actionKey); - ChecksForEnabled retval = useMap.get(actionKeyObject); - if (retval != null) { - return (retval); - } else { - switch (actionKey) { - case ABOUT: - retval = new AboutAction(withIcon); - break; - case EMPTY_NETWORK: - retval = new EmptyNetworkAction(withIcon); - break; - case CLOSE: - retval = new CloseAction(withIcon); - break; - case LOAD_XML: - retval = new LoadXMLAction(withIcon); - break; - case LOAD: - retval = new ImportSIFAction(withIcon, false); - break; - case LOAD_WITH_EDGE_WEIGHTS: - retval = new ImportSIFAction(withIcon, true); - break; - case LOAD_WITH_NODE_ATTRIBUTES: - retval = new LoadWithNodeAttributesAction(withIcon); - break; - case SAVE_AS: - retval = new SaveAsAction(withIcon); - break; - case SAVE: - retval = new SaveAction(withIcon); - break; - case EXPORT_NODE_ORDER: - retval = new ExportNodeOrderAction(withIcon); - break; - case EXPORT_LINK_ORDER: - retval = new ExportLinkOrderAction(withIcon); - break; - case EXPORT_SELECTED_NODES: - retval = new ExportSelectedNodesAction(withIcon); - break; - case EXPORT_IMAGE: - retval = new ExportSimpleAction(withIcon); - break; - case EXPORT_IMAGE_PUBLISH: - retval = new ExportPublishAction(withIcon); - break; - case PRINT: - retval = new PrintAction(withIcon); - break; - case PRINT_PDF: - retval = new PrintPDFAction(withIcon); - break; - case SEARCH: - retval = new SearchAction(withIcon); - break; - case ZOOM_IN: - retval = new InOutZoomAction(withIcon, '+'); - break; - case ZOOM_OUT: - retval = new InOutZoomAction(withIcon, '-'); - break; - case CLEAR_SELECTIONS: - retval = new ClearSelectionsAction(withIcon); - break; - case ZOOM_TO_MODEL: - retval = new ZoomToModelAction(withIcon); - break; - case ZOOM_TO_SELECTIONS: - retval = new ZoomToSelected(withIcon); - break; - case PROPAGATE_DOWN: - retval = new PropagateDownAction(withIcon); - break; - case ZOOM_TO_RECT: - retval = new ZoomToRect(withIcon); - break; - case CANCEL: - retval = new CancelAction(withIcon); - break; - case CENTER_ON_NEXT_SELECTION: - retval = new CenterOnNextSelected(withIcon); - break; - case CENTER_ON_PREVIOUS_SELECTION: - retval = new CenterOnPreviousSelected(withIcon); - break; - case ZOOM_TO_CURRENT_SELECTION: - retval = new ZoomToCurrentSelected(withIcon); - break; - case ZOOM_TO_CURRENT_MOUSE: - retval = new ZoomToCurrentMouse(withIcon); - break; - case ZOOM_TO_CURRENT_MAGNIFY: - retval = new ZoomToCurrentMagnify(withIcon); - break; - case ADD_FIRST_NEIGHBORS: - retval = new AddFirstNeighborsAction(withIcon); - break; - case BUILD_SELECT: - retval = new BuildSelectAction(withIcon); - break; - case SET_DISPLAY_OPTIONS: - retval = new SetDisplayOptionsAction(withIcon); - break; - case LAYOUT_NODES_VIA_ATTRIBUTES: - retval = new LayoutNodesViaAttributesAction(withIcon); - break; - case LAYOUT_LINKS_VIA_ATTRIBUTES: - retval = new LayoutLinksViaAttributesAction(withIcon); - break; - case RELAYOUT_USING_CONNECTIVITY: - retval = new LayoutViaConnectivityAction(withIcon); - break; - case DEFAULT_LAYOUT: - retval = new DefaultLayoutAction(withIcon); - break; - case HIER_DAG_LAYOUT: - retval = new HierDAGLayoutAction(withIcon); - break; - case RELAYOUT_USING_SHAPE_MATCH: - retval = new LayoutViaShapeMatchAction(withIcon); - break; - case SET_LINK_GROUPS: - retval = new SetLinkGroupsAction(withIcon); - break; - case LAYOUT_NETWORK_ALIGNMENT: - retval = new LayoutNetworkAlignment(withIcon); - break; - case COMPARE_NODES: - retval = new CompareNodesAction(withIcon); - break; - case LAYOUT_VIA_NODE_CLUSTER_ASSIGN: - retval = new LayoutViaNodeClusterAction(withIcon); - break; - case LAYOUT_TOP_CONTROL: - retval = new LayoutTopControlAction(withIcon); - break; - case SHOW_TOUR: - retval = new ToggleShowTourAction(withIcon); - break; - case SHOW_NAV_PANEL: - retval = new ToggleShowNavPanelAction(withIcon); - break; - case WORLD_BANK_LAYOUT: - retval = new WorldBankLayoutAction(withIcon); - break; - default: - throw new IllegalArgumentException(); - } - useMap.put(actionKeyObject, retval); - } - return (retval); - } - - /*************************************************************************** - ** - ** Common load operations. Take your pick of input sources - */ - - private boolean loadFromSifSource(File file, Map nameMap, Integer magBins, - UniqueLabeller idGen) { - ArrayList links = new ArrayList(); - HashSet loneNodes = new HashSet(); - HashMap nodeNames = null; - if (nameMap != null) { - nodeNames = new HashMap(); - for (AttributeLoader.AttributeKey key : nameMap.keySet()) { - nodeNames.put(((AttributeLoader.StringKey)key).key, nameMap.get(key)); - } - } - - FabricSIFLoader.SIFStats sss; - if (file.length() > 500000) { - sss = new FabricSIFLoader.SIFStats(); - BackgroundFileReader br = new BackgroundFileReader(); - br.doBackgroundSIFRead(file, idGen, links, loneNodes, nodeNames, sss, magBins); - return (true); - } else { - try { - sss = (new FabricSIFLoader()).readSIF(file, idGen, links, loneNodes, nodeNames, magBins); - return (finishLoadFromSIFSource(file, idGen, sss, links, loneNodes, (magBins != null))); - } catch (IOException ioe) { - displayFileInputError(ioe); - return (false); - } catch (OutOfMemoryError oom) { - ExceptionHandler.getHandler().displayOutOfMemory(oom); - return (false); - } - } - } - - /*************************************************************************** - ** - ** Common load operations. - */ - - private boolean finishLoadFromSIFSource(File file, UniqueLabeller idGen, FabricSIFLoader.SIFStats sss, List links, Set loneNodeIDs, boolean binMag) { - ResourceManager rMan = ResourceManager.getManager(); - try { - if (!sss.badLines.isEmpty()) { - String badLineFormat = rMan.getString("fabricRead.badLineFormat"); - String badLineMsg = MessageFormat.format(badLineFormat, new Object[] {Integer.valueOf(sss.badLines.size())}); - JOptionPane.showMessageDialog(topWindow_, badLineMsg, - rMan.getString("fabricRead.badLineTitle"), - JOptionPane.WARNING_MESSAGE); - } - - SortedMap relaMap = BioFabricNetwork.extractRelations(links); - RelationDirectionDialog rdd = new RelationDirectionDialog(topWindow_, relaMap); - rdd.setVisible(true); - if (!rdd.haveResult()) { - return (false); - } - if (rdd.getFromFile()) { - File fileEda = getTheFile(".rda", ".txt", "AttribDirectory", "filterName.rda"); - if (fileEda == null) { - return (true); - } - Map relAttributes = loadTheFile(fileEda, null, true); // Use the simple a = b format of node attributes - if (relAttributes == null) { - return (true); - } - - HashSet needed = new HashSet(relaMap.keySet()); - - boolean tooMany = false; - Iterator rit = relAttributes.keySet().iterator(); - while (rit.hasNext()) { - AttributeLoader.StringKey sKey = (AttributeLoader.StringKey)rit.next(); - String key = sKey.key; - String val = relAttributes.get(sKey); - Boolean dirVal = Boolean.valueOf(val); - FabricLink.AugRelation forNorm = new FabricLink.AugRelation(key, false); - FabricLink.AugRelation forShad = new FabricLink.AugRelation(key, true); - boolean matched = false; - if (needed.contains(forNorm)) { - matched = true; - relaMap.put(forNorm, dirVal); - needed.remove(forNorm); - } - if (needed.contains(forShad)) { - matched = true; - relaMap.put(forShad, dirVal); - needed.remove(forShad); - } - if (!matched) { - tooMany = true; - break; - } - } - if (!needed.isEmpty() || tooMany) { - JOptionPane.showMessageDialog(topWindow_, rMan.getString("fabricRead.directionMapLoadFailure"), - rMan.getString("fabricRead.directionMapLoadFailureTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - } else { - relaMap = rdd.getRelationMap(); - } - - BioFabricNetwork.assignDirections(links, relaMap); - HashSet reducedLinks = new HashSet(); - HashSet culledLinks = new HashSet(); - BioFabricNetwork.preprocessLinks(links, reducedLinks, culledLinks); - if (!culledLinks.isEmpty()) { - String dupLinkFormat = rMan.getString("fabricRead.dupLinkFormat"); - // Ignore shadow link culls: / 2 - String dupLinkMsg = MessageFormat.format(dupLinkFormat, new Object[] {Integer.valueOf(culledLinks.size() / 2)}); - JOptionPane.showMessageDialog(topWindow_, dupLinkMsg, - rMan.getString("fabricRead.dupLinkTitle"), - JOptionPane.WARNING_MESSAGE); - } - - // - // Handle magnitude bins: - // - - if (binMag) { - HashSet binnedLinks = new HashSet(); - Pattern p = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"); - - Iterator alit = reducedLinks.iterator(); - while (alit.hasNext()) { - FabricLink nextLink = alit.next(); - FabricLink.AugRelation rel = nextLink.getAugRelation(); - Matcher m = p.matcher(rel.relation); - int magCount = 0; - if (m.find()) { - double d = Double.parseDouble(m.group(0)); - magCount = (int)Math.floor((Math.abs(d) * 10.0) - 5.0); - } - /* - for (int k = 0; k < magCount; k++) { - String suf = ":" + Integer.toString(k); - FabricLink nextLink = new FabricLink(source, target, rel + suf, false); - links.add(nextLink); - // We never create shadow feedback links! - if (!source.equals(target)) { - FabricLink nextShadowLink = new FabricLink(source, target, rel + suf, true); - links.add(nextShadowLink); - }*/ - } - } - - BioFabricNetwork.RelayoutBuildData bfn = new BioFabricNetwork.RelayoutBuildData(idGen, reducedLinks, loneNodeIDs, - new HashMap(), colGen_, - BioFabricNetwork.BuildMode.BUILD_FROM_SIF); - NetworkBuilder nb = new NetworkBuilder(); - nb.doNetworkBuild(bfn, true); - } catch (OutOfMemoryError oom) { - ExceptionHandler.getHandler().displayOutOfMemory(oom); - return (false); - } - currentFile_ = null; - FabricCommands.setPreference("LoadDirectory", file.getAbsoluteFile().getParent()); - manageWindowTitle(file.getName()); - return (true); - } - - /*************************************************************************** - ** - ** Common load operations. - */ - - private boolean loadXMLFromSource(File file) { - ArrayList alist = new ArrayList(); - FabricFactory ff = new FabricFactory(); - alist.add(ff); - SUParser sup = new SUParser(alist); - if (file.length() > 1000000) { - BackgroundFileReader br = new BackgroundFileReader(); - br.doBackgroundRead(ff, sup, file); - return (true); - } else { - try { - sup.parse(file); - } catch (IOException ioe) { - displayFileInputError(ioe); - return (false); - } catch (OutOfMemoryError oom) { - ExceptionHandler.getHandler().displayOutOfMemory(oom); - return (false); - } - } - setCurrentXMLFile(file); - postXMLLoad(ff, file.getName()); - return (true); - } - - /*************************************************************************** - ** - ** Common load operations. - */ - - boolean postXMLLoad(FabricFactory ff, String fileName) { - BioFabricNetwork bfn = ff.getFabricNetwork(); - BioFabricNetwork.PreBuiltBuildData pbd = new BioFabricNetwork.PreBuiltBuildData(bfn, BioFabricNetwork.BuildMode.BUILD_FROM_XML); - NetworkBuilder nb = new NetworkBuilder(); - nb.doNetworkBuild(pbd, true); - manageWindowTitle(fileName); - return (true); - } - - /*************************************************************************** - ** - ** Load network from gaggle - */ - - public boolean loadFromGaggle(List links, List singleIDs, UniqueLabeller uLab, Map idToName) { - HashSet reducedLinks = new HashSet(); - HashSet culledLinks = new HashSet(); - BioFabricNetwork.preprocessLinks(links, reducedLinks, culledLinks); - if (!culledLinks.isEmpty()) { - ResourceManager rMan = ResourceManager.getManager(); - String dupLinkFormat = rMan.getString("fabricRead.dupLinkFormat"); - // Ignore shadow link culls: / 2 - String dupLinkMsg = MessageFormat.format(dupLinkFormat, new Object[] {Integer.valueOf(culledLinks.size() / 2)}); - JOptionPane.showMessageDialog(topWindow_, dupLinkMsg, - rMan.getString("fabricRead.dupLinkTitle"), - JOptionPane.WARNING_MESSAGE); - } - BioFabricNetwork.RelayoutBuildData bfnbd = - new BioFabricNetwork.RelayoutBuildData(uLab, reducedLinks, new HashSet(singleIDs), - new HashMap(), - colGen_, BioFabricNetwork.BuildMode.BUILD_FROM_GAGGLE); - NetworkBuilder nb = new NetworkBuilder(); - nb.doNetworkBuild(bfnbd, true); - manageWindowTitle("Gaggle"); - return (true); - } - - /*************************************************************************** - ** - ** Do standard file checks and warnings - */ - - public boolean standardFileChecks(File target, boolean mustExist, boolean canCreate, - boolean checkOverwrite, boolean mustBeDirectory, - boolean canWrite, boolean canRead) { - ResourceManager rMan = ResourceManager.getManager(); - boolean doesExist = target.exists(); - - if (mustExist) { - if (!doesExist) { - String noFileFormat = rMan.getString("fileChecks.noFileFormat"); - String noFileMsg = MessageFormat.format(noFileFormat, new Object[] {target.getName()}); - JOptionPane.showMessageDialog(topWindow_, noFileMsg, - rMan.getString("fileChecks.noFileTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - } - if (mustBeDirectory) { - if (doesExist && !target.isDirectory()) { - String notADirectoryFormat = rMan.getString("fileChecks.notADirectoryFormat"); - String notADirectoryMsg = MessageFormat.format(notADirectoryFormat, new Object[] {target.getName()}); - JOptionPane.showMessageDialog(topWindow_, notADirectoryMsg, - rMan.getString("fileChecks.notADirectoryTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - } else { // gotta be a file - if (doesExist && !target.isFile()) { - String notAFileFormat = rMan.getString("fileChecks.notAFileFormat"); - String notAFileMsg = MessageFormat.format(notAFileFormat, new Object[] {target.getName()}); - JOptionPane.showMessageDialog(topWindow_, notAFileMsg, - rMan.getString("fileChecks.notAFileTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - } - - if (!doesExist && canCreate) { - if (mustBeDirectory) { - throw new IllegalArgumentException(); - } - boolean couldNotCreate = false; - try { - if (!target.createNewFile()) { - couldNotCreate = true; - } - } catch (IOException ioex) { - couldNotCreate = true; - } - if (couldNotCreate) { - String noCreateFormat = rMan.getString("fileChecks.noCreateFormat"); - String noCreateMsg = MessageFormat.format(noCreateFormat, new Object[] {target.getName()}); - JOptionPane.showMessageDialog(topWindow_, noCreateMsg, - rMan.getString("fileChecks.noCreateTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - } - - boolean didExist = doesExist; - doesExist = target.exists(); - - if (canWrite) { - if (doesExist && !target.canWrite()) { - String noWriteFormat = rMan.getString("fileChecks.noWriteFormat"); - String noWriteMsg = MessageFormat.format(noWriteFormat, new Object[] {target.getName()}); - JOptionPane.showMessageDialog(topWindow_, noWriteMsg, - rMan.getString("fileChecks.noWriteTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - } - if (canRead) { - if (doesExist && !target.canRead()) { - String noReadFormat = rMan.getString("fileChecks.noReadFormat"); - String noReadMsg = MessageFormat.format(noReadFormat, new Object[] {target.getName()}); - JOptionPane.showMessageDialog(topWindow_, noReadMsg, - rMan.getString("fileChecks.noReadTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - } - - if (didExist && checkOverwrite) { // note we care about DID exist (before creation) - String overFormat = rMan.getString("fileChecks.doOverwriteFormat"); - String overMsg = MessageFormat.format(overFormat, new Object[] {target.getName()}); - int overwrite = - JOptionPane.showConfirmDialog(topWindow_, overMsg, - rMan.getString("fileChecks.doOverwriteTitle"), - JOptionPane.YES_NO_OPTION); - if (overwrite != JOptionPane.YES_OPTION) { - return (false); - } - } - return (true); - } - - /*************************************************************************** - ** - ** Get readable attribute file - */ - - public File getTheFile(String ext1, String ext2, String prefTag, String desc) { - File file = null; - String filename = FabricCommands.getPreference(prefTag); - while (file == null) { - JFileChooser chooser = new JFileChooser(); - FileFilter filter; - if (ext2 == null) { - filter = new FileExtensionFilters.SimpleFilter(ext1, desc); - } else { - filter = new FileExtensionFilters.DoubleExtensionFilter(ext1, ext2, desc); - } - chooser.addChoosableFileFilter(filter); - chooser.setAcceptAllFileFilterUsed(true); - chooser.setFileFilter(filter); - if (filename != null) { - File startDir = new File(filename); - if (startDir.exists()) { - chooser.setCurrentDirectory(startDir); - } - } - - int option = chooser.showOpenDialog(topWindow_); - if (option != JFileChooser.APPROVE_OPTION) { - return (null); - } - file = chooser.getSelectedFile(); - if (file == null) { - return (null); - } - if (!standardFileChecks(file, FILE_MUST_EXIST, FILE_CAN_CREATE_DONT_CARE, - FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE_DONT_CARE, FILE_CAN_READ)) { - file = null; - continue; - } - } - return (file); - } - - /*************************************************************************** - ** - ** Load the file. Map keys are strings or Links - */ - - public Map loadTheFile(File file, Map> nameToIDs, boolean forNodes) { - HashMap attributes = new HashMap(); - try { - AttributeLoader.ReadStats stats = new AttributeLoader.ReadStats(); - AttributeLoader alod = new AttributeLoader(); - Map nameToID = (!forNodes) ? BioFabricNetwork.reduceNameSetToOne(nameToIDs) : null; - alod.readAttributes(file, forNodes, attributes, nameToID, stats); - if (!stats.badLines.isEmpty()) { - ResourceManager rMan = ResourceManager.getManager(); - String badLineFormat = rMan.getString("attribRead.badLineFormat"); - String badLineMsg = MessageFormat.format(badLineFormat, new Object[] {Integer.valueOf(stats.badLines.size())}); - JOptionPane.showMessageDialog(topWindow_, badLineMsg, - rMan.getString("attribRead.badLineTitle"), - JOptionPane.WARNING_MESSAGE); - } - if (!stats.dupLines.isEmpty()) { - ResourceManager rMan = ResourceManager.getManager(); - String dupLineFormat = rMan.getString("attribRead.dupLineFormat"); - String dupLineMsg = MessageFormat.format(dupLineFormat, new Object[] {Integer.valueOf(stats.dupLines.size())}); - JOptionPane.showMessageDialog(topWindow_, dupLineMsg, - rMan.getString("attribRead.dupLineTitle"), - JOptionPane.WARNING_MESSAGE); - } - if (!forNodes && !stats.shadowsPresent) { - ResourceManager rMan = ResourceManager.getManager(); - JOptionPane.showMessageDialog(topWindow_, rMan.getString("attribRead.noShadowError"), - rMan.getString("attribRead.noShadowTitle"), - JOptionPane.ERROR_MESSAGE); - return (null); - } - - } catch (IOException ioe) { - displayFileInputError(ioe); - return (null); - } - FabricCommands.setPreference("AttribDirectory", file.getAbsoluteFile().getParent()); - return (attributes); - } - - /*************************************************************************** - ** - ** Do new model operations - */ - - public void preLoadOperations() { - bfp_.reset(); - return; - } - - /*************************************************************************** - ** - ** Do new model operations - */ - - public BufferedImage expensiveModelOperations(BioFabricNetwork.BuildData bfnbd, boolean forMain) throws IOException { - Dimension screenSize = (forMain) ? Toolkit.getDefaultToolkit().getScreenSize() : new Dimension(600, 800); - screenSize.setSize((int)(screenSize.getWidth() * 0.8), (int)(screenSize.getHeight() * 0.4)); - // Possibly expensive network analysis preparation: - BioFabricNetwork bfn = new BioFabricNetwork(bfnbd); - // Possibly expensive display object creation: - bfp_.installModel(bfn); - // Very expensive display buffer creation: - int[] preZooms = BufferBuilder.calcImageZooms(bfn); - bfp_.zoomForBuf(preZooms, screenSize); - BufferedImage topImage = null; - if (forMain) { - BufferBuilder bb = new BufferBuilder(null, 1/*30*/, bfp_); - topImage = bb.buildBufs(preZooms, bfp_, 24); - bfp_.setBufBuilder(bb); - } else { - BufferBuilder bb = new BufferBuilder(bfp_); - topImage = bb.buildOneBuf(preZooms); - bfp_.setBufBuilder(null); - } - return (topImage); - } - - - - /*************************************************************************** - ** - ** Do new model operations - */ - - public BufferedImage expensiveRecolorOperations(boolean forMain) throws IOException { - Dimension screenSize = (forMain) ? Toolkit.getDefaultToolkit().getScreenSize() : new Dimension(800, 400); - screenSize.setSize((int)(screenSize.getWidth() * 0.8), (int)(screenSize.getHeight() * 0.4)); - colGen_.newColorModel(); - bfp_.changePaint(); - BioFabricNetwork bfn = bfp_.getNetwork(); - int[] preZooms = BufferBuilder.calcImageZooms(bfn); - bfp_.zoomForBuf(preZooms, screenSize); - BufferedImage topImage = null; - if (forMain) { - BufferBuilder bb = new BufferBuilder(null, 1, bfp_); - topImage = bb.buildBufs(preZooms, bfp_, 24); - bfp_.setBufBuilder(bb); - } else { - BufferBuilder bb = new BufferBuilder(bfp_); - topImage = bb.buildOneBuf(preZooms); - bfp_.setBufBuilder(null); - } - return (topImage); - } - - /*************************************************************************** - ** - ** Handles post-recolor operations - */ - - public void postRecolorOperations(BufferedImage topImage) { - topWindow_.getOverview().installImage(topImage, bfp_.getWorldRect()); - return; - } - - /*************************************************************************** - ** - ** Handles post-loading operations - */ - - public void postLoadOperations(BufferedImage topImage) { - topWindow_.getOverview().installImage(topImage, bfp_.getWorldRect()); - bfp_.installModelPost(); - bfp_.installZooms(); - bfp_.initZoom(); - checkForChanges(); - bfp_.repaint(); - return; - } - - /*************************************************************************** - ** - ** Do new model operations all on AWT thread! - */ - - public void newModelOperations(BioFabricNetwork.BuildData bfnbd, boolean forMain) throws IOException { - preLoadOperations(); - BufferedImage topImage = expensiveModelOperations(bfnbd, forMain); - postLoadOperations(topImage); - return; - } - - /*************************************************************************** - ** - ** Do window title - */ - - public void manageWindowTitle(String fileName) { - ResourceManager rMan = ResourceManager.getManager(); - String title; - if (fileName == null) { - title = rMan.getString("window.title"); - } else { - String titleFormat = rMan.getString("window.titleWithName"); - title = MessageFormat.format(titleFormat, new Object[] {fileName}); - } - topWindow_.setTitle(title); - return; - } - - /*************************************************************************** - ** - ** Common save activities - */ - - boolean saveToFile(String fileName) { - - File file = null; - if (fileName == null) { - String dirName = FabricCommands.getPreference("LoadDirectory"); - while (file == null) { - JFileChooser chooser = new JFileChooser(); - FileExtensionFilters.SimpleFilter sf = new FileExtensionFilters.SimpleFilter(".bif", "filterName.bif"); - chooser.addChoosableFileFilter(sf); - chooser.setAcceptAllFileFilterUsed(true); - chooser.setFileFilter(sf); - if (dirName != null) { - File startDir = new File(dirName); - if (startDir.exists()) { - chooser.setCurrentDirectory(startDir); - } - } - int option = chooser.showSaveDialog(topWindow_); - if (option != JFileChooser.APPROVE_OPTION) { - return (true); - } - file = chooser.getSelectedFile(); - if (file != null) { - if (!file.exists()) { - if (!FileExtensionFilters.hasSuffix(file.getName(), ".bif")) { - file = new File(file.getAbsolutePath() + ".bif"); - } - } - if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, - FILE_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { - file = null; - continue; - } - } - } - } else { - // given a name, we do not check overwrite: - file = new File(fileName); - if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, - FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { - return (false); - } - } - - - BioFabricNetwork bfn = bfp_.getNetwork(); - - if (bfn.getLinkCount(true) > 5000) { - BackgroundFileWriter bw = new BackgroundFileWriter(); - bw.doBackgroundWrite(file); - return (true); - } else { - try { - saveToOutputStream(new FileOutputStream(file)); - setCurrentXMLFile(file); - manageWindowTitle(file.getName()); - return (true); - } catch (IOException ioe) { - displayFileOutputError(); - return (false); - } - } - } - - - - /*************************************************************************** - ** - ** Common save activities - */ - - void saveToOutputStream(OutputStream stream) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"))); - Indenter ind = new Indenter(out, Indenter.DEFAULT_INDENT); - BioFabricNetwork bfn = bfp_.getNetwork(); - bfn.writeXML(out, ind); - out.close(); - return; - } - - /*************************************************************************** - ** - ** Displays file reading error message - */ - - public void displayFileInputError(IOException ioex) { - ResourceManager rMan = ResourceManager.getManager(); - - if ((ioex == null) || (ioex.getMessage() == null) || (ioex.getMessage().trim().equals(""))) { - JOptionPane.showMessageDialog(topWindow_, - rMan.getString("fileRead.errorMessage"), - rMan.getString("fileRead.errorTitle"), - JOptionPane.ERROR_MESSAGE); - return; - } - String errMsg = ioex.getMessage().trim(); - String format = rMan.getString("fileRead.inputErrorMessageForIOEx"); - String outMsg = MessageFormat.format(format, new Object[] {errMsg}); - JOptionPane.showMessageDialog(topWindow_, outMsg, - rMan.getString("fileRead.errorTitle"), - JOptionPane.ERROR_MESSAGE); - return; - } - - /*************************************************************************** - ** - ** Displays file writing error message - */ - - void displayFileOutputError() { - ResourceManager rMan = ResourceManager.getManager(); - JOptionPane.showMessageDialog(topWindow_, - rMan.getString("fileWrite.errorMessage"), - rMan.getString("fileWrite.errorTitle"), - JOptionPane.ERROR_MESSAGE); - return; - } - - /*************************************************************************** - ** - ** Displays file reading error message for invalid input - */ - - public void displayInvalidInputError(InvalidInputException iiex) { - ResourceManager rMan = ResourceManager.getManager(); - String errKey = iiex.getErrorKey(); - boolean haveKey = (errKey != null) && (!errKey.equals(InvalidInputException.UNSPECIFIED_ERROR)); - int lineno = iiex.getErrorLineNumber(); - boolean haveLine = (lineno != InvalidInputException.UNSPECIFIED_LINE); - String outMsg; - if (haveKey && haveLine) { - String format = rMan.getString("fileRead.inputErrorMessageForLineWithDesc"); - String keyedErr = rMan.getString("invalidInput." + errKey); - outMsg = MessageFormat.format(format, new Object[] {Integer.valueOf(lineno + 1), keyedErr}); - } else if (haveKey && !haveLine) { - String format = rMan.getString("fileRead.inputErrorMessageWithDesc"); - String keyedErr = rMan.getString("invalidInput." + errKey); - outMsg = MessageFormat.format(format, new Object[] {keyedErr}); - } else if (!haveKey && haveLine) { - String format = rMan.getString("fileRead.inputErrorMessageForLine"); - outMsg = MessageFormat.format(format, new Object[] {Integer.valueOf(lineno + 1)}); - } else { - outMsg = rMan.getString("fileRead.inputErrorMessage"); - } - JOptionPane.showMessageDialog(topWindow_, outMsg, - rMan.getString("fileRead.errorTitle"), - JOptionPane.ERROR_MESSAGE); - return; - } - - /*************************************************************************** - ** - ** Set the fabric panel - */ - - public void setFabricPanel(BioFabricPanel bfp) { - bfp_ = bfp; - return; - } - - /*************************************************************************** - ** - ** Tell us the zoom state has changed - */ - - public void zoomStateChanged(boolean scrollOnly) { - if (!scrollOnly) { - handleZoomButtons(); - } - topWindow_.getOverview().setViewInWorld(bfp_.getViewInWorld()); - return; - } - - /*************************************************************************** - ** - ** Handle zoom buttons - */ - - private void handleZoomButtons() { - // - // Enable/disable zoom actions based on zoom limits: - // - - InOutZoomAction zaOutWI = (InOutZoomAction)withIcons_.get(Integer.valueOf(ZOOM_OUT)); - InOutZoomAction zaOutNI = (InOutZoomAction)noIcons_.get(Integer.valueOf(ZOOM_OUT)); - InOutZoomAction zaInWI = (InOutZoomAction)withIcons_.get(Integer.valueOf(ZOOM_IN)); - InOutZoomAction zaInNI = (InOutZoomAction)noIcons_.get(Integer.valueOf(ZOOM_IN)); - // In this case, we do not want to allow a "wide" zoom, since we do not have - // a buffered image to handle it! Restrict to first defined zoom! - if (bfp_.getZoomController().zoomIsFirstDefined()) { - zaOutWI.setConditionalEnabled(false); - if (zaOutNI != null) zaOutNI.setConditionalEnabled(false); - zaInWI.setConditionalEnabled(true); - if (zaInNI != null) zaInNI.setConditionalEnabled(true); - } else if (bfp_.getZoomController().zoomIsMax()) { - zaOutWI.setConditionalEnabled(true); - if (zaOutNI != null) zaOutNI.setConditionalEnabled(true); - zaInWI.setConditionalEnabled(false); - if (zaInNI != null) zaInNI.setConditionalEnabled(false); - } else { - zaOutWI.setConditionalEnabled(true); - if (zaOutNI != null) zaOutNI.setConditionalEnabled(true); - zaInWI.setConditionalEnabled(true); - if (zaInNI != null) zaInNI.setConditionalEnabled(true); - } - return; - } - - /*************************************************************************** - ** - ** Set the current file - */ - - public void setCurrentXMLFile(File file) { - currentFile_ = file; - if (currentFile_ == null) { - return; - } - FabricCommands.setPreference("LoadDirectory", file.getAbsoluteFile().getParent()); - return; - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC STATIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Get the commands for the given tag - */ - - public static synchronized CommandSet getCmds(String className) { - if (perClass_ == null) { - throw new IllegalStateException(); - } - CommandSet fc = perClass_.get(className); - if (fc == null) { - throw new IllegalStateException(); - } - return (fc); - } - - /*************************************************************************** - ** - ** Init the commands for the given tag - */ - - public static synchronized CommandSet initCmds(String className, BioFabricApplication bfa, - BioFabricWindow topWindow, boolean isForMain) { - if (perClass_ == null) { - perClass_ = new HashMap(); - } - CommandSet fc = perClass_.get(className); - if (fc != null) { - throw new IllegalStateException(); - } - fc = new CommandSet(bfa, topWindow, isForMain); - perClass_.put(className, fc); - return (fc); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - private CommandSet(BioFabricApplication bfa, BioFabricWindow topWindow, boolean isMain) { - bfa_ = bfa; - topWindow_ = topWindow; - withIcons_ = new HashMap(); - noIcons_ = new HashMap(); - colGen_ = new FabricColorGenerator(); - colGen_.newColorModel(); - isForMain_ = isMain; - isAMac_ = System.getProperty("os.name").toLowerCase().startsWith("mac os x"); - FabricDisplayOptionsManager.getMgr().addTracker(this); - EventManager mgr = EventManager.getManager(); - mgr.addSelectionChangeListener(this); - } - - //////////////////////////////////////////////////////////////////////////// - // - // INNER CLASSES - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Checks if it is enabled or not - */ - - public abstract class ChecksForEnabled extends AbstractAction { - - private static final long serialVersionUID = 1L; - - protected static final int IGNORE = -1; - protected static final int DISABLED = 0; - protected static final int ENABLED = 1; - - protected boolean enabled_ = true; - protected boolean pushed_ = false; - - public void checkIfEnabled() { - enabled_ = checkGuts(); - if (!pushed_) { - this.setEnabled(enabled_); - } - return; - } - - public void pushDisabled(int pushCondition) { - pushed_ = canPush(pushCondition); - boolean reversed = reversePush(pushCondition); - if (pushed_) { - this.setEnabled(reversed); - } - } - - public void setConditionalEnabled(boolean enabled) { - // - // If we are pushed, just stash the value. If not - // pushed, stash and apply. - // - enabled_ = enabled; - if (!pushed_) { - this.setEnabled(enabled_); - } - } - - public boolean isPushed() { - return (pushed_); - } - - public void popDisabled() { - if (pushed_) { - this.setEnabled(enabled_); - pushed_ = false; - } - return; - } - - // Default can always be enabled: - protected boolean checkGuts() { - return (true); - } - - // Default can always be pushed: - protected boolean canPush(int pushCondition) { - return (true); - } - - // Signals we are reverse pushed (enabled when others disabled) - protected boolean reversePush(int pushCondition) { - return (false); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class PropagateDownAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - PropagateDownAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.PropagateDown")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.PropagateDown")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/PropagateSelected24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.PropagateDownMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.selectionsToSubmodel(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.haveASelection()); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class ZoomToSelected extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ZoomToSelected(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ZoomToSelected")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToSelected")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/ZoomToAllFabricSelected24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ZoomToSelectedMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.getZoomController().zoomToSelected(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.haveASelection()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ZoomToModelAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ZoomToModelAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ZoomToModel")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToModel")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/ZoomToAllFabric24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ZoomToModelMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.getZoomController().zoomToModel(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ZoomToCurrentSelected extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ZoomToCurrentSelected(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ZoomToCurrentSelected")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToCurrentSelected")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/ZoomToFabricSelected24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ZoomToCurrentSelectedMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.getZoomController().zoomToCurrentSelected(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.haveASelection()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ZoomToCurrentMouse extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ZoomToCurrentMouse(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ZoomToCurrentMouse")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToCurrentMouse")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ZoomToCurrentMouseMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - char accel = rMan.getChar("command.ZoomToCurrentMouseAccel"); - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - FabricMagnifyingTool fmt = bfp_.getMagnifier(); - Point2D pt = fmt.getMouseLoc(); - Point rcPoint = bfp_.worldToRowCol(pt); - Rectangle rect = bfp_.buildFocusBox(rcPoint); - bfp_.getZoomController().zoomToRect(rect); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ZoomToCurrentMagnify extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ZoomToCurrentMagnify(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ZoomToCurrentMagnify")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToCurrentMagnify")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/ZoomToFabricSelected24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ZoomToCurrentMagnifyMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - char accel = rMan.getChar("command.ZoomToCurrentMagnifyAccel"); - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - FabricMagnifyingTool fmt = bfp_.getMagnifier(); - Rectangle rect = fmt.getClipRect(); - bfp_.getZoomController().zoomToRect(rect); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class CenterOnNextSelected extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - CenterOnNextSelected(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.CenterOnNextSelected")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.CenterOnNextSelected")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/Forward24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.CenterOnNextSelectedMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.getZoomController().centerToNextSelected(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.haveASelection()); - } - } - - - /*************************************************************************** - ** - ** Command - */ - - private class CenterOnPreviousSelected extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - CenterOnPreviousSelected(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.CenterOnPreviousSelected")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.CenterOnPreviousSelected")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/Back24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.CenterOnPreviousSelectedMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.getZoomController().centerToPreviousSelected(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.haveASelection()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class AddFirstNeighborsAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - AddFirstNeighborsAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.AddFirstNeighbors")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.AddFirstNeighbors")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/PlusOneDeg24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.AddFirstNeighborsMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.addFirstNeighbors(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.haveASelection()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class BuildSelectAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - BuildSelectAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.BuildSelect")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.BuildSelect")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.BuildSelectMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.toggleBuildSelect(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class InOutZoomAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - private char sign_; - - InOutZoomAction(boolean doIcon, char sign) { - sign_ = sign; - ResourceManager rMan = ResourceManager.getManager(); - String iconName; - String stringName; - String mnemName; - String accelName; - if (sign == '+') { - iconName = "ZoomIn24.gif"; - stringName = "command.ZoomIn"; - mnemName = "command.ZoomInMnem"; - accelName = "command.ZoomInAccel"; - } else { - iconName = "ZoomOut24.gif"; - stringName = "command.ZoomOut"; - mnemName = "command.ZoomOutMnem"; - accelName = "command.ZoomOutAccel"; - } - putValue(Action.NAME, rMan.getString(stringName)); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString(stringName)); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/" + iconName); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar(mnemName); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - char accel = rMan.getChar(accelName); - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.getZoomController().bumpZoomWrapper(sign_); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - public void setConditionalEnabled(boolean enabled) { - setEnabled(enabled); - return; - } - - // - // Override: We handle this internally. - // - public void checkIfEnabled() { - } - - protected boolean canPush(int pushCondition) { - return ((pushCondition & CommandSet.ALLOW_NAV_PUSH) == 0x00); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class ClearSelectionsAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ClearSelectionsAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ClearSel")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ClearSel")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/ClearFabricSelected24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ClearSelMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.clearSelections(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.haveASelection()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ZoomToRect extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ZoomToRect(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ZoomToRect")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToRect")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/ZoomToFabricRect24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ZoomToRectMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - char accel = rMan.getChar("command.ZoomToRectAccel"); - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); - } - - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.setToCollectZoomRect(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class CancelAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - CancelAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.CancelAddMode")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.CancelAddMode")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/Stop24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.CancelAddModeMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfp_.cancelModals(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (false); - } - - protected boolean reversePush(int pushCondition) { - return ((pushCondition & CommandSet.ALLOW_NAV_PUSH) != 0x00); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class SearchAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - SearchAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.Search")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.Search")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/Find24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.SearchMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - boolean haveSelection = bfp_.haveASelection(); - boolean buildingSels = bfp_.amBuildingSelections(); - FabricSearchDialog fsd = new FabricSearchDialog(topWindow_, topWindow_.getFabricPanel().getNetwork(), - haveSelection, buildingSels); - fsd.setVisible(true); - if (fsd.itemWasFound()) { - Set matches = fsd.getMatches(); - boolean doDiscard = fsd.discardSelections(); - topWindow_.getFabricPanel().installSearchResult(matches, doDiscard); - } - return; - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class CompareNodesAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - CompareNodesAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.CompareNodes")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.CompareNodes")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.CompareNodesMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - Set allNodeIDs = bfp_.getNetwork().getNodeSetIDs(); - Map> normNameToIDs = bfp_.getNetwork().getNormNameToIDs(); - CompareNodesSetupDialog fsd = new CompareNodesSetupDialog(topWindow_, allNodeIDs, normNameToIDs); - fsd.setVisible(true); - if (fsd.haveResult()) { - Set result = fsd.getResults(); - bfp_.installSearchResult(result, true); - bfp_.addFirstNeighbors(); - bfp_.selectionsToSubmodel(); - } - return; - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class CloseAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - CloseAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.Close")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.Close")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/Stop24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.CloseMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - bfa_.shutdownFabric(); - } catch (Exception ex) { - // Going down (usually) so don't show exception in UI - ex.printStackTrace(); - } - } - } - - /*************************************************************************** - ** - ** Command - */ - - private abstract class LayoutViaAttributesAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - LayoutViaAttributesAction(boolean doIcon, String name, String mnemStr) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString(name)); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString(name)); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar(mnemStr); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected abstract boolean performOperation(); - - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class LayoutNodesViaAttributesAction extends LayoutViaAttributesAction { - - private static final long serialVersionUID = 1L; - - LayoutNodesViaAttributesAction(boolean doIcon) { - super(doIcon, "command.LayoutNodesViaAttributes", "command.LayoutNodesViaAttributesMnem"); - } - - protected boolean performOperation() { - File file = getTheFile(".noa", ".na", "AttribDirectory", "filterName.noa"); - if (file == null) { - return (true); - } - Map nodeAttributes = loadTheFile(file, null, true); - if (nodeAttributes == null) { - return (true); - } - if (!bfp_.getNetwork().checkNewNodeOrder(nodeAttributes)) { - ResourceManager rMan = ResourceManager.getManager(); - JOptionPane.showMessageDialog(topWindow_, rMan.getString("attribRead.badRowMessage"), - rMan.getString("attribRead.badRowSemanticsTitle"), - JOptionPane.WARNING_MESSAGE); - return (true); - } - BioFabricNetwork.RelayoutBuildData bfn = - new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.BuildMode.NODE_ATTRIB_LAYOUT); - bfn.setNodeOrderFromAttrib(nodeAttributes); - NetworkRelayout nb = new NetworkRelayout(); - nb.doNetworkRelayout(bfn, null); - return (true); - } - - protected boolean checkGuts() { - return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class LayoutLinksViaAttributesAction extends LayoutViaAttributesAction { - - private static final long serialVersionUID = 1L; - - LayoutLinksViaAttributesAction(boolean doIcon) { - super(doIcon, "command.LayoutLinksViaAttributes", "command.LayoutLinksViaAttributesMnem"); - } - - protected boolean performOperation() { - File file = getTheFile(".eda", ".ed", "AttribDirectory", "filterName.eda"); - if (file == null) { - return (true); - } - Map> nameToIDs = bfp_.getNetwork().getNormNameToIDs(); - Map edgeAttributes = loadTheFile(file, nameToIDs, false); - if (edgeAttributes == null) { - return (true); - } - SortedMap modifiedAndChecked = bfp_.getNetwork().checkNewLinkOrder(edgeAttributes); - if (modifiedAndChecked == null) { - ResourceManager rMan = ResourceManager.getManager(); - JOptionPane.showMessageDialog(topWindow_, rMan.getString("attribRead.badColMessage"), - rMan.getString("attribRead.badColSemanticsTitle"), - JOptionPane.WARNING_MESSAGE); - return (true); - } - BioFabricNetwork.RelayoutBuildData bfn = - new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.BuildMode.LINK_ATTRIB_LAYOUT); - bfn.setLinkOrder(modifiedAndChecked); - NetworkRelayout nb = new NetworkRelayout(); - nb.doNetworkRelayout(bfn, null); - return (true); - } - - protected boolean checkGuts() { - return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ToggleShowTourAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - private boolean showTour_; - - ToggleShowTourAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ShowTourAction")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ShowTourAction")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ShowTourActionMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - showTour_ = true; - } - - public void actionPerformed(ActionEvent ev) { - showTour_ = !showTour_; - topWindow_.showTour(showTour_); - return; - } - - @Override - protected boolean checkGuts() { - return (showNav_); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ToggleShowNavPanelAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ToggleShowNavPanelAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.ShowNavPanel")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ShowNavPanel")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.ShowNavPanelMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - showNav_ = true; - } - - public void actionPerformed(ActionEvent ev) { - showNav_ = !showNav_; - topWindow_.showNavAndControl(showNav_); - checkForChanges(); // To disable/enable tour hiding - return; - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class LayoutViaNodeClusterAction extends LayoutViaAttributesAction { - - private static final long serialVersionUID = 1L; - - LayoutViaNodeClusterAction(boolean doIcon) { - super(doIcon, "command.LayoutViaNodeClusterAction", "command.LayoutViaNodeClusterAction"); - } - - protected boolean performOperation() { - Set sels = bfp_.getNodeSelections(); - NID.WithName selNode = (sels.size() == 1) ? sels.iterator().next() : null; - - ClusterLayoutSetupDialog clsd = new ClusterLayoutSetupDialog(topWindow_, bfp_.getNetwork(), selNode); - clsd.setVisible(true); - if (clsd.haveResult()) { - NodeClusterLayout.ClusterParams params = clsd.getParams(); - if (params.needsFile()) { - if (!ClusterLayoutSetupDialog.askForFileInfo(params, CommandSet.this, bfp_.getNetwork())) { - return (true); - } - } - BioFabricNetwork.RelayoutBuildData bfn = - new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.BuildMode.NODE_CLUSTER_LAYOUT); - NetworkRelayout nb = new NetworkRelayout(); - nb.doNetworkRelayout(bfn, params); - } - return (true); - } - - protected boolean checkGuts() { - return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class LayoutTopControlAction extends BasicLayoutAction { - - private static final long serialVersionUID = 1L; - - LayoutTopControlAction(boolean doIcon) { - super(doIcon, "command.TopControlLayout", "command.TopControlLayoutMnem", BioFabricNetwork.BuildMode.CONTROL_TOP_LAYOUT); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class HierDAGLayoutAction extends BasicLayoutAction { - - private static final long serialVersionUID = 1L; - - HierDAGLayoutAction(boolean doIcon) { - super(doIcon, "command.HierDAGLayout", "command.HierDAGLayoutMnem", BioFabricNetwork.BuildMode.HIER_DAG_LAYOUT); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class WorldBankLayoutAction extends BasicLayoutAction { - - private static final long serialVersionUID = 1L; - - WorldBankLayoutAction(boolean doIcon) { - super(doIcon, "command.WorldBankLayout", "command.WorldBankLayoutMnem", BioFabricNetwork.BuildMode.WORLD_BANK_LAYOUT); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class DefaultLayoutAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - DefaultLayoutAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.DefaultLayout")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.DefaultLayout")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.DefaultLayoutMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - Set sels = bfp_.getNodeSelections(); - NID.WithName selNode = (sels.size() == 1) ? sels.iterator().next() : null; - BreadthFirstLayoutDialog bfl = new BreadthFirstLayoutDialog(topWindow_, selNode, topWindow_.getFabricPanel().getNetwork()); - bfl.setVisible(true); - - if (bfl.haveResult()) { - DefaultLayout.Params params = bfl.getParams(); - BioFabricNetwork.RelayoutBuildData bfn = - new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.BuildMode.DEFAULT_LAYOUT); - NetworkRelayout nb = new NetworkRelayout(); - nb.doNetworkRelayout(bfn, params); - } - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private abstract class BasicLayoutAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - private BioFabricNetwork.BuildMode bMode_; - - BasicLayoutAction(boolean doIcon, String nameTag, String mnemTag, BioFabricNetwork.BuildMode bMode) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString(nameTag)); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString(nameTag)); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar(mnemTag); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - bMode_ = bMode; - } - - public void actionPerformed(ActionEvent e) { - try { - BioFabricNetwork.RelayoutBuildData bfn = new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), bMode_); - (new NetworkRelayout()).doNetworkRelayout(bfn, null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected boolean checkGuts() { - return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); - } - } - - - /*************************************************************************** - ** - ** Command - */ - - private class LayoutViaConnectivityAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - LayoutViaConnectivityAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.LayoutViaConnectivity")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LayoutViaConnectivity")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.LayoutViaConnectivityMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - private boolean performOperation(Object[] args) { - - NodeSimilarityLayoutSetupDialog clpd = - new NodeSimilarityLayoutSetupDialog(topWindow_, new NodeSimilarityLayout.ClusterParams()); - - clpd.setVisible(true); - if (!clpd.haveResult()) { - return (false); - } - - NodeSimilarityLayout.ClusterParams result = clpd.getParams(); - BioFabricNetwork.RelayoutBuildData bfn = - new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.BuildMode.CLUSTERED_LAYOUT); - NetworkRelayout nb = new NetworkRelayout(); - nb.doNetworkRelayout(bfn, result); - return (true); - } - - @Override - protected boolean checkGuts() { - return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class LayoutViaShapeMatchAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - LayoutViaShapeMatchAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.LayoutViaShapeMatch")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LayoutViaShapeMatch")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.LayoutViaShapeMatchMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - private boolean performOperation(Object[] args) { - - ReorderLayoutParamsDialog clpd = - new ReorderLayoutParamsDialog(topWindow_, new NodeSimilarityLayout.ResortParams()); - - clpd.setVisible(true); - if (!clpd.haveResult()) { - return (false); - } - - NodeSimilarityLayout.ResortParams result = clpd.getParams(); - BioFabricNetwork.RelayoutBuildData bfn = - new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.BuildMode.REORDER_LAYOUT); - NetworkRelayout nb = new NetworkRelayout(); - nb.doNetworkRelayout(bfn, result); - return (true); - } - - protected boolean checkGuts() { - return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class SetLinkGroupsAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - SetLinkGroupsAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.SetLinkGroups")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.SetLinkGroups")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.SetLinkGroupsMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - private boolean performOperation(Object[] args) { - - BioFabricNetwork bfn = bfp_.getNetwork(); - List currentTags = bfn.getLinkGroups(); - ArrayList links = new ArrayList(bfn.getAllLinks(true)); - Set allRelations = BioFabricNetwork.extractRelations(links).keySet(); - LinkGroupingSetupDialog lgsd = new LinkGroupingSetupDialog(topWindow_, currentTags, allRelations, bfn); - lgsd.setVisible(true); - if (!lgsd.haveResult()) { - return (false); - } - - BioFabricNetwork.LayoutMode mode = lgsd.getChosenMode(); - - BioFabricNetwork.BuildMode bmode; - if (mode == BioFabricNetwork.LayoutMode.PER_NODE_MODE) { - bmode = BioFabricNetwork.BuildMode.GROUP_PER_NODE_CHANGE; - } else if (mode == BioFabricNetwork.LayoutMode.PER_NETWORK_MODE) { - bmode = BioFabricNetwork.BuildMode.GROUP_PER_NETWORK_CHANGE; - } else { - throw new IllegalStateException(); - } - - BioFabricNetwork.RelayoutBuildData bfnd = new BioFabricNetwork.RelayoutBuildData(bfn, bmode); - bfnd.setGroupOrderAndMode(lgsd.getGroups(), mode); - - NetworkRelayout nb = new NetworkRelayout(); - nb.doNetworkRelayout(bfnd, null); - - return (true); - } - - @Override - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class LayoutNetworkAlignment extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - LayoutNetworkAlignment(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.LayoutNetworkAlignment")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LayoutNetworkAlignment")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.LayoutNetworkAlignmentMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - private boolean performOperation(Object[] args) { - - NetworkAlignmentDialog nad = new NetworkAlignmentDialog(topWindow_); - nad.setVisible(true); - - NetworkAlignment.NetworkAlignInfo nai = nad.getNAInfo(); - - NetworkAlignment na = new NetworkAlignment(nai); - -// System.out.println(na.getSmall().getSize()); -// System.out.println(na.getLarge().getSize()); - - return (true); - } - -// @Override -// protected boolean checkGuts() { -// return (bfp_.hasAModel()); -// } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class ImportSIFAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - private boolean doWeights_; - - ImportSIFAction(boolean doIcon, boolean doWeights) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString((doWeights) ? "command.LoadSIFWithWeights" :"command.LoadSIF")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString((doWeights) ? "command.LoadSIFWithWeights" :"command.LoadSIF")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar((doWeights) ? "command.LoadSIFWithWeightsMnem" :"command.LoadSIFMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - doWeights_ = doWeights; - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - private boolean performOperation(Object[] args) { - - File file = null; - String filename = FabricCommands.getPreference("LoadDirectory"); - while (file == null) { - JFileChooser chooser = new JFileChooser(); - FileExtensionFilters.SimpleFilter sf = new FileExtensionFilters.SimpleFilter(".sif", "filterName.sif"); - chooser.addChoosableFileFilter(sf); - chooser.setAcceptAllFileFilterUsed(true); - chooser.setFileFilter(sf); - - if (filename != null) { - File startDir = new File(filename); - if (startDir.exists()) { - chooser.setCurrentDirectory(startDir); - } - } - - int option = chooser.showOpenDialog(topWindow_); - if (option != JFileChooser.APPROVE_OPTION) { - return (true); - } - file = chooser.getSelectedFile(); - if (file == null) { - return (true); - } - if (!standardFileChecks(file, FILE_MUST_EXIST, FILE_CAN_CREATE_DONT_CARE, - FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE_DONT_CARE, FILE_CAN_READ)) { - file = null; - continue; - } - } - Integer magBins = (doWeights_) ? Integer.valueOf(4) : null; - return (loadFromSifSource(file, null, magBins, new UniqueLabeller())); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class LoadXMLAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - LoadXMLAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.LoadXML")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LoadXML")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.LoadXMLMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - char accel = rMan.getChar("command.LoadXMLAccel"); - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - private boolean performOperation(Object[] args) { - - File file = null; - String filename = FabricCommands.getPreference("LoadDirectory"); - while (file == null) { - JFileChooser chooser = new JFileChooser(); - FileExtensionFilters.SimpleFilter sf = new FileExtensionFilters.SimpleFilter(".bif", "filterName.bif"); - chooser.addChoosableFileFilter(sf); - chooser.setAcceptAllFileFilterUsed(true); - chooser.setFileFilter(sf); - - if (filename != null) { - File startDir = new File(filename); - if (startDir.exists()) { - chooser.setCurrentDirectory(startDir); - } - } - - int option = chooser.showOpenDialog(topWindow_); - if (option != JFileChooser.APPROVE_OPTION) { - return (true); - } - file = chooser.getSelectedFile(); - if (file == null) { - return (true); - } - if (!standardFileChecks(file, FILE_MUST_EXIST, FILE_CAN_CREATE_DONT_CARE, - FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE_DONT_CARE, FILE_CAN_READ)) { - file = null; - continue; - } - } - return (loadXMLFromSource(file)); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class LoadWithNodeAttributesAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - LoadWithNodeAttributesAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.LoadSIFWithNodeAttributes")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LoadSIFWithNodeAttributes")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.LoadSIFWithNodeAttributesMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - private boolean performOperation(Object[] args) { - File file = null; - String filename = FabricCommands.getPreference("LoadDirectory"); - while (file == null) { - JFileChooser chooser = new JFileChooser(); - FileExtensionFilters.SimpleFilter sf = new FileExtensionFilters.SimpleFilter(".sif", "filterName.sif"); - chooser.addChoosableFileFilter(sf); - chooser.setAcceptAllFileFilterUsed(true); - chooser.setFileFilter(sf); - if (filename != null) { - File startDir = new File(filename); - if (startDir.exists()) { - chooser.setCurrentDirectory(startDir); - } - } - - int option = chooser.showOpenDialog(topWindow_); - if (option != JFileChooser.APPROVE_OPTION) { - return (true); - } - file = chooser.getSelectedFile(); - if (file == null) { - return (true); - } - if (!standardFileChecks(file, FILE_MUST_EXIST, FILE_CAN_CREATE_DONT_CARE, - FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE_DONT_CARE, FILE_CAN_READ)) { - file = null; - continue; - } - } - - File attribFile = getTheFile(".noa", ".na", "AttribDirectory", "filterName.noa"); - if (attribFile == null) { - return (true); - } - - Map attribs = loadTheFile(attribFile, null, true); - if (attribs == null) { - return (true); - } - - return (loadFromSifSource(file, attribs, null, new UniqueLabeller())); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class SaveAsAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - SaveAsAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.SaveAs")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.SaveAs")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/SaveAs24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.SaveAsMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - public boolean performOperation(Object[] args) { - if (args == null) { - return (saveToFile(null)); - } else { - if (((Boolean)args[0]).booleanValue()) { - String fileName = (String)args[1]; - return (saveToFile(fileName)); - } else { - OutputStream stream = (OutputStream)args[1]; - try { - saveToOutputStream(stream); - } catch (IOException ioe) { - displayFileOutputError(); // Which is kinda bogus... - return (false); - } - return (true); - } - } - } - - @Override - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class SaveAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - SaveAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.Save")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.Save")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/Save24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.SaveMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - char accel = rMan.getChar("command.SaveAccel"); - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); - } - - public void actionPerformed(ActionEvent e) { - try { - if (currentFile_ != null) { - saveToFile(currentFile_.getAbsolutePath()); - } else { - saveToFile(null); - } - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - @Override - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private abstract class ExportOrderAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ExportOrderAction(boolean doIcon, String name, String mnemStr) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString(name)); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString(name)); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar(mnemStr); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected abstract FileFilter getFilter(); - protected abstract List getSuffixList(); - protected abstract String getPrefSuffix(); - protected abstract void writeItOut(File file) throws IOException; - - public boolean performOperation(Object[] args) { - File file = null; - String dirName = FabricCommands.getPreference("AttribDirectory"); - while (file == null) { - JFileChooser chooser = new JFileChooser(); - FileFilter sf = getFilter(); - chooser.addChoosableFileFilter(sf); - chooser.setAcceptAllFileFilterUsed(true); - chooser.setFileFilter(sf); - - chooser.addChoosableFileFilter(getFilter()); - if (dirName != null) { - File startDir = new File(dirName); - if (startDir.exists()) { - chooser.setCurrentDirectory(startDir); - } - } - int option = chooser.showSaveDialog(topWindow_); - if (option != JFileChooser.APPROVE_OPTION) { - return (true); - } - file = chooser.getSelectedFile(); - if (file != null) { - if (!file.exists()) { - List cand = getSuffixList(); - if (!FileExtensionFilters.hasASuffix(file.getName(), "", cand)) { - file = new File(file.getAbsolutePath() + getPrefSuffix()); - } - } - if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, - FILE_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { - file = null; - continue; - } - } - } - - try { - writeItOut(file); - } catch (IOException ioe) { - displayFileOutputError(); - return (false); - } - FabricCommands.setPreference("AttribDirectory", file.getAbsoluteFile().getParent()); - return (true); - } - - @Override - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class ExportNodeOrderAction extends ExportOrderAction { - - private static final long serialVersionUID = 1L; - - ExportNodeOrderAction(boolean doIcon) { - super(doIcon, "command.ExportNodeOrder", "command.ExportNodeOrderMnem"); - } - - protected FileFilter getFilter() { - return (new FileExtensionFilters.DoubleExtensionFilter(".noa", ".na", "filterName.noa")); - } - - protected List getSuffixList() { - ArrayList cand = new ArrayList(); - cand.add(".noa"); - cand.add(".na"); - return (cand); - } - - protected String getPrefSuffix() { - return (".noa"); - } - - protected void writeItOut(File file) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))); - bfp_.getNetwork().writeNOA(out); - out.close(); - return; - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ExportLinkOrderAction extends ExportOrderAction { - - private static final long serialVersionUID = 1L; - - ExportLinkOrderAction(boolean doIcon) { - super(doIcon, "command.ExportLinkOrder", "command.ExportLinkOrderMnem"); - } - - protected FileFilter getFilter() { - return (new FileExtensionFilters.DoubleExtensionFilter(".eda", ".ea", "filterName.eda")); - } - - protected List getSuffixList() { - ArrayList cand = new ArrayList(); - cand.add(".eda"); - cand.add(".ea"); - return (cand); - } - - protected String getPrefSuffix() { - return (".eda"); - } - - protected void writeItOut(File file) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))); - bfp_.getNetwork().writeEDA(out); - out.close(); - return; - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ExportSelectedNodesAction extends ExportOrderAction { - - private static final long serialVersionUID = 1L; - - ExportSelectedNodesAction(boolean doIcon) { - super(doIcon, "command.ExportSelectedNodes", "command.ExportSelectedNodesMnem"); - } - - protected FileFilter getFilter() { - return (new FileExtensionFilters.SimpleFilter(".txt", "filterName.txt")); - } - - protected List getSuffixList() { - ArrayList cand = new ArrayList(); - cand.add(".txt"); - return (cand); - } - - protected String getPrefSuffix() { - return (".txt"); - } - - protected void writeItOut(File file) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))); - Set sels = bfp_.getNodeSelections(); - Iterator sit = sels.iterator(); - while (sit.hasNext()) { - NID.WithName node = sit.next(); - out.println(node.getName()); - } - out.close(); - return; - } - - @Override - protected boolean checkGuts() { - return (super.checkGuts() && !bfp_.getNodeSelections().isEmpty()); - } - - } - - /*************************************************************************** - ** - ** Command - */ - - private class PrintAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - PrintAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.Print")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.Print")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/Print24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.PrintMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - char accel = rMan.getChar("command.PrintAccel"); - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); - } - - public void actionPerformed(ActionEvent e) { - try { - PrinterJob pj = PrinterJob.getPrinterJob(); - PageFormat pf = pj.defaultPage(); - pf.setOrientation(PageFormat.LANDSCAPE); - // FIX ME: Needed for Win32? Linux won't default to landscape without this? - //PageFormat pf2 = pj.pageDialog(pf); - pj.setPrintable(bfp_, pf); - if (pj.printDialog()) { - try { - pj.print(); - } catch (PrinterException pex) { - System.err.println(pex); - } - } - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - @Override - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class PrintPDFAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - PrintPDFAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.PrintPDF")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.PrintPDF")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/Print24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.PrintPDFMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - char accel = rMan.getChar("command.PrintPDFAccel"); - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); - } - - public void actionPerformed(ActionEvent e) { - try { - //PrinterJob pj = PrinterJob.getPrinterJob(); - //// PageFormat pf = pj.defaultPage(); - // pf.setOrientation(PageFormat.LANDSCAPE); - Properties p = new Properties(); - p.setProperty("PageSize","A5"); - // p.setProperty(PSGraphics2D.ORIENTATION, PageConstants.LANDSCAPE); - // ExportDialog export = new ExportDialog(); - // export.showExportDialog(topWindow_, "Export view as ...", bfp_, "export"); - - - Rectangle2D viewInWorld = bfp_.getViewInWorld(); - Dimension viw = new Dimension((int)(viewInWorld.getWidth() / 10.0), (int)(viewInWorld.getHeight() / 10.0)); - // VectorGraphics g = new PDFGraphics2D(new File("/Users/bill/OutputAOa.pdf"), viw); - // g.setProperties(p); - // g.startExport(); - // bfp_.print(g); - // g.endExport(); - - - // FIX ME: Needed for Win32? Linux won't default to landscape without this? - //PageFormat pf2 = pj.pageDialog(pf); - // pj.setPrintable(bfp_, pf); - // if (pj.printDialog()) { - // try { - // pj.print(); - // } catch (PrinterException pex) { - // System.err.println(pex); - // } - // } - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - @Override - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - } - - - - /*************************************************************************** - ** - ** Command - */ - - private abstract class ExportImageAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - ExportImageAction(boolean doIcon, String res, String mnemStr) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString(res)); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString(res)); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar(mnemStr); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - performOperation(null); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - protected abstract ExportSettingsDialog.ExportSettings getExportSettings(); - - - public boolean performOperation(Object[] args) { - - ExportSettingsDialog.ExportSettings set; - if (args == null) { - set = getExportSettings(); - if (set == null) { - return (true); - } - } else { - set = (ExportSettingsDialog.ExportSettings)args[0]; - } - - File file = null; - OutputStream stream = null; - - if (args == null) { // not headless... - List supported = ImageExporter.getSupportedFileSuffixes(); - String filename = FabricCommands.getPreference("ExportDirectory"); - while (file == null) { - JFileChooser chooser = new JFileChooser(); - chooser.addChoosableFileFilter(new FileExtensionFilters.MultiExtensionFilter(supported, "filterName.img")); - if (filename != null) { - File startDir = new File(filename); - if (startDir.exists()) { - chooser.setCurrentDirectory(startDir); - } - } - - int option = chooser.showSaveDialog(topWindow_); - if (option != JFileChooser.APPROVE_OPTION) { - return (true); - } - file = chooser.getSelectedFile(); - if (file == null) { - continue; - } - if (!file.exists()) { - List suffs = ImageExporter.getFileSuffixesForType(set.formatType); - if (!FileExtensionFilters.hasASuffix(file.getName(), "." , suffs)) { - file = new File(file.getAbsolutePath() + "." + - ImageExporter.getPreferredSuffixForType(set.formatType)); - } - } - if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, - FILE_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { - file = null; - continue; - } - } - } else { - if (((Boolean)args[1]).booleanValue()) { - file = new File((String)args[2]); - if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, - FILE_CHECK_OVERWRITE, FILE_MUST_BE_FILE, - FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { - return (false); - } - } else { - stream = (OutputStream)args[2]; - } - } - - try { - if (file != null) { - bfp_.exportToFile(file, set.formatType, set.res, set.zoomVal, set.size); - } else { - bfp_.exportToStream(stream, set.formatType, set.res, set.zoomVal, set.size); - } - if (args == null) { - FabricCommands.setPreference("ExportDirectory", file.getAbsoluteFile().getParent()); - } - } catch (IOException ioe) { - displayFileOutputError(); - return (false); - } - - return (true); - } - - @Override - protected boolean checkGuts() { - return (bfp_.hasAModel()); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class ExportSimpleAction extends ExportImageAction { - - private static final long serialVersionUID = 1L; - - ExportSimpleAction(boolean doIcon) { - super(doIcon, "command.Export", "command.ExportMnem"); - } - - protected ExportSettingsDialog.ExportSettings getExportSettings() { - Rectangle wr = bfp_.getWorldRect(); - ExportSettingsDialog esd = new ExportSettingsDialog(topWindow_, wr.width, wr.height); - esd.setVisible(true); - ExportSettingsDialog.ExportSettings set = esd.getResults(); - return (set); - } - } - - - /*************************************************************************** - ** - ** Command - */ - - private class ExportPublishAction extends ExportImageAction { - - private static final long serialVersionUID = 1L; - - ExportPublishAction(boolean doIcon) { - super(doIcon, "command.ExportPublish", "command.ExportPublishMnem"); - } - - protected ExportSettingsDialog.ExportSettings getExportSettings() { - Rectangle wr = bfp_.getWorldRect(); - ExportSettingsPublishDialog esd = new ExportSettingsPublishDialog(topWindow_, wr.width, wr.height); - esd.setVisible(true); - ExportSettingsDialog.ExportSettings set = esd.getResults(); - return (set); - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class EmptyNetworkAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - EmptyNetworkAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.EmptyNet")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.EmptyNet")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.EmptyNetMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - manageWindowTitle(null); - - BioFabricNetwork.RelayoutBuildData obd = new BioFabricNetwork.RelayoutBuildData(new UniqueLabeller(), - new HashSet(), - new HashSet(), - new HashMap(), - colGen_, - BioFabricNetwork.BuildMode.BUILD_FROM_SIF); - newModelOperations(obd, true); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - } - - /*************************************************************************** - ** - ** Command - */ - - private class SetDisplayOptionsAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - - SetDisplayOptionsAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.SetDisplayOpts")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.SetDisplayOpts")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/FIXME.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.SetDisplayOptsMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - } - - public void actionPerformed(ActionEvent e) { - try { - FabricDisplayOptionsDialog dod = new FabricDisplayOptionsDialog(topWindow_); - dod.setVisible(true); - if (dod.haveResult()) { - FabricDisplayOptionsManager dopmgr = FabricDisplayOptionsManager.getMgr(); - dopmgr.setDisplayOptions(dod.getNewOpts(), dod.needsRebuild(), dod.needsRecolor()); - } - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - } - - /*************************************************************************** - ** - ** Command - */ - - public class AboutAction extends ChecksForEnabled { - - private static final long serialVersionUID = 1L; - private URL aboutURL_; - private JEditorPane pane_; - private JFrame frame_; - private FixedJButton buttonB_; - private URL gnuUrl_; - private URL sunUrl_; - - AboutAction(boolean doIcon) { - ResourceManager rMan = ResourceManager.getManager(); - putValue(Action.NAME, rMan.getString("command.About")); - if (doIcon) { - putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.About")); - URL ugif = getClass().getResource("/org/systemsbiology/biofabric/images/About24.gif"); - putValue(Action.SMALL_ICON, new ImageIcon(ugif)); - } else { - char mnem = rMan.getChar("command.AboutMnem"); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); - } - aboutURL_ = getClass().getResource("/org/systemsbiology/biofabric/license/about.html"); - } - - // - // Having an image link in the html turns out to be problematic - // starting Fall 2008 with URL security holes being plugged. So - // change the window. Note we use a back button now too! - - public void actionPerformed(ActionEvent e) { - try { - if (frame_ != null) { - frame_.setExtendedState(JFrame.NORMAL); - frame_.toFront(); - return; - } - try { - pane_ = new JEditorPane(aboutURL_); - } catch (IOException ioex) { - ExceptionHandler.getHandler().displayException(ioex); - return; - } - // 8/09: COMPLETELY BOGUS, but URLs are breaking everywhere in the latest JVMs, an I don't - // have time to fix this in a more elegant fashion! - gnuUrl_ = getClass().getResource("/org/systemsbiology/biofabric/license/LICENSE"); - sunUrl_ = getClass().getResource("/org/systemsbiology/biofabric/license/LICENSE-SUN"); - ResourceManager rMan = ResourceManager.getManager(); - pane_.setEditable(false); - frame_ = new JFrame(rMan.getString("window.aboutTitle")); - pane_.addHyperlinkListener(new HyperlinkListener() { - public void hyperlinkUpdate(HyperlinkEvent ev) { - try { - if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - URL toUse = (ev.getDescription().indexOf("-SUN") != -1) ? sunUrl_ : gnuUrl_; - pane_.setPage(toUse); - buttonB_.setEnabled(true); - } - } catch (IOException ex) { - } - } - }); - frame_.addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - frame_ = null; - e.getWindow().dispose(); - } - }); - - JPanel cp = (JPanel)frame_.getContentPane(); - cp.setBackground(Color.white); - cp.setBorder(new EmptyBorder(20, 20, 20, 20)); - cp.setLayout(new GridBagLayout()); - GridBagConstraints gbc = new GridBagConstraints(); - // URL sugif = getClass().getResource( - // "/org/systemsbiology/biotapestry/images/BioTapestrySplash.gif"); - JLabel label = new JLabel(); //new ImageIcon(sugif)); - - UiUtil.gbcSet(gbc, 0, 0, 1, 3, UiUtil.BO, 0, 0, 5, 5, 5, 5, UiUtil.CEN, 1.0, 0.0); - cp.add(label, gbc); - - JScrollPane jsp = new JScrollPane(pane_); - UiUtil.gbcSet(gbc, 0, 3, 1, 2, UiUtil.BO, 0, 0, 5, 5, 5, 5, UiUtil.CEN, 1.0, 1.0); - cp.add(jsp, gbc); - - - buttonB_ = new FixedJButton(rMan.getString("dialogs.back")); - buttonB_.setEnabled(false); - buttonB_.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - try { - pane_.setPage(aboutURL_); - buttonB_.setEnabled(false); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - FixedJButton buttonC = new FixedJButton(rMan.getString("dialogs.close")); - buttonC.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - try { - frame_.setVisible(false); - frame_.dispose(); - frame_ = null; - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - Box buttonPanel = Box.createHorizontalBox(); - buttonPanel.add(Box.createHorizontalGlue()); - buttonPanel.add(buttonB_); - buttonPanel.add(Box.createHorizontalStrut(10)); - buttonPanel.add(buttonC); - UiUtil.gbcSet(gbc, 0, 5, 1, 1, UiUtil.HOR, 0, 0, 5, 5, 5, 5, UiUtil.SE, 1.0, 0.0); - cp.add(buttonPanel, gbc); - frame_.setSize(700, 700); - frame_.setLocationRelativeTo(topWindow_); - frame_.setVisible(true); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - } - - /*************************************************************************** - ** - ** Class for building networks - */ - - public class NetworkBuilder implements BackgroundWorkerOwner { - - private BioFabricNetwork.PreBuiltBuildData restore_; - - public void doNetworkBuild(BioFabricNetwork.BuildData bfn, boolean isMain) { - try { - if (bfn.canRestore()) { - BioFabricNetwork net = bfp_.getNetwork(); - restore_ = new BioFabricNetwork.PreBuiltBuildData(net, BioFabricNetwork.BuildMode.BUILD_FROM_XML); - } else { - restore_ = null; - } - preLoadOperations(); - NewNetworkRunner runner = new NewNetworkRunner(bfn, isMain); - BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, - "netBuild.waitTitle", "netBuild.wait", null, false); - runner.setClient(bwc); - bwc.launchWorker(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - public boolean handleRemoteException(Exception remoteEx) { - if (remoteEx instanceof IOException) { - finishedImport(null, (IOException)remoteEx); - return (true); - } - return (false); - } - - public void cleanUpPreEnable(Object result) { - return; - } - - public void handleCancellation() { - BioFabricNetwork.BuildData ubd; - if (restore_ != null) { - ubd = restore_; - } else { - ubd = new BioFabricNetwork.RelayoutBuildData(new UniqueLabeller(), - new HashSet(), new HashSet(), - new HashMap(), - colGen_, BioFabricNetwork.BuildMode.BUILD_FROM_SIF); - } - try { - newModelOperations(ubd, true); - } catch (IOException ioex) { - //Silent fail - } - return; - } - - public void cleanUpPostRepaint(Object result) { - finishedImport(result, null); - return; - } - - private void finishedImport(Object result, IOException ioEx) { - if (ioEx != null) { - displayFileInputError(ioEx); - return; - } - // FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); - // if ((goose != null) && goose.isActivated()) { - // SelectionSupport ss = goose.getSelectionSupport(); - // ss.setSpecies(species_); - // } - postLoadOperations((BufferedImage)result); - return; - } - } - - /*************************************************************************** - ** - ** Class for relayout of networks - */ - - public class NetworkRelayout implements BackgroundWorkerOwner { - - private BioFabricNetwork.PreBuiltBuildData restore_; - - public void doNetworkRelayout(BioFabricNetwork.RelayoutBuildData rbd, NodeSimilarityLayout.CRParams params) { - if (rbd.canRestore()) { - BioFabricNetwork net = bfp_.getNetwork(); - restore_ = new BioFabricNetwork.PreBuiltBuildData(net, BioFabricNetwork.BuildMode.BUILD_FROM_XML); - } else { - restore_ = null; - } - - try { - preLoadOperations(); - NetworkRelayoutRunner runner = new NetworkRelayoutRunner(rbd, params); - BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, - "netRelayout.waitTitle", "netRelayout.wait", null, true); - if (rbd.getMode() == BioFabricNetwork.BuildMode.REORDER_LAYOUT) { - bwc.makeSuperChart(); - } - runner.setClient(bwc); - bwc.launchWorker(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - public boolean handleRemoteException(Exception remoteEx) { - if (remoteEx instanceof IOException) { - finishedImport(null, (IOException)remoteEx); - return (true); - } - return (false); - } - - public void cleanUpPreEnable(Object result) { - return; - } - - public void handleCancellation() { - BioFabricNetwork.BuildData ubd; - if (restore_ != null) { - ubd = restore_; - } else { - ubd = new BioFabricNetwork.RelayoutBuildData(new UniqueLabeller(), - new HashSet(), - new HashSet(), - new HashMap(), - colGen_, - BioFabricNetwork.BuildMode.BUILD_FROM_SIF); - - } - try { - newModelOperations(ubd, true); - } catch (IOException ioex) { - //Silent fail - } - return; - } - - public void cleanUpPostRepaint(Object result) { - finishedImport(result, null); - return; - } - - private void finishedImport(Object result, IOException ioEx) { - if (ioEx != null) { - displayFileInputError(ioEx); - return; - } - // FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); - // if ((goose != null) && goose.isActivated()) { - // SelectionSupport ss = goose.getSelectionSupport(); - // ss.setSpecies(species_); - // } - postLoadOperations((BufferedImage)result); - return; - } - } - - /*************************************************************************** - ** - ** Class for loading huge files in - */ - - public class BackgroundFileReader implements BackgroundWorkerOwner { - - private FabricFactory ff_; - private Exception ex_; - - private File file_; - private List links_; - private Set loneNodeIDs_; - private UniqueLabeller idGen_; - private FabricSIFLoader.SIFStats sss_; - private Integer magBins_; - - public void doBackgroundSIFRead(File file, UniqueLabeller idGen, - List links, Set loneNodeIDs, - Map nameMap, FabricSIFLoader.SIFStats sss, Integer magBins) { - file_ = file; - links_ = links; - loneNodeIDs_ = loneNodeIDs; - idGen_ = idGen; - sss_ = sss; - magBins_ = magBins; - try { - SIFReaderRunner runner = new SIFReaderRunner(file, idGen, links, loneNodeIDs, nameMap, sss, magBins); - BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, - "fileLoad.waitTitle", "fileLoad.wait", null, false); - runner.setClient(bwc); - bwc.launchWorker(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - public void doBackgroundRead(FabricFactory ff, SUParser sup, File file) { - ff_ = ff; - file_ = file; - try { - ReaderRunner runner = new ReaderRunner(sup, file); - BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, - "fileLoad.waitTitle", "fileLoad.wait", null, false); - runner.setClient(bwc); - bwc.launchWorker(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - public boolean handleRemoteException(Exception remoteEx) { - if (remoteEx instanceof IOException) { - ex_ = remoteEx; - return (true); - } - return (false); - } - - public void cleanUpPreEnable(Object result) { - return; - } - - public void handleCancellation() { - throw new UnsupportedOperationException(); - } - - public void cleanUpPostRepaint(Object result) { - finishedLoad(); - return; - } - - private void finishedLoad() { - if (ex_ != null) { - displayFileInputError((IOException)ex_); - return; - } - if (ff_ != null) { - setCurrentXMLFile(file_); - postXMLLoad(ff_, file_.getName()); - } else { - finishLoadFromSIFSource(file_, idGen_, sss_, links_, loneNodeIDs_, (magBins_ != null)); - } - return; - } - } - - /*************************************************************************** - ** - ** Class for writing huge files out - */ - - public class BackgroundFileWriter implements BackgroundWorkerOwner { - - private Exception ex_; - private File file_; - - public void doBackgroundWrite(File file) { - file_ = file; - try { - WriterRunner runner = new WriterRunner(file); - BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, - "fileWrite.waitTitle", "fileWrite.wait", null, false); - runner.setClient(bwc); - bwc.launchWorker(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - public boolean handleRemoteException(Exception remoteEx) { - if (remoteEx instanceof IOException) { - ex_ = remoteEx; - return (true); - } - return (false); - } - - public void cleanUpPreEnable(Object result) { - return; - } - - public void handleCancellation() { - throw new UnsupportedOperationException(); - } - - public void cleanUpPostRepaint(Object result) { - finishedOut(); - return; - } - - private void finishedOut() { - if (ex_ != null) { - displayFileOutputError(); - return; - } - setCurrentXMLFile(file_); - manageWindowTitle(file_.getName()); - return; - } - } - - /*************************************************************************** - ** - ** Class for recoloring networks - */ - - public class NetworkRecolor implements BackgroundWorkerOwner { - - public void doNetworkRecolor(boolean isMain) { - try { - bfp_.shutdown(); - RecolorNetworkRunner runner = new RecolorNetworkRunner(isMain); - BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, - "netRecolor.waitTitle", "netRecolor.wait", null, false); - runner.setClient(bwc); - bwc.launchWorker(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - return; - } - - public boolean handleRemoteException(Exception remoteEx) { - if (remoteEx instanceof IOException) { - finishedRecolor(null, (IOException)remoteEx); - return (true); - } - return (false); - } - - public void cleanUpPreEnable(Object result) { - return; - } - - public void handleCancellation() { - // Not allowing cancellation! - return; - } - - public void cleanUpPostRepaint(Object result) { - finishedRecolor(result, null); - return; - } - - private void finishedRecolor(Object result, IOException ioEx) { - postRecolorOperations((BufferedImage)result); - return; - } - } - - /*************************************************************************** - ** - ** Background network import - */ - - private class NewNetworkRunner extends BackgroundWorker { - - private BioFabricNetwork.BuildData bfn_; - private boolean forMain_; - - public NewNetworkRunner(BioFabricNetwork.BuildData bfn, boolean forMain) { - super("Early Result"); - bfn_ = bfn; - forMain_ = forMain; - } - - public Object runCore() throws AsynchExitRequestException { - try { - BufferedImage bi = expensiveModelOperations(bfn_, forMain_); - return (bi); - } catch (IOException ex) { - stashException(ex); - return (null); - } - } - - public Object postRunCore() { - return (null); - } - } - - /*************************************************************************** - ** - ** Background network layout - */ - - private class NetworkRelayoutRunner extends BackgroundWorker { - - private BioFabricNetwork.RelayoutBuildData rbd_; - private BioFabricNetwork.BuildMode mode_; - private NodeSimilarityLayout.CRParams params_; - - public NetworkRelayoutRunner(BioFabricNetwork.RelayoutBuildData rbd, NodeSimilarityLayout.CRParams params) { - super("Early Result"); - rbd_ = rbd; - mode_ = rbd.getMode(); - params_ = params; - } - - public Object runCore() throws AsynchExitRequestException { - try { - switch (mode_) { - case DEFAULT_LAYOUT: - (new DefaultLayout()).doLayout(rbd_, params_); - break; - case CONTROL_TOP_LAYOUT: - List forcedTop = new ArrayList(); - // forcedTop.add("VIM"); - // forcedTop.add("PACS1"); - // this has to be FORCED; the layers after the first are laid out in a crap fashion! - UiUtil.fixMePrintout("Gotta handle the forced top!"); - (new ControlTopLayout()).doLayout(rbd_, forcedTop); - break; - case HIER_DAG_LAYOUT: - (new HierDAGLayout()).doLayout(rbd_); - break; - case WORLD_BANK_LAYOUT: - (new ProcessWorldBankCSV()).doLayout(rbd_); - break; - case NODE_ATTRIB_LAYOUT: - case LINK_ATTRIB_LAYOUT: - case GROUP_PER_NODE_CHANGE: - case GROUP_PER_NETWORK_CHANGE: - // previously installed.... - break; - case REORDER_LAYOUT: - (new NodeSimilarityLayout()).doReorderLayout(rbd_, params_, this, 0.0, 1.0); - break; - case CLUSTERED_LAYOUT: - (new NodeSimilarityLayout()).doClusteredLayout(rbd_, params_, this, 0.0, 1.0); - break; - case NODE_CLUSTER_LAYOUT: - (new NodeClusterLayout()).orderByClusterAssignment(rbd_, params_, this, 0.0, 1.0); - break; - case SHADOW_LINK_CHANGE: - case BUILD_FOR_SUBMODEL: - case BUILD_FROM_XML: - case BUILD_FROM_SIF: - case BUILD_FROM_GAGGLE: - default: - throw new IllegalArgumentException(); - } - BufferedImage bi = expensiveModelOperations(rbd_, true); - return (bi); - } catch (IOException ex) { - stashException(ex); - return (null); - } - } - - public Object postRunCore() { - return (null); - } - } - - /*************************************************************************** - ** - ** Background network recolor - */ - - private class RecolorNetworkRunner extends BackgroundWorker { - - private boolean forMain_; - - public RecolorNetworkRunner(boolean forMain) { - super("Early Result"); - forMain_ = forMain; - } - - public Object runCore() throws AsynchExitRequestException { - try { - BufferedImage bi = expensiveRecolorOperations(forMain_); - return (bi); - } catch (IOException ex) { - stashException(ex); - return (null); - } - } - - public Object postRunCore() { - return (null); - } - } - - /*************************************************************************** - ** - ** Background file load - */ - - private class ReaderRunner extends BackgroundWorker { - - private File myFile_; - private SUParser myParser_; - - public ReaderRunner(SUParser sup, File file) { - super("Early Result"); - myFile_ = file; - myParser_ = sup; - } - public Object runCore() throws AsynchExitRequestException { - try { - myParser_.parse(myFile_); - return (new Boolean(true)); - } catch (IOException ioe) { - stashException(ioe); - return (null); - } - } - public Object postRunCore() { - return (null); - } - } - - /*************************************************************************** - ** - ** Background file load - */ - - private class SIFReaderRunner extends BackgroundWorker { - - private File myFile_; - private List links_; - private Set loneNodeIDs_; - private UniqueLabeller idGen_; - private Map nameMap_; - private FabricSIFLoader.SIFStats sss_; - private Integer magBins_; - - public SIFReaderRunner(File file, UniqueLabeller idGen, List links, - Set loneNodeIDs, Map nameMap, - FabricSIFLoader.SIFStats sss, Integer magBins) { - super("Early Result"); - myFile_ = file; - links_ = links; - loneNodeIDs_ = loneNodeIDs; - idGen_ = idGen; - nameMap_ = nameMap; - sss_ = sss; - magBins_ = magBins; - } - - public Object runCore() throws AsynchExitRequestException { - try { - FabricSIFLoader.SIFStats sss = (new FabricSIFLoader()).readSIF(myFile_, idGen_, links_, loneNodeIDs_, nameMap_, magBins_); - sss_.copyInto(sss); - return (new Boolean(true)); - } catch (IOException ioe) { - stashException(ioe); - return (null); - } - } - public Object postRunCore() { - return (null); - } - } - - /*************************************************************************** - ** - ** Background file write - */ - - private class WriterRunner extends BackgroundWorker { - - private File myFile_; - - public WriterRunner(File file) { - super("Early Result"); - myFile_ = file; - } - public Object runCore() throws AsynchExitRequestException { - try { - saveToOutputStream(new FileOutputStream(myFile_)); - return (new Boolean(true)); - } catch (IOException ioe) { - stashException(ioe); - return (null); - } - } - public Object postRunCore() { - return (null); - } - } -} diff --git a/src/org/systemsbiology/biofabric/layouts/ControlTopLayout.java b/src/org/systemsbiology/biofabric/layouts/ControlTopLayout.java deleted file mode 100644 index 350cd91..0000000 --- a/src/org/systemsbiology/biofabric/layouts/ControlTopLayout.java +++ /dev/null @@ -1,440 +0,0 @@ -/* -** Copyright (C) 2003-2014 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.systemsbiology.biofabric.analysis.CycleFinder; -import org.systemsbiology.biofabric.analysis.GraphSearcher; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.UiUtil; - -/**************************************************************************** -** -** Control nodes at top -*/ - -public class ControlTopLayout { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public ControlTopLayout() { - - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public void doLayout(BioFabricNetwork.RelayoutBuildData rbd, List forcedTop) { - doNodeLayout(rbd, forcedTop); - (new DefaultEdgeLayout()).layoutEdges(rbd); - return; - } - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public List doNodeLayout(BioFabricNetwork.RelayoutBuildData rbd, List forcedTop) { - - List targets = orderByNodeDegree(rbd, forcedTop); - // - // Now have the ordered list of targets we are going to display. - // Build target->row maps and the inverse: - // - (new DefaultLayout()).installNodeOrder(targets, rbd); - return (targets); - } - - /*************************************************************************** - ** - ** Target nodes are ordered by degree. Within degree, targets are arranged - ** to "odometer" thru the inputs - */ - - private List orderByNodeDegree(BioFabricNetwork.RelayoutBuildData rbd, List forcedTop) { - - List snSorted = (forcedTop == null) ? controlSort(rbd.allNodeIDs, rbd.allLinks) : forcedTop; - HashSet snSortSet = new HashSet(snSorted); - ArrayList outList = new ArrayList(); - outList.addAll(snSorted); - - UiUtil.fixMePrintout("UGLY HACK"); - - HashSet repLin = new HashSet(); - Iterator alit = rbd.allLinks.iterator(); - while (alit.hasNext()) { - FabricLink nLink = alit.next(); - if ((forcedTop != null) && !forcedTop.contains(nLink.getSrcID()) && !nLink.isFeedback()) { - repLin.add(nLink.flipped()); - } else { - repLin.add(nLink); - } - } - - GraphSearcher gs = new GraphSearcher(rbd.allNodeIDs, repLin); //rbd.allLinks); - SortedSet snds = gs.nodeDegreeSetWithSource(snSorted); - - Iterator dfit = snds.iterator(); - while (dfit.hasNext()) { - GraphSearcher.SourcedNodeDegree node = dfit.next(); - if (!snSortSet.contains(node.getNode())) { - outList.add(node.getNode()); - } - } - return (outList); - } - - /*************************************************************************** - ** - ** Calculate control node order; this will create a partial ordering. Cycles - ** are currently broken arbitrarily: - */ - - private List controlSort(Set nodes, Set links) { - - // - // Create a set of all the source nodes: - // - - HashSet srcs = new HashSet(); - Iterator lit = links.iterator(); - while (lit.hasNext()) { - FabricLink nextLink = lit.next(); - srcs.add(nextLink.getSrcID()); - } - - // - // Create a set of links that are internal to the control - // subnetwork: - // - - HashSet ctrlLinks = new HashSet(); - lit = links.iterator(); - while (lit.hasNext()) { - FabricLink nextLink = lit.next(); - if (srcs.contains(nextLink.getTrgID())) { - ctrlLinks.add(nextLink); - } - } - - // - // Create a subset of the control links that form a DAG: - // Note the order is arbitrary: - // - - HashSet dagLinks = new HashSet(); - HashSet testLinks = new HashSet(); - lit = ctrlLinks.iterator(); - while (lit.hasNext()) { - FabricLink nextLink = lit.next(); - if (nextLink.isShadow()) { - continue; - } - testLinks.add(nextLink); - CycleFinder cf = new CycleFinder(nodes, testLinks); - if (!cf.hasACycle()) { - dagLinks.add(nextLink); - } else { - testLinks.remove(nextLink); - } - } - - // - // Topo sort the nodes: - // - - GraphSearcher gs = new GraphSearcher(srcs, dagLinks); - Map ts = gs.topoSort(false); - List retval = gs.topoSortToPartialOrdering(ts, links); - - // - // Nodes that were dropped due to cycles still need to be added as - // source nodes! FIXME: Should add in degree order, not alpha order! - // - // - - TreeSet remaining = new TreeSet(srcs); - remaining.removeAll(retval); - retval.addAll(remaining); - - return (retval); - } - - /*************************************************************************** - ** - ** Calculate an ordering of nodes that puts the highest degree nodes first: - */ - - private List allNodeOrder(Set nodes, Set links) { - GraphSearcher gs = new GraphSearcher(nodes, links); - List retval = gs.nodeDegreeOrder(); - Collections.reverse(retval); - return (retval); - } - - /*************************************************************************** - ** - ** Order source nodes by median target degree - */ - - private SortedSet medianTargetDegree(Set nodes, Set links) { - - GraphSearcher gs = new GraphSearcher(nodes, links); - Map nDeg = gs.nodeDegree(true); - - HashMap> deg = new HashMap>(); - Iterator lit = links.iterator(); - while (lit.hasNext()) { - FabricLink nextLink = lit.next(); - NID.WithName src = nextLink.getSrcID(); - NID.WithName trg = nextLink.getTrgID(); - Integer trgDeg = nDeg.get(trg); - List forSrc = deg.get(src); - if (forSrc == null) { - forSrc = new ArrayList(); - deg.put(src, forSrc); - } - forSrc.add(trgDeg); - } - - TreeSet retval = new TreeSet(); - Iterator sit = deg.keySet().iterator(); - while (sit.hasNext()) { - NID.WithName src = sit.next(); - List forSrc = deg.get(src); - Collections.sort(forSrc); - int size = forSrc.size(); - int medI = size / 2; - Integer med = forSrc.get(medI); - retval.add(new GraphSearcher.NodeDegree(src, med.intValue())); - } - return (retval); - } - - /*************************************************************************** - ** - ** Calculate control node order - */ - - private List controlSortDegreeOnly(Set nodes, Set links) { - - HashSet srcs = new HashSet(); - Iterator lit = links.iterator(); - while (lit.hasNext()) { - FabricLink nextLink = lit.next(); - srcs.add(nextLink.getSrcID()); - } - - HashSet ctrlLinks = new HashSet(); - lit = links.iterator(); - while (lit.hasNext()) { - FabricLink nextLink = lit.next(); - if (srcs.contains(nextLink.getTrgID())) { - ctrlLinks.add(nextLink); - } - } - - GraphSearcher gs = new GraphSearcher(srcs, ctrlLinks); - List retval = gs.nodeDegreeOrder(); - Collections.reverse(retval); - return (retval); - } - - /*************************************************************************** - ** - ** Return source nodes - */ - - private Set controlNodes(Set nodes, Set links) { - - HashSet srcs = new HashSet(); - Iterator lit = links.iterator(); - while (lit.hasNext()) { - FabricLink nextLink = lit.next(); - srcs.add(nextLink.getSrcID()); - } - return (srcs); - } - - /*************************************************************************** - ** - ** Generate breadth-first-order - */ - - private List orderBreadth(Set nodes, Set links) { - - // List controlNodes = cp.controlSortDegreeOnly(nodes, links); //cp.controlSort(nodes, links); - - ArrayList ctrlList = new ArrayList(); - Set cnSet = controlNodes(nodes, links); - - - List dfo = allNodeOrder(nodes, links); - Iterator dfit = dfo.iterator(); - while (dfit.hasNext()) { - NID.WithName node = dfit.next(); - if (cnSet.contains(node)) { - ctrlList.add(node); - } - } - - GraphSearcher gs = new GraphSearcher(nodes, links); - List queue = gs.breadthSearch(ctrlList); - - ArrayList outList = new ArrayList(); - Iterator qit = queue.iterator(); - while (qit.hasNext()) { - GraphSearcher.QueueEntry qe = qit.next(); - outList.add(qe.name); - } - return (outList); - } - - /*************************************************************************** - ** - ** Test frame - */ - - private List orderPureDegree(Set nodes, Set links) { - - Set cnSet = controlNodes(nodes, links); - ArrayList outList = new ArrayList(); - - List dfo = allNodeOrder(nodes, links); - Iterator dfit = dfo.iterator(); - while (dfit.hasNext()) { - NID.WithName node = dfit.next(); - if (cnSet.contains(node)) { - outList.add(node); - } - } - dfit = dfo.iterator(); - while (dfit.hasNext()) { - NID.WithName node = dfit.next(); - if (!cnSet.contains(node)) { - outList.add(node); - } - } - return (outList); - } - - /*************************************************************************** - ** - ** Test frame - */ - - private List orderCtrlMedianTargetDegree(Set nodes, Set links) { - - Set cnSet = controlNodes(nodes, links); - ArrayList outList = new ArrayList(); - - SortedSet ctrlMed = medianTargetDegree(nodes, links); - Iterator ndit = ctrlMed.iterator(); - while (ndit.hasNext()) { - GraphSearcher.NodeDegree nodeDeg = ndit.next(); - outList.add(nodeDeg.getNode()); - } - Collections.reverse(outList); - - List dfo = allNodeOrder(nodes, links); - Iterator dfit = dfo.iterator(); - while (dfit.hasNext()) { - NID.WithName node = dfit.next(); - if (!cnSet.contains(node)) { - outList.add(node); - } - } - return (outList); - } - - /*************************************************************************** - ** - ** Test frame - */ - - private List mainSourceSortedTargs(Set nodes, Set links) { - - List snSorted = controlSort(nodes, links); - HashSet snSortSet = new HashSet(snSorted); - ArrayList outList = new ArrayList(); - outList.addAll(snSorted); - - GraphSearcher gs = new GraphSearcher(nodes, links); - SortedSet snds = gs.nodeDegreeSetWithSource(snSorted); - - Iterator dfit = snds.iterator(); - while (dfit.hasNext()) { - GraphSearcher.SourcedNodeDegree node = dfit.next(); - if (!snSortSet.contains(node.getNode())) { - outList.add(node.getNode()); - } - } - return (outList); - } -} - diff --git a/src/org/systemsbiology/biofabric/layouts/DefaultEdgeLayout.java b/src/org/systemsbiology/biofabric/layouts/DefaultEdgeLayout.java deleted file mode 100644 index 868a68b..0000000 --- a/src/org/systemsbiology/biofabric/layouts/DefaultEdgeLayout.java +++ /dev/null @@ -1,416 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.systemsbiology.biofabric.analysis.NIDLink; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.NID; - -/**************************************************************************** -** -** This is the default layout algorithm for edges. Actually usable in combination -** with a wide variety of different node layout algorithms, not just the default -*/ - -public class DefaultEdgeLayout { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public DefaultEdgeLayout() { - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public void layoutEdges(BioFabricNetwork.RelayoutBuildData rbd) { - - Map nodeOrder = rbd.nodeOrder; - - // - // Build target->row maps and the inverse: - // - HashMap targToRow = new HashMap(); - HashMap rowToTarg = new HashMap(); - Iterator trit = nodeOrder.keySet().iterator(); - while (trit.hasNext()) { - NID.WithName target = trit.next(); - Integer rowObj = nodeOrder.get(target); - targToRow.put(target, rowObj); - rowToTarg.put(rowObj, target); - } - - // - // Now each link is given a vertical extent. - // - - TreeMap> rankedLinks = new TreeMap>(); - Map> relsForPair = - generateLinkExtents(rbd.allLinks, targToRow, rankedLinks); - - // - // Ordering of links: - // - - rbd.setLinkOrder(defaultLinkToColumn(rankedLinks, relsForPair, rowToTarg, rbd)); - - return; - } - - - /*************************************************************************** - ** - ** Process a link set - */ - - private SortedMap defaultLinkToColumn(SortedMap> rankedLinks, - Map> relsForPair, - HashMap rowToTarg, - BioFabricNetwork.RelayoutBuildData rbd) { - - TreeMap linkOrder = new TreeMap(); - // - // This now assigns the link to its column. Note that we order them - // so that the shortest vertical link is drawn first! - // - - ArrayList microRels; - ArrayList macroRels; - if (rbd.layoutMode == BioFabricNetwork.LayoutMode.PER_NODE_MODE) { - microRels = new ArrayList(rbd.linkGroups); - macroRels = null; - } else if (rbd.layoutMode == BioFabricNetwork.LayoutMode.PER_NETWORK_MODE) { - microRels = new ArrayList(); - macroRels = new ArrayList(rbd.linkGroups); - } else { - microRels = new ArrayList(); - macroRels = null; - } - - if (microRels.isEmpty()) { - microRels.add(""); - } - int numRel = microRels.size(); - - int colCount = 0; - int rowCount = rbd.nodeOrder.size(); - // For each top row... - for (int k = 0; k < rowCount; k++) { - Integer topRow = Integer.valueOf(k); - for (int i = 0; i < numRel; i++) { - String relOnly = microRels.get(i); - if (relOnly.equals("")) { - relOnly = null; - } - colCount = shadowLinkToColumn(topRow.intValue(), rankedLinks, relsForPair, relOnly, microRels, colCount, rowToTarg, rbd, linkOrder); - SortedSet perSrc = rankedLinks.get(topRow); - if (perSrc == null) { - continue; - } - Iterator psit = perSrc.iterator(); - - // Drain the bottom rows, in increasing order... - while (psit.hasNext()) { - Integer botRow = psit.next(); - NID.WithName topNode = rowToTarg.get(topRow); - NID.WithName botNode = rowToTarg.get(botRow); - // Dumping links in order of the relation sort (alphabetical)... - SortedMap forPair1 = relsForPair.get(new NIDLink(topNode, botNode)); - if (forPair1 != null) { - Iterator fp1it = forPair1.values().iterator(); - while (fp1it.hasNext()) { - FabricLink nextLink = fp1it.next(); - if (!nextLink.isShadow()) { - String augRel = nextLink.getAugRelation().relation; - if (bestSuffixMatch(augRel, relOnly, microRels)) { - Integer shadowKey = Integer.valueOf(colCount++); - linkOrder.put(shadowKey, nextLink); - } - } - } - } - // With directed links from above coming before directed links from below... - if (!topNode.equals(botNode)) { // DO NOT DUPLICATE FEEDBACK LINKS! - SortedMap forPair2 = relsForPair.get(new NIDLink(botNode, topNode)); - if (forPair2 != null) { - Iterator fp2it = forPair2.values().iterator(); - while (fp2it.hasNext()) { - FabricLink nextLink = fp2it.next(); - if (!nextLink.isShadow()) { - String augRel = nextLink.getAugRelation().relation; - if (bestSuffixMatch(augRel, relOnly, microRels)) { - Integer shadowKey = Integer.valueOf(colCount++); - linkOrder.put(shadowKey, nextLink); - } - } - } - } - } - } - } - } - - // - // This is what determines if we have an existing link order that needs to reorganize on a per-network basis: - // - - if (rbd.layoutMode == BioFabricNetwork.LayoutMode.PER_NETWORK_MODE) { - orderNetworkByGroups(linkOrder, macroRels); - } - - return (linkOrder); - } - - /*************************************************************************** - * existingOrd's link order will follow groupOrder's relation order. - */ - - private void orderNetworkByGroups(SortedMap existingOrd, List groupOrder) { - - Map> groups = new TreeMap>(); - // String: link relation, List: all the links with that relation - - for (Map.Entry entry : existingOrd.entrySet()) { - - FabricLink fl = entry.getValue(); - String rel = fl.getRelation(); - - if (groups.get(rel) == null) { - groups.put(rel, new ArrayList()); - } - - groups.get(rel).add(fl); - } - - int rowIdx = 0; - for (String suffix : groupOrder) { // note: 'groupOrder' contains the suffixes - - for (String fullRel : groups.keySet()) { // iterate through full Relation names to find best match - - if (bestSuffixMatch(fullRel, suffix, groupOrder)) { - - List group = groups.get(fullRel); - for (FabricLink fl : group) { - existingOrd.put(rowIdx, fl); - rowIdx++; // increment the row index - } - } - } - - } - return; - } - - /*************************************************************************** - ** - ** Get shadow links into their columns: - */ - - private int shadowLinkToColumn(int currDrainRow, SortedMap> rankedLinks, - Map> relsForPair, - String relOnly, List allRels, int colCount, HashMap rowToTarg, - BioFabricNetwork.RelayoutBuildData rbd, TreeMap linkOrder) { - - Iterator rlit = rankedLinks.keySet().iterator(); - // For each top row... - while (rlit.hasNext()) { - Integer topRow = rlit.next(); - SortedSet perSrc = rankedLinks.get(topRow); - Iterator psit = perSrc.iterator(); - // Drain ONLY the bottom row that ends on our row... - while (psit.hasNext()) { - Integer botRow = psit.next(); - if (botRow.intValue() != currDrainRow) { - continue; - } - // We NEVER create shadow feedback links. They are insanely redundant. - if (topRow.equals(botRow)) { - continue; - } - - NID.WithName topNode = rowToTarg.get(topRow); - NID.WithName botNode = rowToTarg.get(botRow); - // Dumping links in order of the relation sort (alphabetical)... - SortedMap forPair1 = relsForPair.get(new NIDLink(topNode, botNode)); - if (forPair1 != null) { - Iterator fp1it = forPair1.values().iterator(); - while (fp1it.hasNext()) { - // But ONLY if they are shadow links: - FabricLink nextLink = fp1it.next(); - if (nextLink.isShadow()) { - String augRel = nextLink.getAugRelation().relation; - if (bestSuffixMatch(augRel, relOnly, allRels)) { - Integer shadowKey = Integer.valueOf(colCount++); - linkOrder.put(shadowKey, nextLink); - } - } - } - } - // With directed links from above coming before directed links from below... - // This test should now always be true, given we are never doing feedback.... - if (!topNode.equals(botNode)) { // DO NOT DUPLICATE FEEDBACK LINKS! - SortedMap forPair2 = relsForPair.get(new NIDLink(botNode, topNode)); - if (forPair2 != null) { - Iterator fp2it = forPair2.values().iterator(); - while (fp2it.hasNext()) { - FabricLink nextLink = fp2it.next(); - if (nextLink.isShadow()) { - String augRel = nextLink.getAugRelation().relation; - if (bestSuffixMatch(augRel, relOnly, allRels)) { - Integer shadowKey = Integer.valueOf(colCount++); - linkOrder.put(shadowKey, nextLink); - } - } - } - } - } else { - throw new IllegalStateException(); // Now should never get here for shadow links... - } - } - } - return (colCount); - } - - /*************************************************************************** - ** - ** Answer if the given relation has the best suffix match with the given match, - ** given all the options. Thus, "430" should match "30" instead of "0" if both - ** are present. - */ - - private boolean bestSuffixMatch(String augR, String relToMatch, List allRels) { - if (relToMatch == null) { - return (true); - } - int topLen = 0; - String topRel = null; - for (String aRel : allRels) { - int matchLen = aRel.length(); - if (matchLen < topLen) { - continue; - } - int ioaRel = augR.indexOf(aRel); - if ((ioaRel >= 0) && ((ioaRel == (augR.length() - matchLen)))) { - if (topLen == matchLen) { - throw new IllegalStateException(); - } else if (topLen < matchLen) { - topLen = matchLen; - topRel = aRel; - } - } - } - if (topRel == null) { - throw new IllegalStateException(); - } - return (topRel.equals(relToMatch)); - } - - /*************************************************************************** - ** - ** Generate vertical extents for links: - ** - ** Returns Map relsForPair: - ** Maps each simple source/target "Link" to sorted map - ** Sorted map maps each link relation to the associated FabricLink, ordered by - ** how the AugRelation comparator works - ** - ** Fills in empty SortedMap rankedLinks: - ** Maps each top link row to an ordered set of link maximums - */ - - private Map> generateLinkExtents(Set allLinks, - HashMap targToRow, - TreeMap> rankedLinks) { - // - // Now each link is given a vertical extent. - // - - HashMap> relsForPair - = new HashMap>(); - // HashMap directedMap = new HashMap(); - Iterator alit = allLinks.iterator(); - while (alit.hasNext()) { - FabricLink nextLink = alit.next(); - NID.WithName source = nextLink.getSrcID(); - NID.WithName target = nextLink.getTrgID(); - // boolean directed = nextLink.isDirected(); - // directedMap.put(new Link(source, target), new Boolean(directed)); - NIDLink key = new NIDLink(source, target); - SortedMap rels = relsForPair.get(key); - if (rels == null) { - rels = new TreeMap(); - relsForPair.put(key, rels); - } - rels.put(nextLink.getAugRelation(), nextLink); - Integer srcRow = targToRow.get(source); - Integer trgRow = targToRow.get(target); - Integer minRow; - Integer maxRow; - if (srcRow.intValue() < trgRow.intValue()) { - minRow = srcRow; - maxRow = trgRow; - } else { - minRow = trgRow; - maxRow = srcRow; - } - SortedSet perSrc = rankedLinks.get(minRow); // min == node row! - if (perSrc == null) { - perSrc = new TreeSet(); - rankedLinks.put(minRow, perSrc); - } - perSrc.add(maxRow); // Have the ordered set of link maxes - } - return (relsForPair); - } -} diff --git a/src/org/systemsbiology/biofabric/layouts/DefaultLayout.java b/src/org/systemsbiology/biofabric/layouts/DefaultLayout.java deleted file mode 100644 index 4f346c7..0000000 --- a/src/org/systemsbiology/biofabric/layouts/DefaultLayout.java +++ /dev/null @@ -1,321 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.NID; - -/**************************************************************************** -** -** This is the default layout algorithm -*/ - -public class DefaultLayout { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public DefaultLayout() { - - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public void doLayout(BioFabricNetwork.RelayoutBuildData rbd, NodeSimilarityLayout.CRParams params) { - doNodeLayout(rbd, ((Params)params).startNodes); - (new DefaultEdgeLayout()).layoutEdges(rbd); - return; - } - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public List doNodeLayout(BioFabricNetwork.RelayoutBuildData rbd, List startNodeIDs) { - - List targetIDs = defaultNodeOrder(rbd.allLinks, rbd.loneNodeIDs, startNodeIDs); - - // - // Now have the ordered list of targets we are going to display. - // Build target->row maps and the inverse: - // - - installNodeOrder(targetIDs, rbd); - return (targetIDs); - } - - /*************************************************************************** - ** - ** Install node orders - */ - - public void installNodeOrder(List targetIDs, BioFabricNetwork.RelayoutBuildData rbd) { - - int currRow = 0; - HashMap nodeOrder = new HashMap(); - Iterator trit = targetIDs.iterator(); - while (trit.hasNext()) { - NID.WithName target = trit.next(); - Integer rowTag = Integer.valueOf(currRow++); - nodeOrder.put(target, rowTag); - } - rbd.setNodeOrder(nodeOrder); - return; - } - - /*************************************************************************** - ** - ** Calculate default node order - */ - - public List defaultNodeOrder(Set allLinks, - Set loneNodes, List startNodes) { - // - // Note the allLinks Set has pruned out duplicates and synonymous non-directional links - // - // - // Build a target list, top to bottom, that adds the node with the most - // links first, and adds those link targets ASAP. If caller supplies a start node, - // we go there first: - // - - HashMap linkCounts = new HashMap(); - HashMap> targsPerSource = new HashMap>(); - ArrayList targets = new ArrayList(); - - HashSet targsToGo = new HashSet(); - Iterator alit = allLinks.iterator(); - while (alit.hasNext()) { - FabricLink nextLink = alit.next(); - NID.WithName sidwn = nextLink.getSrcID(); - NID.WithName tidwn = nextLink.getTrgID(); - Set targs = targsPerSource.get(sidwn); - if (targs == null) { - targs = new HashSet(); - targsPerSource.put(sidwn, targs); - } - targs.add(tidwn); - targs = targsPerSource.get(tidwn); - if (targs == null) { - targs = new HashSet(); - targsPerSource.put(tidwn, targs); - } - targs.add(sidwn); - targsToGo.add(sidwn); - targsToGo.add(tidwn); - Integer srcCount = linkCounts.get(sidwn); - linkCounts.put(sidwn, (srcCount == null) ? Integer.valueOf(1) : Integer.valueOf(srcCount.intValue() + 1)); - Integer trgCount = linkCounts.get(tidwn); - linkCounts.put(tidwn, (trgCount == null) ? Integer.valueOf(1) : Integer.valueOf(trgCount.intValue() + 1)); - } - - // - // Rank the nodes by link count: - // - - TreeMap> countRank = new TreeMap>(Collections.reverseOrder()); - Iterator lcit = linkCounts.keySet().iterator(); - while (lcit.hasNext()) { - NID.WithName src = lcit.next(); - Integer count = linkCounts.get(src); - SortedSet perCount = countRank.get(count); - if (perCount == null) { - perCount = new TreeSet(); - countRank.put(count, perCount); - } - perCount.add(src); - } - - // - // Handle the specified starting nodes case: - // - - if ((startNodes != null) && !startNodes.isEmpty()) { - ArrayList queue = new ArrayList(); - targsToGo.removeAll(startNodes); - targets.addAll(startNodes); - queue.addAll(startNodes); - flushQueue(targets, targsPerSource, linkCounts, targsToGo, queue); - } - - // - // Get all kids added in. Now doing this without recursion; seeing blown - // stacks for huge networks! - // - - while (!targsToGo.isEmpty()) { - Iterator crit = countRank.keySet().iterator(); - while (crit.hasNext()) { - Integer key = crit.next(); - SortedSet perCount = countRank.get(key); - Iterator pcit = perCount.iterator(); - while (pcit.hasNext()) { - NID.WithName node = pcit.next(); - if (targsToGo.contains(node)) { - ArrayList queue = new ArrayList(); - targsToGo.remove(node); - targets.add(node); - addMyKidsNR(targets, targsPerSource, linkCounts, targsToGo, node, queue); - } - } - } - } - - // - // - // Tag on lone nodes. If a node is by itself, but also shows up in the links, - // we drop it: - // - - HashSet remains = new HashSet(loneNodes); - remains.removeAll(targets); - targets.addAll(new TreeSet(remains)); - return (targets); - } - - /*************************************************************************** - ** - ** Node ordering - */ - - private List orderMyKids(Map> targsPerSource, - Map linkCounts, - Set targsToGo, NID.WithName node) { - Set targs = targsPerSource.get(node); - if (targs == null) { - return (new ArrayList()); - } - TreeMap> kidMap = new TreeMap>(Collections.reverseOrder()); - Iterator tait = targs.iterator(); - while (tait.hasNext()) { - NID.WithName nextTarg = tait.next(); - Integer count = linkCounts.get(nextTarg); - SortedSet perCount = kidMap.get(count); - if (perCount == null) { - perCount = new TreeSet(); - kidMap.put(count, perCount); - } - perCount.add(nextTarg); - } - - ArrayList myKidsToProc = new ArrayList(); - Iterator> kmit = kidMap.values().iterator(); - while (kmit.hasNext()) { - SortedSet perCount = kmit.next(); - Iterator pcit = perCount.iterator(); - while (pcit.hasNext()) { - NID.WithName kid = pcit.next(); - if (targsToGo.contains(kid)) { - myKidsToProc.add(kid); - } - } - } - return (myKidsToProc); - } - - /*************************************************************************** - ** - ** Node ordering, non-recursive: - */ - - private void addMyKidsNR(List targets, Map> targsPerSource, - Map linkCounts, - Set targsToGo, NID.WithName node, List queue) { - queue.add(node); - flushQueue(targets, targsPerSource, linkCounts, targsToGo, queue); - return; - } - - /*************************************************************************** - ** - ** Node ordering, non-recursive: - */ - - private void flushQueue(List targets, - Map> targsPerSource, - Map linkCounts, - Set targsToGo, List queue) { - while (!queue.isEmpty()) { - NID.WithName node = queue.remove(0); - List myKids = orderMyKids(targsPerSource, linkCounts, targsToGo, node); - Iterator ktpit = myKids.iterator(); - while (ktpit.hasNext()) { - NID.WithName kid = ktpit.next(); - if (targsToGo.contains(kid)) { - targsToGo.remove(kid); - targets.add(kid); - queue.add(kid); - } - } - } - return; - } - - /*************************************************************************** - ** - ** For passing around layout params - */ - - public static class Params implements NodeSimilarityLayout.CRParams { - - public List startNodes; - - public Params(List startNodes) { - this.startNodes = startNodes; - } - } -} diff --git a/src/org/systemsbiology/biofabric/layouts/ElementRatios.java b/src/org/systemsbiology/biofabric/layouts/ElementRatios.java deleted file mode 100644 index f5fa02e..0000000 --- a/src/org/systemsbiology/biofabric/layouts/ElementRatios.java +++ /dev/null @@ -1,190 +0,0 @@ -/* -** Copyright (C) 2003-2014 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/**************************************************************************** -** -** Do Element Ration Import -*/ - -public class ElementRatios { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public ElementRatios() { - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Do reading - */ - - public List readERT(File infile) throws IOException { - // - // Read in the lines. - // - ArrayList retval = new ArrayList(); - ArrayList rows = new ArrayList(); - ArrayList colNames = new ArrayList(); - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "ISO-8859-1")); - String line = null; - int count = 0; - while ((line = in.readLine()) != null) { - if (line.trim().equals("")) { - continue; - } - if (count == 0) { - String[] toks = line.split(" "); - colNames.addAll(Arrays.asList(toks)); - count++; - } else { - String[] toks = line.split(" "); - rows.add(toks); - } - } - } finally { - if (in != null) in.close(); - } - - Iterator roit = rows.iterator(); - double conv = 1.0 / Math.log10(2.0); - while (roit.hasNext()) { - String[] row = roit.next(); - String src = row[0]; - if (src.equals("R") || src.equals("E")) { - continue; - } - for (int i = 1; i < row.length; i++) { - if (colNames.get(i).equals("R") || colNames.get(i).equals("E")) { - continue; - } - Double doub = Double.parseDouble(row[i]); - if (doub == 0) { - continue; - } - double log2 = Math.log10(doub.doubleValue()) * conv; - int rndLog2 = (int)Math.round(log2); - int numLink = (rndLog2 <= 0) ? 1 : rndLog2; - for (int j = 0; j < numLink; j++) { - String[] link = new String[3]; - link[0] = src; - link[1] = (rndLog2 <= 0) ? Integer.toString(rndLog2) : Integer.toString(j + 1); - link[2] = colNames.get(i); - retval.add(link); - } - } - } - return (retval); - } - - - /*************************************************************************** - ** - ** Save nodes - */ - - public void dumpSIF(String outfile, List edges) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"))); - Iterator onit = edges.iterator(); - while (onit.hasNext()) { - String[] edge = onit.next(); - out.print(edge[0]); - out.print("\t"); - out.print(edge[1]); - out.print("\t"); - out.println(edge[2]); - } - out.close(); - return; - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC STATIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Test frame - */ - - public static void main(String[] argv) { - try { - ElementRatios cp = new ElementRatios(); - List edges = cp.readERT(new File("/Users/bill/XXX.txt")); - cp.dumpSIF("/Users/bill/XXX.sif", edges); - } catch (IOException ioex) { - System.err.println("IO Error " + ioex); - } - } -} diff --git a/src/org/systemsbiology/biofabric/layouts/GluOleNodeOrder.java b/src/org/systemsbiology/biofabric/layouts/GluOleNodeOrder.java deleted file mode 100644 index efa695c..0000000 --- a/src/org/systemsbiology/biofabric/layouts/GluOleNodeOrder.java +++ /dev/null @@ -1,344 +0,0 @@ -/* -** Copyright (C) 2003-2013 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -/**************************************************************************** -** -** Generate node order attribute files for the example combined Glucose/Oleate -** network discussed in the blog post at: -** -** http://biofabric.blogspot.com/2013/11/i-view-yeast-to-breadth-and-height.html -*/ - -public class GluOleNodeOrder { - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public GluOleNodeOrder() { - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Read in a SIF line and return a map of target node names to Bintags - */ - - public Map readSIF(String infile1) throws IOException { - - Map tags = new HashMap(); - String line; - BufferedReader in = new BufferedReader(new FileReader(infile1)); - while ((line = in.readLine()) != null) { - String[] tokens = line.split("\\t"); - if (tokens.length == 0) { - continue; - } else if ((tokens.length == 1) || (tokens.length == 2)) { - throw new IOException(); - } else { - String src = tokens[0].trim(); - String tag = tokens[1].trim(); - String trg = tokens[2].trim(); - Bintag btag = tags.get(trg); - if (btag == null) { - btag = new Bintag(src, tag); - tags.put(trg, btag); - } else { - btag.addRel(src, tag); - } - } - } - in.close(); - return (tags); - } - - /*************************************************************************** - ** - ** Invert the tag map to order the nodes - */ - - public SortedMap> invertTags(Map tagging) { - SortedMap> retval = new TreeMap>(Collections.reverseOrder()); - Iterator tkit = tagging.keySet().iterator(); - while (tkit.hasNext()) { - String trg = tkit.next(); - Bintag btag = tagging.get(trg); - SortedSet ss = retval.get(btag); - if (ss == null) { - ss = new TreeSet(); - retval.put(btag, ss); - } - ss.add(trg); - } - return (retval); - } - - /*************************************************************************** - ** - ** Flatten the sorted inverted map to a single list - */ - - public List flattenTags(SortedMap> mapped) { - List retval = new ArrayList(); - Iterator> tkit = mapped.values().iterator(); - while (tkit.hasNext()) { - SortedSet ss = tkit.next(); - retval.addAll(ss); - } - return (retval); - } - - /*************************************************************************** - ** - ** Save node order file - */ - - public void dumpNOA(String outfile, List ordering) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"))); - out.println("Node Row"); - out.println("O = 0"); - out.println("Y = 1"); - out.println("P = 2"); - out.println("A = 3"); - - int count = 4; - Iterator onit = ordering.iterator(); - while (onit.hasNext()) { - String nodeID = onit.next(); - out.print(nodeID); - out.print(" = "); - out.println(count++); - } - out.close(); - return; - } - - /*************************************************************************** - ** - ** Run a cycle - */ - - public void runCycle(String sifName, String noaBase, Bintag.Mode daMode) throws IOException { - Bintag.setMode(daMode); - Map btm = readSIF(sifName); - SortedMap> im = invertTags(btm); - List flat = flattenTags(im); - dumpNOA(noaBase + daMode + ".noa", flat); - return; - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC STATIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Run it - */ - - public static void main(String[] argv) { - try { - GluOleNodeOrder cp = new GluOleNodeOrder(); - String sifName = argv[0]; - String noaBase = argv[1]; - cp.runCycle(sifName, noaBase, Bintag.Mode.ODOMETER); - cp.runCycle(sifName, noaBase, Bintag.Mode.GLUCOSE_BASE); - cp.runCycle(sifName, noaBase, Bintag.Mode.OLEATE_BASE); - } catch (IOException ioex) { -// System.err.println("IO Error " + ioex); - } - } - -//////////////////////////////////////////////////////////////////////////// -// -// INNER CLASSES -// -//////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Sorting tags - */ - - - - public static class Bintag implements Comparable { - - public enum Mode {ODOMETER, GLUCOSE_BASE, OLEATE_BASE} - - public boolean inAo; - public boolean inOo; - public boolean inYo; - public boolean inPo; - public boolean inAg; - public boolean inOg; - public boolean inYg; - public boolean inPg; - private static Mode ourMode_; - - public static void setMode(Mode daMode) { - ourMode_ = daMode; - return; - } - - Bintag(String src, String rel) { - addRel(src, rel); - } - - public final void addRel(String src, String rel) { - if (src.equals("A")) { - if (rel.equals("pd-o")) { - inAo = true; - } else { - inAg = true; - } - } else if (src.equals("O")) { - if (rel.equals("pd-o")) { - inOo = true; - } else { - inOg = true; - } - } else if (src.equals("P")) { - if (rel.equals("pd-o")) { - inPo = true; - } else { - inPg = true; - } - } else if (src.equals("Y")) { - if (rel.equals("pd-o")) { - inYo = true; - } else { - inYg = true; - } - } - return; - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return (false); - } - if (other == this) { - return (true); - } - if (!(other instanceof Bintag)) { - return (false); - } - Bintag otherBT = (Bintag)other; - - if (this.inAo != otherBT.inAo) return false; - if (this.inOo != otherBT.inOo) return false; - if (this.inYo != otherBT.inYo) return false; - if (this.inPo != otherBT.inPo) return false; - if (this.inAg != otherBT.inAg) return false; - if (this.inOg != otherBT.inOg) return false; - if (this.inYg != otherBT.inYg) return false; - if (this.inPg != otherBT.inPg) return false; - - return (true); - } - - @Override - public int hashCode() { - int sum = 0; - switch (ourMode_) { - case ODOMETER: - // All O, then all Y, etc. - if (inAo) sum += 1; - if (inAg) sum += 2; - if (inPo) sum += 4; - if (inPg) sum += 8; - if (inYo) sum += 16; - if (inYg) sum += 32; - if (inOo) sum += 64; - if (inOg) sum += 128; - break; - case GLUCOSE_BASE: - // All Glu, Then Ola - if (inAo) sum += 1; - if (inAg) sum += 16; - if (inPo) sum += 2; - if (inPg) sum += 32; - if (inYo) sum += 4; - if (inYg) sum += 64; - if (inOo) sum += 8; - if (inOg) sum += 128; - break; - case OLEATE_BASE: - // All Ola, then GLu - if (inAo) sum += 16; - if (inAg) sum += 1; - if (inPo) sum += 32; - if (inPg) sum += 2; - if (inYo) sum += 64; - if (inYg) sum += 4; - if (inOo) sum += 128; - if (inOg) sum += 8; - break; - default: - throw new IllegalStateException(); - } - return (sum); - } - - public int compareTo(Bintag otherBT) { - return (this.hashCode() - otherBT.hashCode()); - } - - @Override - public String toString() { - return (Integer.toString(hashCode())); - } - } -} diff --git a/src/org/systemsbiology/biofabric/layouts/HierDAGLayout.java b/src/org/systemsbiology/biofabric/layouts/HierDAGLayout.java deleted file mode 100644 index 31234cd..0000000 --- a/src/org/systemsbiology/biofabric/layouts/HierDAGLayout.java +++ /dev/null @@ -1,384 +0,0 @@ -/* -** Copyright (C) 2003-2014 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.NID; - -/**************************************************************************** -** -** This is a hierarchical layout of a DAG -*/ - -public class HierDAGLayout { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - private Map> l2s_; - private Map inDegs_; - private Map outDegs_; - private ArrayList placeList_; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public HierDAGLayout() { - l2s_ = new HashMap>(); - inDegs_ = new HashMap(); - outDegs_ = new HashMap(); - placeList_ = new ArrayList(); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public void doLayout(BioFabricNetwork.RelayoutBuildData rbd) { - doNodeLayout(rbd); - (new DefaultEdgeLayout()).layoutEdges(rbd); - return; - } - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public List doNodeLayout(BioFabricNetwork.RelayoutBuildData rbd) { - - List targets = orderByNodeDegree(rbd); - - // - // Now have the ordered list of targets we are going to display. - // Build target->row maps and the inverse: - // - - (new DefaultLayout()).installNodeOrder(targets, rbd); - return (targets); - } - - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public List orderByNodeDegree(BioFabricNetwork.RelayoutBuildData rbd) { - - HashSet nodesToGo = new HashSet(rbd.allNodeIDs); - linksToSources(rbd.allNodeIDs, rbd.allLinks); - List placeList = extractRoots(); - addToPlaceList(placeList); - nodesToGo.removeAll(placeList); - - // - // Find the guys whose cites have already been placed and place them: - // - - while (!nodesToGo.isEmpty()) { - List nextBatch = findNextCandidates(); - addToPlaceList(nextBatch); - nodesToGo.removeAll(nextBatch); - } - - return (placeList_); - - } - - /*************************************************************************** - ** - ** Build the set of guys we are looking at and degrees - */ - - public Map> linksToSources(Set nodeList, Set linkList) { - - Iterator nit = nodeList.iterator(); - while (nit.hasNext()) { - NID.WithName node = nit.next(); - l2s_.put(node, new HashSet()); - inDegs_.put(node, Integer.valueOf(0)); - outDegs_.put(node, Integer.valueOf(0)); - } - - Iterator llit = linkList.iterator(); - while (llit.hasNext()) { - FabricLink link = llit.next(); - NID.WithName src = link.getSrcID(); - NID.WithName trg = link.getTrgID(); - Set toTarg = l2s_.get(src); - toTarg.add(trg); - Integer deg = outDegs_.get(src); - outDegs_.put(src, Integer.valueOf(deg.intValue() + 1)); - deg = inDegs_.get(trg); - inDegs_.put(trg, Integer.valueOf(deg.intValue() + 1)); - } - return (l2s_); - } - - /*************************************************************************** - ** - ** Add to list to place - */ - - public void addToPlaceList(List nextBatch) { - placeList_.addAll(nextBatch); - return; - } - - /*************************************************************************** - ** - ** Extract the root nodes in order from highest degree to low - */ - - public List extractRoots() { - - Map roots = new HashMap(); - - Iterator lit = l2s_.keySet().iterator(); - while (lit.hasNext()) { - NID.WithName node = lit.next(); - Set fn = l2s_.get(node); - if (fn.isEmpty()) { - roots.put(node, Integer.valueOf(0)); - } - } - - lit = l2s_.keySet().iterator(); - while (lit.hasNext()) { - NID.WithName node = lit.next(); - Set fn = l2s_.get(node); - Iterator sit = fn.iterator(); - while (sit.hasNext()) { - NID.WithName trg = sit.next(); - Integer rs = roots.get(trg); - if (rs != null) { - roots.put(trg, Integer.valueOf(rs.intValue() + 1)); - } - } - } - - ArrayList buildList = new ArrayList(); - - int count = 1; - while (buildList.size() < roots.size()) { - TreeSet alpha = new TreeSet(Collections.reverseOrder()); - alpha.addAll(roots.keySet()); - Iterator rit = alpha.iterator(); - while (rit.hasNext()) { - NID.WithName node = rit.next(); - Integer val = roots.get(node); - if (val.intValue() == count) { - buildList.add(node); - } - } - count++; - } - - Collections.reverse(buildList); - return (buildList); - } - - /*************************************************************************** - ** - ** Find the next guys to go: - */ - - public List findNextCandidates() { - - HashSet quickie = new HashSet(placeList_); - - TreeSet nextOut = new TreeSet(Collections.reverseOrder()); - - Iterator lit = l2s_.keySet().iterator(); - while (lit.hasNext()) { - NID.WithName node = lit.next(); - if (quickie.contains(node)) { - continue; - } - Set fn = l2s_.get(node); - boolean allThere = true; - Iterator sit = fn.iterator(); - while (sit.hasNext()) { - NID.WithName trg = sit.next(); - if (!quickie.contains(trg)) { - allThere = false; - break; - } - } - if (allThere) { - nextOut.add(new SourcedNode(node)); - } - } - - ArrayList retval = new ArrayList(); - Iterator noit = nextOut.iterator(); - while (noit.hasNext()) { - SourcedNode sn = noit.next(); - retval.add(sn.getNode()); - } - return (retval); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC STATIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /**************************************************************************** - ** - ** A Class - */ - - public class SourcedNode implements Comparable { - - private NID.WithName node_; - - - public SourcedNode(NID.WithName node) { - node_ = node; - } - - public NID.WithName getNode() { - return (node_); - } - - @Override - public int hashCode() { - return (node_.hashCode()); - } - - @Override - public String toString() { - return (" node = " + node_); - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof SourcedNode)) { - return (false); - } - SourcedNode otherDeg = (SourcedNode)other; - return ((this.node_ == null) ? (otherDeg.node_ == null) : this.node_.equals(otherDeg.node_)); - } - - public int compareTo(SourcedNode otherDeg) { - - // - // Same name, same node: - // - - if (this.node_.equals(otherDeg.node_)) { - return (0); - } - - Set mySet = l2s_.get(this.node_); - Set hisSet = l2s_.get(otherDeg.node_); - - TreeSet myOrder = new TreeSet(); - TreeSet hisOrder = new TreeSet(); - int numNode = placeList_.size(); - for (int i = 0; i < numNode; i++) { - NID.WithName node = placeList_.get(i); - if (mySet.contains(node)) { - myOrder.add(new Integer(i)); - } - if (hisSet.contains(node)) { - hisOrder.add(new Integer(i)); - } - } - - ArrayList myList = new ArrayList(myOrder); - ArrayList hisList = new ArrayList(hisOrder); - - - int mySize = myOrder.size(); - int hisSize = hisOrder.size(); - int min = Math.min(mySize, hisSize); - for (int i = 0; i < min; i++) { - int myVal = myList.get(i).intValue(); - int hisVal = hisList.get(i).intValue(); - int diff = hisVal - myVal; - if (diff != 0) { - return (diff); - } - } - - int diffSize = hisSize - mySize; - if (diffSize != 0) { - return (diffSize); - } - - int myIn = inDegs_.get(this.node_); - int hisIn = inDegs_.get(otherDeg.node_); - int diffIn = myIn - hisIn; - if (diffIn != 0) { - return (diffIn); - } - - if (this.node_ == null) { - return ((otherDeg.node_ == null) ? 0 : -1); - } - return (this.node_.compareTo(otherDeg.node_)); - } - } -} diff --git a/src/org/systemsbiology/biofabric/layouts/NodeClusterLayout.java b/src/org/systemsbiology/biofabric/layouts/NodeClusterLayout.java deleted file mode 100644 index 5ffa56e..0000000 --- a/src/org/systemsbiology/biofabric/layouts/NodeClusterLayout.java +++ /dev/null @@ -1,653 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.Vector; - -import org.systemsbiology.biofabric.analysis.GraphSearcher; -import org.systemsbiology.biofabric.io.AttributeLoader; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.AsynchExitRequestException; -import org.systemsbiology.biofabric.util.BTProgressMonitor; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.TrueObjChoiceContent; -import org.systemsbiology.biofabric.util.UiUtil; -import org.systemsbiology.biofabric.util.UniqueLabeller; - -/**************************************************************************** -** -** This does node clustering layout -*/ - -public class NodeClusterLayout { - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public NodeClusterLayout() { - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - */ - - public void orderByClusterAssignment(BioFabricNetwork.RelayoutBuildData rbd, - NodeSimilarityLayout.CRParams crParams, - BTProgressMonitor monitor, - double startFrac, double endFrac) throws AsynchExitRequestException { - - // - // Go through all the links. If a link source and target are both in the same cluster, we add the link to the cluster - // - - ClusterParams params = (ClusterParams)crParams; - - TreeMap perClust = new TreeMap(); - HashMap> interClust = new HashMap>(); - HashSet interNodesOnly = new HashSet(); - - HashMap fullNodeDegree = null; - if (params.cLay == ClusterParams.ClustLayout.BREADTH_CONN_FIRST) { - fullNodeDegree = new HashMap(); - } - - BioFabricNetwork.BuildMode intraLay = (params.cLay == ClusterParams.ClustLayout.SIMILAR) ? BioFabricNetwork.BuildMode.CLUSTERED_LAYOUT - : BioFabricNetwork.BuildMode.DEFAULT_LAYOUT; - - Iterator flit = rbd.allLinks.iterator(); - while (flit.hasNext()) { - FabricLink fl = flit.next(); - NID.WithName source = fl.getSrcID(); - NID.WithName target = fl.getTrgID(); - if (fullNodeDegree != null) { - Integer count = fullNodeDegree.get(source); - count = (count == null) ? Integer.valueOf(1) : Integer.valueOf(count.intValue() + 1); - fullNodeDegree.put(source, count); - count = fullNodeDegree.get(target); - count = (count == null) ? Integer.valueOf(1) : Integer.valueOf(count.intValue() + 1); - fullNodeDegree.put(target, count); - } - - String srcClust = params.getClusterForNode(source); - String trgClust = params.getClusterForNode(target); - if (srcClust.equals(trgClust)) { - BioFabricNetwork.RelayoutBuildData rbdpc = perClust.get(srcClust); - if (rbdpc == null) { - rbdpc = new BioFabricNetwork.RelayoutBuildData(new UniqueLabeller(), - new HashSet(), new HashSet(), - new HashMap(), rbd.colGen, intraLay); - rbdpc.allNodeIDs = new HashSet(); - perClust.put(srcClust, rbdpc); - } - rbdpc.allLinks.add(fl); - addClusterNode(rbdpc, source); - addClusterNode(rbdpc, target); - } else { - Tuple intup = new Tuple(srcClust, trgClust); // Tuples reordered so val1 < val2! - List icfl = interClust.get(intup); - if (icfl == null) { - icfl = new ArrayList(); - interClust.put(intup, icfl); - } - icfl.add(fl); - interNodesOnly.add(source); - interNodesOnly.add(target); - } - } - - // - // Need to deal with "clusters" of nodes that have no internal links! - // - - for (NID.WithName node : rbd.allNodeIDs) { - String clust = params.getClusterForNode(node); - BioFabricNetwork.RelayoutBuildData rbdpc = perClust.get(clust); - if (rbdpc == null) { - rbdpc = new BioFabricNetwork.RelayoutBuildData(new UniqueLabeller(), - new HashSet(), new HashSet(), - new HashMap(), rbd.colGen, intraLay); - rbdpc.allNodeIDs = new HashSet(); - perClust.put(clust, rbdpc); - } - addClusterNode(rbdpc, node); - } - - String startClust = (params.startNode != null) ? params.getClusterForNode(params.startNode) : null; - - List bfc; - switch (params.order) { - case BREADTH: - bfc = breadthFirstClustering(params, interClust.keySet(), startClust); - break; - case LINK_SIZE: - bfc = clusterSizeOrder(perClust, false, startClust); - break; - case NODE_SIZE: - bfc = clusterSizeOrder(perClust, true, startClust); - break; - case NAME: - bfc = new ArrayList(perClust.keySet()); - if (startClust != null) { - bfc.remove(startClust); - bfc.add(0, startClust); - } - break; - default: - throw new IllegalStateException(); - } - - Map> hubs = null; - if (params.cLay == ClusterParams.ClustLayout.BREADTH_CONN_FIRST) { - hubs = rankInterClustHubs(interClust, params, fullNodeDegree); - } - - ArrayList allTargets = new ArrayList(); - - Iterator pcit = bfc.iterator(); - while (pcit.hasNext()) { - String clustName = pcit.next(); - BioFabricNetwork.RelayoutBuildData pcrbd = perClust.get(clustName); - if (pcrbd == null) { - continue; - } - List targets; - if (intraLay == BioFabricNetwork.BuildMode.CLUSTERED_LAYOUT) { - NodeSimilarityLayout.CRParams crp = new NodeSimilarityLayout.ClusterParams(); - NodeSimilarityLayout nslLayout = new NodeSimilarityLayout(); - pcrbd.existingIDOrder = new ArrayList(pcrbd.allNodeIDs); - // FAIL - UiUtil.fixMePrintout("What am I trying to do here?"); - //targets = nslLayout.doClusteredLayoutOrder(pcrbd, crp, monitor, startFrac, endFrac); - targets = new ArrayList(); - } else { - DefaultLayout dl = new DefaultLayout(); - List starts = (hubs == null) ? null : hubs.get(clustName); - targets = dl.defaultNodeOrder(pcrbd.allLinks, pcrbd.loneNodeIDs, starts); - } - allTargets.addAll(targets); - } - interNodesOnly.removeAll(allTargets); - allTargets.addAll(interNodesOnly); - - (new DefaultLayout()).installNodeOrder(allTargets, rbd); - - (new DefaultEdgeLayout()).layoutEdges(rbd); - - if (params.iLink == ClusterParams.InterLink.BETWEEN) { - int origNum = rbd.linkOrder.size(); - TreeMap newOrder = new TreeMap(); - HashMap> holdEm = new HashMap>(); - Iterator ksit = rbd.linkOrder.values().iterator(); - int colCount = 0; - String currClust = null; - boolean drainTime = false; - boolean interClustLink = false; - while (ksit.hasNext()) { - FabricLink daLink = ksit.next(); - String srcClust = params.getClusterForNode(daLink.getSrcID()); - String trgClust = params.getClusterForNode(daLink.getTrgID()); - if (srcClust.equals(trgClust)) { - if ((currClust != null) && !currClust.equals(srcClust)) { - drainTime = true; - } - currClust = srcClust; - interClustLink = false; - } else { - interClustLink = true; - } - - if (drainTime) { - List toDrain = holdEm.get(currClust); - if (toDrain != null) { - for (FabricLink ihe : toDrain) { - newOrder.put(Integer.valueOf(colCount++), ihe); - } - } - holdEm.remove(currClust); - drainTime = false; - newOrder.put(Integer.valueOf(colCount++), daLink); - } else if (!interClustLink) { - currClust = srcClust; - newOrder.put(Integer.valueOf(colCount++), daLink); - } else { - String otherClust = srcClust.equals(currClust) ? trgClust : srcClust; - List toDefer = holdEm.get(otherClust); - if (toDefer == null) { - toDefer = new ArrayList(); - holdEm.put(otherClust, toDefer); - } - toDefer.add(daLink); - } - } - - UiUtil.fixMePrintout("Cluster drain order is not correct"); - for (String daClust : holdEm.keySet()) { - List toDrain = holdEm.get(daClust); - if (toDrain != null) { - for (FabricLink ihe : toDrain) { - newOrder.put(Integer.valueOf(colCount++), ihe); - } - } - } - if (newOrder.size() != origNum) { - throw new IllegalStateException(); - } - rbd.setLinkOrder(newOrder); - } - if (params.saveAssign) { - rbd.clustAssign = params.getClusterAssign(); - } - return; - } - - /*************************************************************************** - ** - ** Helper - */ - - private void addClusterNode(BioFabricNetwork.RelayoutBuildData rbd, NID.WithName nid) { - if (!rbd.allNodeIDs.contains(nid)) { - boolean ok = rbd.idGen.addExistingLabel(nid.getNID().getInternal()); - if (!ok) { - throw new IllegalStateException(); - } - rbd.allNodeIDs.add(nid); - } - return; - } - - /*************************************************************************** - ** - ** Count map maintenance - */ - - private void addToCount(Map> countMap, String clust, NID.WithName node) { - - Map perClust = countMap.get(clust); - if (perClust == null) { - perClust = new HashMap(); - countMap.put(clust, perClust); - } - Integer count = perClust.get(node); - count = (count == null) ? Integer.valueOf(1) : Integer.valueOf(count.intValue() + 1); - perClust.put(node, count); - return; - } - - - /*************************************************************************** - ** - ** The nodes that are responsible for inter-cluster links may be almost no-shows - ** in the intra-cluster link competition. Find those guys so we can put them first - ** in the pile. - */ - - private Map> rankInterClustHubs(Map> interLinks, - ClusterParams params, - Map fullNodeDegree) { - - // Map(ClusterID -> Map(NodeID, InterClustDegree)): - Map> preRetval = new HashMap>(); - for (Tuple tup : interLinks.keySet()) { - List forTup = interLinks.get(tup); - for (FabricLink link : forTup) { - // Tup order is NOT src, trg, but lo, hi: - addToCount(preRetval, params.getClusterForNode(link.getSrcID()), link.getSrcID()); - addToCount(preRetval, params.getClusterForNode(link.getTrgID()), link.getTrgID()); - } - } - - // Map(ClusterID -> List(NodeID)): - Map> retval = new HashMap>(); - for (String clust: preRetval.keySet()) { - Map degMap = preRetval.get(clust); - // Map(SortedInterClustDegree->Map(SortedFullNodeDegree, Set(SortedNodeName))): - TreeMap>> invert = - new TreeMap>>(Collections.reverseOrder()); - for (NID.WithName node : degMap.keySet()) { - Integer interClustDeg = degMap.get(node); - SortedMap> perInterDeg = invert.get(interClustDeg); - if (perInterDeg == null) { - perInterDeg = new TreeMap>(Collections.reverseOrder()); - invert.put(interClustDeg, perInterDeg); - } - Integer fnDeg = fullNodeDegree.get(node); - SortedSet perFullDeg = perInterDeg.get(fnDeg); - if (perFullDeg == null) { - perFullDeg = new TreeSet(); - perInterDeg.put(fnDeg, perFullDeg); - } - perFullDeg.add(node); - } - List flat = new ArrayList(); - for (SortedMap> perInterDeg : invert.values()) { - for (SortedSet perFull : perInterDeg.values()) { - flat.addAll(perFull); - } - } - retval.put(clust, flat); - } - return (retval); - } - - - /*************************************************************************** - ** - */ - - private List clusterSizeOrder(TreeMap perClust, - boolean nodeFirst, String startClust) { - - TreeMap>> preRet = - new TreeMap>>(Collections.reverseOrder()); - for (String clustName : perClust.keySet()) { - BioFabricNetwork.RelayoutBuildData rbdpc = perClust.get(clustName); - Integer size1 = Integer.valueOf((nodeFirst) ? rbdpc.allNodeIDs.size() : rbdpc.allLinks.size()); - SortedMap> forSize1 = preRet.get(size1); - if (forSize1 == null) { - forSize1 = new TreeMap>(Collections.reverseOrder()); - preRet.put(size1, forSize1); - } - Integer size2 = Integer.valueOf((nodeFirst) ? rbdpc.allLinks.size() : rbdpc.allNodeIDs.size()); - SortedSet forSize2 = forSize1.get(size2); - if (forSize2 == null) { - forSize2 = new TreeSet(); - forSize1.put(size2, forSize2); - } - forSize2.add(clustName); - } - - List flat = new ArrayList(); - for (SortedMap> perSize1 : preRet.values()) { - for (SortedSet perSize2 : perSize1.values()) { - flat.addAll(perSize2); - } - } - - if (startClust != null) { - flat.remove(startClust); - flat.add(0, startClust); - } - - return (flat); - } - - /*************************************************************************** - ** - */ - - private List breadthFirstClustering(ClusterParams params, Set iclinks, String startClust) { - - UniqueLabeller uLab = new UniqueLabeller(); - Map fakeNodes = new HashMap(); - - for (String clu : params.getClusters()) { - NID pnid = uLab.getNextOID(); - fakeNodes.put(clu, new NID.WithName(pnid, clu)); - } - - Set links = new HashSet(); - for (Tuple tup : iclinks) { - FabricLink pseudo = new FabricLink(fakeNodes.get(tup.getVal1()), fakeNodes.get(tup.getVal2()), "ic", Boolean.valueOf(false), Boolean.valueOf(false)); - links.add(pseudo); - pseudo = new FabricLink(fakeNodes.get(tup.getVal2()), fakeNodes.get(tup.getVal1()), "ic", Boolean.valueOf(false), Boolean.valueOf(false)); - links.add(pseudo); - } - - List useRoots = null; - if (startClust != null) { - useRoots = new ArrayList(); - useRoots.add(fakeNodes.get(startClust)); - } - GraphSearcher gs = new GraphSearcher(new HashSet(fakeNodes.values()), links); - List qes = gs.breadthSearch(useRoots); - ArrayList retval = new ArrayList(); - for (GraphSearcher.QueueEntry aqe : qes) { - retval.add(aqe.name.getName()); - } - return (retval); - } - - /*************************************************************************** - ** - ** For passing around layout params - */ - - public static class ClusterParams implements NodeSimilarityLayout.CRParams { - - public enum Source {STORED, FILE, PLUGIN}; - - public enum Order {NAME, NODE_SIZE, LINK_SIZE, BREADTH}; - - public enum InterLink {INLINE, BETWEEN}; - - public enum ClustLayout {BREADTH_CONN_FIRST, BREADTH, SIMILAR}; - - - public Source source; - public Order order; - public InterLink iLink; - public ClustLayout cLay; - public NID.WithName startNode; - public boolean saveAssign; - private Map nodeClusters_; - - public ClusterParams(Source source, Order order, InterLink iLink, ClustLayout cLay, String startNode, - Map nodeClusterAttributes, - Map nodes, boolean saveAssign) { - - if (nodeClusterAttributes != null) { - nodeClusters_ = new HashMap(); - for (AttributeLoader.AttributeKey key : nodeClusterAttributes.keySet()) { - NID.WithName nodeID = nodes.get(DataUtil.normKey(((AttributeLoader.StringKey)key).key)); - nodeClusters_.put(nodeID, nodeClusterAttributes.get(key)); - } - } - this.source = source; - this.order = order; - this.saveAssign = saveAssign; - } - - public ClusterParams(boolean stored) { - this.source = (stored) ? Source.STORED : Source.FILE; - this.order = Order.BREADTH; - this.iLink = InterLink.BETWEEN; - this.cLay = ClustLayout.BREADTH_CONN_FIRST; - this.startNode = null; - this.saveAssign = true; - } - - public boolean needsFile() { - return (source.equals(Source.FILE)); - } - - public void install(Map nodeClusterAttributes, Map nodes) { - if (nodeClusterAttributes != null) { - nodeClusters_ = new HashMap(); - for (AttributeLoader.AttributeKey key : nodeClusterAttributes.keySet()) { - NID.WithName nodeID = nodes.get(DataUtil.normKey(((AttributeLoader.StringKey)key).key)); - nodeClusters_.put(nodeID, nodeClusterAttributes.get(key)); - } - } - } - - public void assign(Map nodeClusterAssign) { - nodeClusters_ = nodeClusterAssign; - return; - } - - public String getClusterForNode(NID.WithName nodeID) { - return (nodeClusters_.get(nodeID)); - } - - public Map getClusterAssign() { - return (nodeClusters_); - } - - - public Collection getClusters() { - return (nodeClusters_.values()); - } - - public static Vector> getSourceChoices(boolean stored) { - ResourceManager rMan = ResourceManager.getManager(); - Vector> retval = new Vector>(); - if (stored) { - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.stored"), Source.STORED)); - } - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.file"), Source.FILE)); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.plugin"), Source.PLUGIN)); - return (retval); - } - - public static Vector> getILinkChoices() { - ResourceManager rMan = ResourceManager.getManager(); - Vector> retval = new Vector>(); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.between"), InterLink.BETWEEN)); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.inline"), InterLink.INLINE)); - return (retval); - } - - public static Vector> getClustLayoutChoices() { - ResourceManager rMan = ResourceManager.getManager(); - Vector> retval = new Vector>(); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.breadthConnFirst"), ClustLayout.BREADTH_CONN_FIRST)); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.breadth"), ClustLayout.BREADTH)); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.similar"), ClustLayout.SIMILAR)); - return (retval); - } - - public static Vector> getOrderChoices() { - ResourceManager rMan = ResourceManager.getManager(); - Vector> retval = new Vector>(); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.breadthOrder"), Order.BREADTH)); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.name"), Order.NAME)); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.nodeSize"), Order.NODE_SIZE)); - retval.add(new TrueObjChoiceContent(rMan.getString("nodeClusterParams.linkSize"), Order.LINK_SIZE)); - return (retval); - } - } - - /*************************************************************************** - ** - ** Class for representing a tuple - */ - - public static class Tuple implements Cloneable, Comparable { - - private String val1_; - private String val2_; - - public Tuple(String val1, String val2) { - if ((val1 == null) || (val2 == null)) { - throw new IllegalArgumentException(); - } - if (val1.compareTo(val2) < 0) { - val1_ = val1; - val2_ = val2; - } else { - val1_ = val2; - val2_ = val1; - } - } - - @Override - public Tuple clone() { - try { - Tuple newTup = (Tuple)super.clone(); - return (newTup); - } catch (CloneNotSupportedException ex) { - throw new IllegalStateException(); - } - } - - @Override - public int hashCode() { - return (val1_.hashCode() + val2_.hashCode()); - } - - public String getVal1() { - return (val1_); - } - - public String getVal2() { - return (val2_); - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return (false); - } - if (other == this) { - return (true); - } - if (!(other instanceof Tuple)) { - return (false); - } - Tuple otherT = (Tuple)other; - return ((this.val1_.equals(otherT.val1_)) && (this.val2_.equals(otherT.val2_))); - } - - @Override - public String toString() { - return ("Tuple: (" + val1_ + ", " + val2_ + ")"); - } - - public int compareTo(Tuple otherTup) { - int val1Diff = this.val1_.compareTo(otherTup.val1_); - if (val1Diff != 0) { - return (val1Diff); - } - return (this.val2_.compareTo(otherTup.val2_)); - } - } -} - diff --git a/src/org/systemsbiology/biofabric/layouts/ProcessWorldBankCSV.java b/src/org/systemsbiology/biofabric/layouts/ProcessWorldBankCSV.java deleted file mode 100644 index 039167b..0000000 --- a/src/org/systemsbiology/biofabric/layouts/ProcessWorldBankCSV.java +++ /dev/null @@ -1,277 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.NID; - -/**************************************************************************** -** -** This does the world bank layout -*/ - -public class ProcessWorldBankCSV { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public ProcessWorldBankCSV() { - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public void doLayout(BioFabricNetwork.RelayoutBuildData rbd) { - doNodeLayout(rbd); - (new DefaultEdgeLayout()).layoutEdges(rbd); - return; - } - - /*************************************************************************** - ** - ** Relayout the network! - */ - - public List doNodeLayout(BioFabricNetwork.RelayoutBuildData rbd) { - - List targets = calcNodeOrder(rbd.allLinks, rbd.loneNodeIDs); - - // - // Now have the ordered list of targets we are going to display. - // Build target->row maps and the inverse: - // - - (new DefaultLayout()).installNodeOrder(targets, rbd); - return (targets); - } - - /*************************************************************************** - ** - ** Bump count - */ - - public void bumpDaCount(Map countMap, NID.WithName dNode) { - Integer inc = countMap.get(dNode); - if (inc == null) { - countMap.put(dNode, Integer.valueOf(1)); - } else { - countMap.put(dNode, Integer.valueOf(inc.intValue() + 1)); - } - return; - } - - /*************************************************************************** - ** - ** Track neighbors - */ - - public void addANeighbor(Map> neighMap, NID.WithName daNode, NID.WithName daNeigh) { - SortedSet forNode = neighMap.get(daNode); - if (forNode == null) { - forNode = new TreeSet(); - neighMap.put(daNode, forNode); - } - forNode.add(daNeigh); - return; - } - - /*************************************************************************** - ** - ** Invert a map - */ - - public SortedMap> invertDaCount(Map countMap) { - TreeMap> retval = new TreeMap>(Collections.reverseOrder()); - Iterator cmit = countMap.keySet().iterator(); - while (cmit.hasNext()) { - NID.WithName daKey = cmit.next(); - Integer daCount = countMap.get(daKey); - SortedSet forCount = retval.get(daCount); - if (forCount == null) { - forCount = new TreeSet(); - retval.put(daCount, forCount); - } - forCount.add(daKey); - } - return (retval); - } - - /*************************************************************************** - ** - ** Flatten a map - */ - - public List flattenDaCount(SortedMap> invCountMap) { - ArrayList retval = new ArrayList(); - Iterator> icmit = invCountMap.values().iterator(); - while (icmit.hasNext()) { - retval.addAll(icmit.next()); - } - return (retval); - } - - /*************************************************************************** - ** - ** Calculate node order - */ - - public List calcNodeOrder(Set allLinks, Set loneNodes) { - - ArrayList targets = new ArrayList(); - HashMap node2Degree = new HashMap(); - HashMap> node2Neighbor = new HashMap>(); - HashSet allNodes = new HashSet(); - - Iterator alit = allLinks.iterator(); - while (alit.hasNext()) { - FabricLink nextLink = alit.next(); - NID.WithName source = nextLink.getSrcID(); - NID.WithName target = nextLink.getTrgID(); - - allNodes.add(source); - allNodes.add(target); - - bumpDaCount(node2Degree, source); - bumpDaCount(node2Degree, target); - - addANeighbor(node2Neighbor, source, target); - addANeighbor(node2Neighbor, target, source); - } - - SortedMap> degree2Nodes = invertDaCount(node2Degree); - - // - // For nodes that have one neighbor, collect those popular neighbors: - // - - HashMap> oneNeighbor = new HashMap>(); - Iterator nit = node2Neighbor.keySet().iterator(); - while (nit.hasNext()) { - NID.WithName node = nit.next(); - SortedSet nextDoor = node2Neighbor.get(node); - if (nextDoor.size() == 1) { - NID.WithName popular = nextDoor.first(); - Set popFriends = oneNeighbor.get(popular); - if (popFriends == null) { - popFriends = new HashSet(); - oneNeighbor.put(popular, popFriends); - } - popFriends.add(node); - } - } - - Iterator degit = degree2Nodes.keySet().iterator(); - while (degit.hasNext()) { - Integer deg = degit.next(); - SortedSet forDeg = degree2Nodes.get(deg); - Iterator fdit = forDeg.iterator(); - while (fdit.hasNext()) { - NID.WithName degNode = fdit.next(); - if (oneNeighbor.keySet().contains(degNode)) { - targets.add(degNode); - HashMap forDaPop = new HashMap(); - Set unpopFriends = oneNeighbor.get(degNode); - Iterator upfit = unpopFriends.iterator(); - while (upfit.hasNext()) { - NID.WithName unPop = upfit.next(); - Integer upd = node2Degree.get(unPop); - forDaPop.put(unPop, upd); - } - SortedMap> invFor = invertDaCount(forDaPop); - targets.addAll(flattenDaCount(invFor)); - } - } - } - - HashSet stillToPlace = new HashSet(allNodes); - stillToPlace.removeAll(targets); - - Iterator> icmit = degree2Nodes.values().iterator(); - while (icmit.hasNext()) { - SortedSet fdeg = icmit.next(); - Iterator fdit = fdeg.iterator(); - while (fdit.hasNext()) { - NID.WithName chkNode = fdit.next(); - if (stillToPlace.contains(chkNode)) { - targets.add(chkNode); - } - } - } - - // - // - // Tag on lone nodes. If a node is by itself, but also shows up in the links, - // we drop it: - // - - HashSet remains = new HashSet(loneNodes); - remains.removeAll(targets); - targets.addAll(new TreeSet(remains)); - return (targets); - } -} diff --git a/src/org/systemsbiology/biofabric/layouts/WordLinkComm.java b/src/org/systemsbiology/biofabric/layouts/WordLinkComm.java deleted file mode 100644 index 74792d1..0000000 --- a/src/org/systemsbiology/biofabric/layouts/WordLinkComm.java +++ /dev/null @@ -1,494 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.layouts; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; - -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.systemsbiology.biofabric.analysis.Link; -import org.systemsbiology.biofabric.io.AttributeLoader; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.MinMax; -import org.systemsbiology.biofabric.util.UiUtil; - -/**************************************************************************** -** -** Do BioFabric cluster layout -*/ - -public class WordLinkComm { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public WordLinkComm() { - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Do reading to records - */ - - public Set readEdgeTab(File infile) throws IOException { - // - // Read in the lines. - // - - BufferedReader in = null; - HashSet interact = new HashSet(); - - try { - in = new BufferedReader(new FileReader(infile)); - - String line = null; - while ((line = in.readLine()) != null) { - String[] tokens = line.split("\\t"); - if (tokens.length != 2) { - System.err.println("WARNING: Short Line: " + line); - continue; - } else { - Link link = new Link(tokens[0].toUpperCase(), tokens[1].toUpperCase()); - interact.add(link); - } - } - - } finally { - if (in != null) in.close(); - } - return (interact); - } - - /*************************************************************************** - ** - ** Do reading - */ - - public SortedMap readCSV(File infile, List allLinks, Map nodeOrder, SortedSet groupOrder, Set trueLinks) throws IOException { - - TreeMap retval = new TreeMap(); - ArrayList groups = new ArrayList(); - BufferedReader in = null; - int lineNum = 0; - try { - in = new BufferedReader(new FileReader(infile)); - String line = null; - while ((line = in.readLine()) != null) { - if (lineNum++ == 0) { - continue; - } - if (line.trim().equals("")) { - continue; - } - List tokens = processCSVLine(line); - if (tokens.isEmpty()) { - continue; - } - Integer comName = Integer.valueOf(((String)tokens.get(0)).trim()); - MinMax forGrp = (new MinMax()).init(); - groups.add(new GroupRange(comName, forGrp)); - HashSet links = (HashSet)retval.get(comName); - if (links == null) { - links = new HashSet(); - retval.put(comName, links); - } - String geneStr = ((String)tokens.get(1)).trim(); - String[] genes = geneStr.split(","); - for (int i = 0; i < genes.length - 1; i++) { - String gi = genes[i].replaceAll(" ", "_"); - for (int j = i + 1; j < genes.length; j++) { - String gj = genes[j].replaceAll(" ", "_"); - Link testLink = new Link(gi, gj); - Link testLinkR = new Link(gj, gi); - if ((trueLinks == null) || (trueLinks.contains(testLink) || trueLinks.contains(testLinkR))) { - UiUtil.fixMePrintout("Restore this"); - /* - FabricLink nfl = new FabricLink(gi, gj, comName.toString(), false); - if (!nodeOrder.isEmpty()) { - forGrp.update((Integer.parseInt((String)nodeOrder.get(gi)))); - forGrp.update((Integer.parseInt((String)nodeOrder.get(gj)))); - } - allLinks.add(nfl); - links.add(nfl); - FabricLink snfl = new FabricLink(gi, gj, comName.toString(), true); - links.add(snfl); - */ - } - } - } - } - } finally { - if (in != null) in.close(); - } - - groupOrder.addAll(groups); - - return (retval); - } - - /*************************************************************************** - ** - ** Process a csv line into tokens - */ - - private List processCSVLine(String line) { - // Pattern for CSV from "Mastering Regular Expressions 2nd Ed." by Friedl (O'Reilly) - Pattern pat = Pattern.compile( - "\\G(?:^|,) (?: \" ( (?> [^\"]*+ ) (?> \"\" [^\"]*+ )*+ ) \" | ( [^\",]*+ ) )", - Pattern.COMMENTS); - Pattern doubq = Pattern.compile("\"\""); - Matcher mainMatch = pat.matcher(""); - Matcher doubMatch = doubq.matcher(""); - - ArrayList argList = new ArrayList(); - argList.clear(); - mainMatch.reset(line); - while (mainMatch.find()) { - String group = mainMatch.group(2); - if (group != null) { - argList.add(group.trim()); - } else { - doubMatch.reset(mainMatch.group(1)); - argList.add(doubMatch.replaceAll("\"").trim()); - } - } - // - // Chop off trailing empty tokens: - // - ArrayList retval = new ArrayList(); - int alnum = argList.size(); - boolean chopping = true; - for (int i = alnum - 1; i >= 0; i--) { - String tok = (String)argList.get(i); - if (chopping) { - if (tok.trim().equals("")) { - continue; - } else { - chopping = false; - } - } - if (!chopping) { - retval.add(0, tok); - } - } - - return (retval); - } - - - /*************************************************************************** - ** - ** Save nodes - */ - - public void dumpEDA(String outfile, SortedMap ordering) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"))); - out.println("Link Column"); - Iterator onit = ordering.keySet().iterator(); - while (onit.hasNext()) { - Integer col = (Integer)onit.next(); - String edgeID = (String)ordering.get(col); - out.print(edgeID); - out.print(" = "); - out.println(col); - } - out.close(); - return; - } - - /*************************************************************************** - ** - ** Do reading - */ - - public Map readEdgeOrder(File file) throws IOException { - HashMap attributes = new HashMap(); - AttributeLoader.ReadStats stats = new AttributeLoader.ReadStats(); - AttributeLoader alod = new AttributeLoader(); - UiUtil.fixMePrintout("Restore this"); - //alod.readAttributes(file, false, attributes, stats); - return (attributes); - } - - /*************************************************************************** - ** - ** Do reading - */ - - public Map readNodeOrder(File file) throws IOException { - HashMap attributes = new HashMap(); - AttributeLoader.ReadStats stats = new AttributeLoader.ReadStats(); - AttributeLoader alod = new AttributeLoader(); - UiUtil.fixMePrintout("Restore this"); - // alod.readAttributes(file, true, attributes, stats); - return (attributes); - } - - /*************************************************************************** - ** - ** Save nodes - */ - - public void dumpNOA(String outfile, SortedMap ordering) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"))); - out.println("Node Row"); - int count = 0; - Iterator onit = ordering.keySet().iterator(); - while (onit.hasNext()) { - Integer row = (Integer)onit.next(); - String nodeID = (String)ordering.get(row); - out.print(nodeID); - out.print(" = "); - out.println(count++); - } - out.close(); - return; - } - - /*************************************************************************** - ** - ** Dump sif - */ - - public void dumpSIF(String outfile, List allLinks) throws IOException { - PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"))); - Iterator onit = allLinks.iterator(); - while (onit.hasNext()) { - FabricLink nfl = (FabricLink)onit.next(); - out.print(nfl.getSrcID()); - out.print("\t"); - out.print(nfl.getAugRelation().relation); - out.print("\t"); - out.println(nfl.getTrgID()); - } - out.close(); - return; - } - - - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC STATIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** HOWTO! - ** - ** 1) Build sif file from CSV (set forSIF = true!) - ** 2) Load into BioFabric - ** 3) Order nodes using similarity layout - ** 4) Export node order - ** 5) Export link order - ** 6) Run this again (set forSIF = false!) - ** 7) Run BioFabric edge-attribute layout - */ - - /*************************************************************************** - ** - ** Test frame - */ - - public static void main(String[] argv) { - try { - boolean forSIF = false; // set to true for first-time sif creation! - WordLinkComm cp = new WordLinkComm(); - ArrayList allLinks = new ArrayList(); - - Set trueLinks = cp.readEdgeTab(new File("/users/wlongaba/XXX/word.edgelist")); - - Map nodeOrder = (!forSIF) ? cp.readNodeOrder(new File("/users/wlongaba/XXX.noa")) - : new HashMap(); - - TreeSet forGroups = new TreeSet(new GroupRangeComparator()); - SortedMap linkAssign = cp.readCSV(new File("/users/wlongaba/XXX.csv"), allLinks, nodeOrder, forGroups, trueLinks); - cp.dumpSIF("/users/wlongaba/XXX.sif", allLinks); - - - if (!forSIF) { - Map origOrder = cp.readEdgeOrder(new File("/users/wlongaba/XXX.eda")); - - TreeMap reorder = new TreeMap(new GroupRangeComparator()); - Iterator grit = forGroups.iterator(); - while (grit.hasNext()) { - GroupRange gr = (GroupRange)grit.next(); - TreeMap perGrp = new TreeMap(); - reorder.put(gr, perGrp); - Set laPerGrp = (Set)linkAssign.get(gr.name); - Iterator pgit = laPerGrp.iterator(); - while (pgit.hasNext()) { - FabricLink nextLink = (FabricLink)pgit.next(); - String col = (String)origOrder.get(nextLink); - String rel = nextLink.getAugRelation().relation; - String pref = (nextLink.getAugRelation().isShadow) ? "shdw(" : "("; - String asText = nextLink.getSrcID() + " " + pref + rel + ") " + nextLink.getTrgID(); - Integer colI = Integer.valueOf(col); - perGrp.put(colI, asText); - } - } - - int count = 0; - TreeMap ordering = new TreeMap(); - Iterator rit = reorder.keySet().iterator(); - while (rit.hasNext()) { - GroupRange comm = (GroupRange)rit.next(); - TreeMap forComm = (TreeMap)reorder.get(comm); - Iterator fcit = forComm.values().iterator(); - while (fcit.hasNext()) { - String linkTxt = (String)fcit.next(); - ordering.put(new Integer(count++), linkTxt); - } - } - - cp.dumpEDA("/users/wlongaba/XXX-G.eda", ordering); - } - } catch (IOException ioex) { - System.err.println("IO Error " + ioex); - } - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC INNER CLASSES - // - //////////////////////////////////////////////////////////////////////////// - - - /*************************************************************************** - ** - ** Just compares the basics. Child class may be equal even though they - ** are different. - */ - - - public static class GroupRange { - public Integer name; - public MinMax range; - - public GroupRange(Integer name, MinMax range) { - this.name = name; - this.range = range; - } - - public int hashCode() { - return (name.hashCode() + range.hashCode()); - } - - public boolean equals(Object other) { - if (other == null) { - return (false); - } - if (other == this) { - return (true); - } - if (!(other instanceof GroupRange)) { - return (false); - } - GroupRange otherGR = (GroupRange)other; - - if (!this.name.equals(otherGR.name)) { - return (false); - } - return (this.range.equals(otherGR)); - } - } - - - /*************************************************************************** - ** - */ - - - public static class GroupRangeComparator implements Comparator { - - public int compare(Object first, Object second) { - GroupRange firstGR = (GroupRange)first; - GroupRange secondGR = (GroupRange)second; - - MinMax firstMM = firstGR.range; - MinMax secondMM = secondGR.range; - int fComp = firstMM.min - secondMM.min; - if (fComp != 0) { - return (fComp); - } - int xComp = firstMM.max - secondMM.max; - if (xComp != 0) { - return (xComp); - } - return (firstGR.name.compareTo(secondGR.name)); - } - } -} diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/BreadthFirstLayoutDialog.java b/src/org/systemsbiology/biofabric/ui/dialogs/BreadthFirstLayoutDialog.java deleted file mode 100644 index 364bcb2..0000000 --- a/src/org/systemsbiology/biofabric/ui/dialogs/BreadthFirstLayoutDialog.java +++ /dev/null @@ -1,180 +0,0 @@ -/* -** Copyright (C) 2003-2014 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.ui.dialogs; - -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.Set; - -import javax.swing.ButtonGroup; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JRadioButton; -import javax.swing.JTextField; - -import org.systemsbiology.biofabric.layouts.DefaultLayout; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.ui.dialogs.utils.BTStashResultsDialog; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.ResourceManager; - -/**************************************************************************** -** -** Dialog box for setting breadth-first layout params -*/ - -public class BreadthFirstLayoutDialog extends BTStashResultsDialog { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - private static final long serialVersionUID = 1L; - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - - private JRadioButton useDefault_; - private JRadioButton userSpec_; - private JTextField userName_; - private DefaultLayout.Params params_; - private JLabel nameLabel_; - private BioFabricNetwork bfn_; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public BreadthFirstLayoutDialog(JFrame parent, NID.WithName currSel, BioFabricNetwork bfn) { - super(parent, "breadthFirstLayout.title", new Dimension(600, 350), 2); - params_ = null; - bfn_ = bfn; - - String highest = rMan_.getString("bFirst.useHighest"); - useDefault_ = new JRadioButton(highest, (currSel == null)); - useDefault_.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - try { - userName_.setEnabled(userSpec_.isSelected()); - nameLabel_.setEnabled(userSpec_.isSelected()); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - addWidgetFullRow(useDefault_, false); - - String spec = rMan_.getString("bFirst.userSelect"); - userSpec_ = new JRadioButton(spec, (currSel != null)); - userSpec_.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - try { - userName_.setEnabled(userSpec_.isSelected()); - nameLabel_.setEnabled(userSpec_.isSelected()); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - addWidgetFullRow(userSpec_, false); - - ButtonGroup group = new ButtonGroup(); - group.add(useDefault_); - group.add(userSpec_); - - userName_ = new JTextField((currSel == null) ? "" : currSel.getName().trim()); - nameLabel_ = new JLabel(rMan_.getString("bFirst.selectName")); - userName_.setEnabled(userSpec_.isSelected()); - nameLabel_.setEnabled(userSpec_.isSelected()); - addLabeledWidget(nameLabel_, userName_, false, false); - - finishConstruction(); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Get results - */ - - public DefaultLayout.Params getParams() { - return (params_); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Stash our results for later interrogation. - ** - */ - - protected boolean stashForOK() { - - boolean useSelected = userSpec_.isSelected(); - - if (useSelected) { - String search = DataUtil.normKey(userName_.getText().trim()); - Set result = bfn_.nodeMatches(true, search); - if (result.size() != 1) { - ResourceManager rMan = ResourceManager.getManager(); - JOptionPane.showMessageDialog(parent_, - rMan.getString("bFirst.badNode"), - rMan.getString("bFirst.badNodeTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - ArrayList starts = new ArrayList(); - starts.add(result.iterator().next()); - params_ = new DefaultLayout.Params(starts); - } else { - params_ = new DefaultLayout.Params(null); - } - - return (true); - } -} diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/ClusterLayoutSetupDialog.java b/src/org/systemsbiology/biofabric/ui/dialogs/ClusterLayoutSetupDialog.java deleted file mode 100644 index 1b265ec..0000000 --- a/src/org/systemsbiology/biofabric/ui/dialogs/ClusterLayoutSetupDialog.java +++ /dev/null @@ -1,314 +0,0 @@ -/* -** Copyright (C) 2003-2016 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.ui.dialogs; - -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JTextField; - -import org.systemsbiology.biofabric.cmd.CommandSet; -import org.systemsbiology.biofabric.io.AttributeLoader; -import org.systemsbiology.biofabric.layouts.NodeClusterLayout; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.ui.dialogs.utils.BTStashResultsDialog; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.TrueObjChoiceContent; - -/**************************************************************************** -** -** Dialog box for cluster layout setup -*/ - -public class ClusterLayoutSetupDialog extends BTStashResultsDialog { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - private static final long serialVersionUID = 1L; - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - private JComboBox sourceCombo_; - private JComboBox orderCombo_; - private JComboBox interCombo_; - private JComboBox cLayoutCombo_; - private JCheckBox saveAssignBox_; - private NID.WithName currSel_; - private JLabel nameLabel_; - private JTextField userName_; - private BioFabricNetwork bfn_; - private NodeClusterLayout.ClusterParams results_; - private boolean haveClusts_; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public ClusterLayoutSetupDialog(JFrame parent, BioFabricNetwork bfn, NID.WithName selNode) { - super(parent, "nodeClusterLayout.title", new Dimension(600, 350), 2); - results_ = null; - bfn_ = bfn; - currSel_ = selNode; - haveClusts_ = bfn.nodeClustersAssigned(); - - sourceCombo_ = new JComboBox(NodeClusterLayout.ClusterParams.getSourceChoices(haveClusts_)); - orderCombo_ = new JComboBox(NodeClusterLayout.ClusterParams.getOrderChoices()); - interCombo_ = new JComboBox(NodeClusterLayout.ClusterParams.getILinkChoices()); - cLayoutCombo_ = new JComboBox(NodeClusterLayout.ClusterParams.getClustLayoutChoices()); - saveAssignBox_ = new JCheckBox(rMan_.getString("nodeClusterLayout.saveAssign")); - - NodeClusterLayout.ClusterParams params = new NodeClusterLayout.ClusterParams(haveClusts_); - setToVals(params); - - JLabel label = new JLabel(rMan_.getString("nodeClusterLayout.source")); - addLabeledWidget(label, sourceCombo_, false, false); - - addWidgetFullRow(saveAssignBox_, false); - - label = new JLabel(rMan_.getString("nodeClusterLayout.order")); - addLabeledWidget(label, orderCombo_, false, false); - - label = new JLabel(rMan_.getString("nodeClusterLayout.interLink")); - addLabeledWidget(label, interCombo_, false, false); - - label = new JLabel(rMan_.getString("nodeClusterLayout.clusterLayout")); - addLabeledWidget(label, cLayoutCombo_, false, false); - - // - // Build extra button: - // - - FixedJButton buttonR = new FixedJButton(rMan_.getString("dialogs.resetDefaults")); - buttonR.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - try { - NodeClusterLayout.ClusterParams params = new NodeClusterLayout.ClusterParams(haveClusts_); - setToVals(params); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - - userName_ = new JTextField((currSel_ == null) ? "" : currSel_.getName().trim()); - nameLabel_ = new JLabel("bFirst.selectName"); - // userName_.setEnabled(userSpec_.isSelected()); - // nameLabel_.setEnabled(userSpec_.isSelected()); - addLabeledWidget(nameLabel_, userName_, false, false); - - finishConstructionWithExtraLeftButton(buttonR); - - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Get results - */ - - public NodeClusterLayout.ClusterParams getParams() { - return (results_); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Stash our results for later interrogation. - ** - */ - - protected boolean stashForOK() { - - results_ = new NodeClusterLayout.ClusterParams(haveClusts_); - - TrueObjChoiceContent scc = - (TrueObjChoiceContent)sourceCombo_.getSelectedItem(); - results_.source = scc.val; - - TrueObjChoiceContent occ = - (TrueObjChoiceContent)orderCombo_.getSelectedItem(); - results_.order = occ.val; - - TrueObjChoiceContent icc = - (TrueObjChoiceContent)interCombo_.getSelectedItem(); - results_.iLink = icc.val; - - TrueObjChoiceContent ccc = - (TrueObjChoiceContent)cLayoutCombo_.getSelectedItem(); - results_.cLay = ccc.val; - - results_.saveAssign = saveAssignBox_.isSelected(); - - if (results_.source.equals(NodeClusterLayout.ClusterParams.Source.STORED)) { - results_.assign(bfn_.nodeClusterAssigment()); - } - - String selName = userName_.getText(); - if ((selName != null) && !selName.trim().equals("")) { - String cand = selName.trim(); - Map> nn2ids = bfn_.getNormNameToIDs(); - Map nn2id = BioFabricNetwork.reduceNameSetToOne(nn2ids); - NID.WithName nidCand = nn2id.get(DataUtil.normKey(cand)); - if (bfn_.getNodeDefinition(nidCand) == null) { - ResourceManager rMan = ResourceManager.getManager(); - JOptionPane.showMessageDialog(parent_, - rMan.getString("nodeClusterLayout.nodeDoesNotExist"), - rMan.getString("nodeClusterLayout.nodeDoesNotExistTitle"), - JOptionPane.ERROR_MESSAGE); - return (false); - } - results_.startNode = nidCand; - } else { - results_.startNode = null; - } - return (true); - } - - /*************************************************************************** - ** - ** Reset to default values - ** - */ - - private void setToVals(NodeClusterLayout.ClusterParams params) { - int numSrc = sourceCombo_.getItemCount(); - for (int i = 0; i < numSrc; i++) { - TrueObjChoiceContent cc = - (TrueObjChoiceContent)sourceCombo_.getItemAt(i); - if (cc.val == params.source) { - sourceCombo_.setSelectedIndex(i); - break; - } - } - - int numOrd = orderCombo_.getItemCount(); - for (int i = 0; i < numOrd; i++) { - TrueObjChoiceContent cc = - (TrueObjChoiceContent)orderCombo_.getItemAt(i); - if (cc.val == params.order) { - orderCombo_.setSelectedIndex(i); - break; - } - } - - int numInt = interCombo_.getItemCount(); - for (int i = 0; i < numInt; i++) { - TrueObjChoiceContent cc = - (TrueObjChoiceContent)interCombo_.getItemAt(i); - if (cc.val == params.iLink) { - orderCombo_.setSelectedIndex(i); - break; - } - } - - int numClay = cLayoutCombo_.getItemCount(); - for (int i = 0; i < numClay; i++) { - TrueObjChoiceContent cc = - (TrueObjChoiceContent)cLayoutCombo_.getItemAt(i); - if (cc.val == params.cLay) { - orderCombo_.setSelectedIndex(i); - break; - } - } - - saveAssignBox_.setSelected(params.saveAssign); - return; - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - - public static boolean askForFileInfo(NodeClusterLayout.ClusterParams params, CommandSet cset, BioFabricNetwork bfn) { - - File file = cset.getTheFile(".noa", ".na", "AttribDirectory", "filterName.noa"); - if (file == null) { - return (true); - } - Map nodeAttributes = cset.loadTheFile(file, null, true); - if (nodeAttributes == null) { - return (false); - } - // - // All existing targets must have a row, and all existing - // rows need a target assigned! - // - - HashSet asUpper = new HashSet(); - Iterator rttvit = bfn.getNodeSetIDs().iterator(); - while (rttvit.hasNext()) { - asUpper.add(new AttributeLoader.StringKey(rttvit.next().getName())); - } - if (!asUpper.equals(new HashSet(nodeAttributes.keySet()))) { - ResourceManager rMan = ResourceManager.getManager(); - JOptionPane.showMessageDialog(cset.getBFW(), rMan.getString("attribRead.badRowMessage"), - rMan.getString("attribRead.badRowSemanticsTitle"), - JOptionPane.WARNING_MESSAGE); - return (false); - } - Map> nn2ids = bfn.getNormNameToIDs(); - Map nn2id = BioFabricNetwork.reduceNameSetToOne(nn2ids); - params.install(nodeAttributes, nn2id); - return (true); - } -} diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/LinkGroupingSetupDialog.java b/src/org/systemsbiology/biofabric/ui/dialogs/LinkGroupingSetupDialog.java deleted file mode 100644 index 171945b..0000000 --- a/src/org/systemsbiology/biofabric/ui/dialogs/LinkGroupingSetupDialog.java +++ /dev/null @@ -1,359 +0,0 @@ -/* -** Copyright (C) 2003-2016 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.ui.dialogs; - -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; - -import org.systemsbiology.biofabric.cmd.CommandSet; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.ui.dialogs.utils.BTStashResultsDialog; -import org.systemsbiology.biofabric.ui.dialogs.utils.EditableTable; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; - -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/**************************************************************************** - * * - * * Dialog comboBox for specifying link groupings - */ - -public class LinkGroupingSetupDialog extends BTStashResultsDialog { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - private final int CHOICE_PER_NODE = 0; - private final int CHOICE_PER_NETWORK = 1; - - private List linkGroupResult_; - private EditableTable est_; - private JFrame parent_; - private Set allRelations_; - private JComboBox comboBox; - private BioFabricNetwork.LayoutMode chosenMode; - - private static final long serialVersionUID = 1L; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - * * - * * Constructor - */ - - public LinkGroupingSetupDialog(JFrame parent, List currentTags, Set allRelations, BioFabricNetwork bfn) { - super(parent, ResourceManager.getManager().getString("linkGroupEdit.title"), new Dimension(650, 450), 2); - parent_ = parent; - allRelations_ = allRelations; - - // bfn is only for pre-selecting the JComboBox to current LayoutMode - installJComboBox(bfn); - - FixedJButton fileButton = - new FixedJButton(rMan_.getString("linkGroupEdit.loadFromFile")); - - fileButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - try { - loadFromFile(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - - est_ = new EditableTable(new LinkGroupingTableModel(), parent_); - EditableTable.TableParams etp = new EditableTable.TableParams(); - etp.addAlwaysAtEnd = false; - etp.buttons = EditableTable.ALL_BUT_EDIT_BUTTONS; - etp.singleSelectOnly = true; - JPanel tablePan = est_.buildEditableTable(etp); - - addTable(tablePan, 4); - - List initRows = initTableRows((currentTags == null) ? new ArrayList() : currentTags); - - est_.getModel().extractValues(initRows); - setLocationRelativeTo(parent); - - finishConstructionWithExtraLeftButton(fileButton); - } - - /*************************************************************************** - * * Install JComboBox with existing mode pre-selected from BioFabric Network's - * * current layoutMode - */ - - private void installJComboBox(BioFabricNetwork bfn) { - JLabel boxLabel = new JLabel(rMan_.getString("linkGroupEdit.mode")); - - String[] choices = new String[2]; - choices[CHOICE_PER_NODE] = rMan_.getString("linkGroupEdit.orderPerNode"); - choices[CHOICE_PER_NETWORK] = rMan_.getString("linkGroupEdit.orderNetwork"); - - comboBox = new JComboBox(choices); - - BioFabricNetwork.LayoutMode mode = bfn.getLayoutMode(); - if (mode == BioFabricNetwork.LayoutMode.UNINITIALIZED_MODE || - mode == BioFabricNetwork.LayoutMode.PER_NODE_MODE) { - comboBox.setSelectedIndex(CHOICE_PER_NODE); - - } else if (mode == BioFabricNetwork.LayoutMode.PER_NETWORK_MODE) { - comboBox.setSelectedIndex(CHOICE_PER_NETWORK); - } - - addLabeledWidget(boxLabel, comboBox, true, true); - } - - /*************************************************************************** - * * - * * Return results - * * - */ - - public List getGroups() { - return (linkGroupResult_); - } - - /*************************************************************************** - * * - * * Return chosen mode of comboBox - * * - */ - - public BioFabricNetwork.LayoutMode getChosenMode() { - return chosenMode; - } - - /*************************************************************************** - * * - * * Stash our results for later interrogation. - */ - - @Override - protected boolean stashForOK() { - linkGroupResult_ = ((LinkGroupingTableModel) est_.getModel()).applyValues(); - if (linkGroupResult_ == null) { - return (false); - } - - int mode = comboBox.getSelectedIndex(); - - if (mode == CHOICE_PER_NODE) { - chosenMode = BioFabricNetwork.LayoutMode.PER_NODE_MODE; - } else if (mode == CHOICE_PER_NETWORK){ - chosenMode = BioFabricNetwork.LayoutMode.PER_NETWORK_MODE; - } else { - ExceptionHandler.getHandler() - .displayException(new IllegalArgumentException("Illegal Selected Index")); - } - return (true); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /** - * loads relation order from file and updates table with new order. - * error checking done when user presses "ok" - */ - - private void loadFromFile() { - CommandSet cmd = CommandSet.getCmds("mainWindow"); - File fileEda = cmd.getTheFile(".txt", null, "AttribDirectory", "filterName.txt"); - if (fileEda == null) { - return; - } - List groups = UiUtil.simpleFileRead(fileEda); - if (groups == null) { - return; - } - - List initRows = initTableRows(groups); - est_.updateTable(true, initRows); // update table - return; - } - - /*************************************************************************** - ** - ** Get the list of table rows - ** - */ - - private List initTableRows(List inTags) { - ArrayList retval = new ArrayList(); - EditableTable.TableModel ecdtm = est_.getModel(); - Iterator ceit = inTags.iterator(); - while (ceit.hasNext()) { - String tag = ceit.next(); - LinkGroupingTableModel.TableRow tr = ecdtm.constructARow(); - tr.groupTag = tag; - retval.add(tr); - } - return (retval); - } - - //////////////////////////////////////////////////////////////////////////// - // - // INNER CLASSES - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - * * - * * The table - */ - - class LinkGroupingTableModel extends EditableTable.TableModel { - - private final static int GROUP_TAG_ = 0; - private final static int NUM_COL_ = 1; - - private static final long serialVersionUID = 1L; - - LinkGroupingTableModel() { - super(NUM_COL_); - colNames_ = new String[]{"linkGroupEdit.suffix"}; - colClasses_ = new Class[]{String.class}; - } - - public class TableRow implements EditableTable.ATableRow { - public String groupTag; - - public TableRow() { - } - - public TableRow(String val) { - groupTag = val; - return; - } - - TableRow(int i) { - groupTag = (String)columns_.get(GROUP_TAG_).get(i); - } - - public void toCols() { - columns_.get(GROUP_TAG_).add(groupTag); - return; - } - } - - protected TableRow constructARow(int i) { - return (new TableRow(i)); - } - - public TableRow constructARow() { - return (new TableRow()); - } - - List applyValues() { - List vals = getValuesFromTable(); - - // - // Make sure the groups are OK. Names must be unique, non-blank, present as suffixes in the - // provided set of link relations, and they must cover the set. - // - - ResourceManager rMan = ResourceManager.getManager(); - ArrayList seenTags = new ArrayList(); - int size = vals.size(); - if (size == 0) { - return (seenTags); - } - - for (int i = 0; i < size; i++) { - String tag = vals.get(i).groupTag; - if ((tag == null) || (tag.trim().equals(""))) { - JOptionPane.showMessageDialog(parent_, rMan.getString("rsedit.badRegion"), - rMan.getString("rsedit.badRegionTitle"), - JOptionPane.ERROR_MESSAGE); - return (null); - } - - tag = tag.trim(); - - if (DataUtil.containsKey(seenTags, tag)) { - JOptionPane.showMessageDialog(parent_, rMan.getString("rsedit.dupRegion"), - rMan.getString("rsedit.badRegionTitle"), - JOptionPane.ERROR_MESSAGE); - - return (null); - } - - seenTags.add(tag); - } - - - boolean fail = false; - int numST = seenTags.size(); - Iterator arit = allRelations_.iterator(); - while (arit.hasNext()) { - FabricLink.AugRelation relation =arit.next(); - boolean gotIt = false; - for (int i = 0; i < numST; i++) { - if (relation.relation.indexOf(seenTags.get(i)) != - 1) { - gotIt = true; - break; - } - } - if (! gotIt) { - fail = true; - break; - } - } - - if (fail) { - JOptionPane.showMessageDialog(parent_, rMan.getString("rsedit.notCovering"), - rMan.getString("rsedit.badCoverageTitle"), - JOptionPane.ERROR_MESSAGE); - - return (null); - } - return (seenTags); - } - } - -} diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/NetworkAlignmentDialog.java b/src/org/systemsbiology/biofabric/ui/dialogs/NetworkAlignmentDialog.java deleted file mode 100644 index 79ead81..0000000 --- a/src/org/systemsbiology/biofabric/ui/dialogs/NetworkAlignmentDialog.java +++ /dev/null @@ -1,484 +0,0 @@ -/* -** Copyright (C) 2003-2014 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.ui.dialogs; - -import org.systemsbiology.biofabric.cmd.CommandSet; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.border.EmptyBorder; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; - -import static org.systemsbiology.biofabric.analysis.NetworkAlignment.*; - -public class NetworkAlignmentDialog extends JDialog { - - private final int GRAPH_ONE_FILE = 1; - private final int GRAPH_TWO_FILE = 2; - private final int ALIGNMENT_FILE = 3; - - private JFrame parent_; - - private GraphNA graph1_, graph2_; - private AlignmentNA alignment_; - - public NetworkAlignmentDialog(final JFrame parent) { - super(parent, ResourceManager.getManager().getString("networkAlignment.title"), true); - this.parent_ = parent; - - ResourceManager rMan = ResourceManager.getManager(); - setSize(450, 400); - JPanel cp = (JPanel) getContentPane(); - cp.setBorder(new EmptyBorder(20, 20, 20, 20)); - cp.setLayout(new GridBagLayout()); - GridBagConstraints gbc = new GridBagConstraints(); - - JButton graph1Button = new JButton(rMan.getString("networkAlignment.graph1")); - JButton graph2Button = new JButton(rMan.getString("networkAlignment.graph2")); - JButton alignmentButton = new JButton(rMan.getString("networkAlignment.alignment")); - - graph1Button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - try { - loadFromFile(GRAPH_ONE_FILE); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - - graph2Button.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - try { - loadFromFile(GRAPH_TWO_FILE); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - - alignmentButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - try { - loadFromFile(ALIGNMENT_FILE); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - - Box funcButtonBox = Box.createVerticalBox(); - funcButtonBox.add(Box.createVerticalGlue()); - funcButtonBox.add(graph1Button); - funcButtonBox.add(Box.createVerticalStrut(10)); - funcButtonBox.add(graph2Button); - funcButtonBox.add(Box.createVerticalStrut(10)); - funcButtonBox.add(alignmentButton); - - UiUtil.gbcSet(gbc, 0, 0, 5, 1, UiUtil.HOR, 0, 0, 5, 5, 5, 5, UiUtil.SE, 1.0, 0.0); - cp.add(funcButtonBox, gbc); - - FixedJButton buttonO = new FixedJButton(rMan.getString("networkAlignment.ok")); - buttonO.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - try { - if (filesAreExtracted()) { - NetworkAlignmentDialog.this.setVisible(false); - NetworkAlignmentDialog.this.dispose(); - } else { - JOptionPane.showMessageDialog(parent_, "Invalid"); - } - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - - FixedJButton buttonC = new FixedJButton(rMan.getString("networkAlignment.cancel")); - buttonC.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ev) { - try { - NetworkAlignmentDialog.this.setVisible(false); - NetworkAlignmentDialog.this.dispose(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }); - - Box optButtonBox = Box.createHorizontalBox(); - optButtonBox.add(buttonO); - optButtonBox.add(Box.createHorizontalStrut(10)); - optButtonBox.add(buttonC); - - UiUtil.gbcSet(gbc, 0, 1, 5, 1, UiUtil.HOR, 0, 0, 5, 5, 5, 5, UiUtil.SE, 1.0, 0.0); - cp.add(optButtonBox, gbc); - - setLocationRelativeTo(parent); - } - - /** - * - */ - - private boolean filesAreExtracted() { - return (graph1_ != null) && (graph2_ != null) && (alignment_ != null); - } - - /** - * - */ - - public NetworkAlignInfo getNAInfo() { - if (graph1_ == null || graph2_ == null || alignment_ == null) { - throw new IllegalArgumentException(); - } - return new NetworkAlignInfo(graph1_, graph2_, alignment_); - } - - /** - * * Loads the file - */ - - private void loadFromFile(int mode) { - CommandSet cmd = CommandSet.getCmds("mainWindow"); - - File file; - - switch (mode) { - case GRAPH_ONE_FILE: - file = cmd.getTheFile(".gw", null, "AttribDirectory", "filterName.gw"); - break; - case GRAPH_TWO_FILE: - file = cmd.getTheFile(".gw", null, "AttribDirectory", "filterName.gw"); - break; - case ALIGNMENT_FILE: - file = cmd.getTheFile(".align", null, "AttribDirectory", "filterName.align"); - break; - default: - throw new IllegalArgumentException(); - } - - if (file == null) { - return; - } - - if (! check(file)) { - - } - - switch (mode) { - case GRAPH_ONE_FILE: - graph1_ = GraphNA.readGraphGWFile(file); - break; - case GRAPH_TWO_FILE: - graph2_ = GraphNA.readGraphGWFile(file); - break; - case ALIGNMENT_FILE: - alignment_ = AlignmentNA.readAlignFile(file); - break; - default: - throw new IllegalArgumentException(); - } - - return; - } - - private boolean check(File file) { // TO CHECK FILE - return true; - } - -} - - -///* -//** Copyright (C) 2003-2014 Institute for Systems Biology -//** Seattle, Washington, USA. -//** -//** This library is free software; you can redistribute it and/or -//** modify it under the terms of the GNU Lesser General Public -//** License as published by the Free Software Foundation; either -//** version 2.1 of the License, or (at your option) any later version. -//** -//** This library is distributed in the hope that it will be useful, -//** but WITHOUT ANY WARRANTY; without even the implied warranty of -//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -//** Lesser General Public License for more details. -//** -//** You should have received a copy of the GNU Lesser General Public -//** License along with this library; if not, write to the Free Software -//** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//*/ -// -//package org.systemsbiology.biofabric.ui.dialogs; -// -// import org.systemsbiology.biofabric.analysis.NetworkAlignment; -// import org.systemsbiology.biofabric.cmd.CommandSet; -// import org.systemsbiology.biofabric.util.ExceptionHandler; -// import org.systemsbiology.biofabric.util.FixedJButton; -// import org.systemsbiology.biofabric.util.ResourceManager; -// import org.systemsbiology.biofabric.util.UiUtil; -// -// import javax.swing.*; -// import javax.swing.border.EmptyBorder; -// import java.awt.*; -// import java.awt.event.ActionEvent; -// import java.awt.event.ActionListener; -// import java.io.File; -// -// import static org.systemsbiology.biofabric.analysis.NetworkAlignment.GraphNA; -// import static org.systemsbiology.biofabric.analysis.NetworkAlignment.AlignmentNA; -// import static org.systemsbiology.biofabric.analysis.NetworkAlignment.NetworkAlignInfo; -// -//public class NetworkAlignmentDialog extends JDialog { -// -// private final int GRAPH_ONE_FILE = 1; -// private final int GRAPH_TWO_FILE = 2; -// private final int ALIGNMENT_FILE = 3; -// -// private JFrame parent_; -// -// private GraphNA graph1_, graph2_; -// private AlignmentNA alignment_; -// -// public NetworkAlignmentDialog(final JFrame parent) { -// super(parent, ResourceManager.getManager().getString("networkAlignment.title"), true); -// this.parent_ = parent; -// -// ResourceManager rMan = ResourceManager.getManager(); -// setSize(450, 400); -// JPanel cp = (JPanel) getContentPane(); -// cp.setBorder(new EmptyBorder(20, 20, 20, 20)); -// cp.setLayout(new GridBagLayout()); -// GridBagConstraints gbc = new GridBagConstraints(); -// -//// JLabel graph_1 = new JLabel(rMan.getString("networkAlignment.graph1")); -//// JLabel graph_2 = new JLabel(rMan.getString("networkAlignment.graph2")); -//// JLabel alignment = new JLabel(rMan.getString("networkAlignment.alignment")); -// -// JButton graph1Button = new JButton(rMan.getString("networkAlignment.graph1")); -// JButton graph2Button = new JButton(rMan.getString("networkAlignment.graph2")); -// JButton alignmentButton = new JButton(rMan.getString("networkAlignment.alignment")); -// -// graph1Button.addActionListener(new ActionListener() { -// public void actionPerformed(ActionEvent e) { -// try { -// loadFromFile(GRAPH_ONE_FILE); -// } catch (Exception ex) { -// ExceptionHandler.getHandler().displayException(ex); -// } -// } -// }); -// -// graph2Button.addActionListener(new ActionListener() { -// public void actionPerformed(ActionEvent e) { -// try { -// loadFromFile(GRAPH_TWO_FILE); -// } catch (Exception ex) { -// ExceptionHandler.getHandler().displayException(ex); -// } -// } -// }); -// -// alignmentButton.addActionListener(new ActionListener() { -// public void actionPerformed(ActionEvent e) { -// try { -// loadFromFile(ALIGNMENT_FILE); -// } catch (Exception ex) { -// ExceptionHandler.getHandler().displayException(ex); -// } -// } -// }); -// -// Box funcButtonBox = Box.createVerticalBox(); -// funcButtonBox.add(Box.createVerticalGlue()); -// funcButtonBox.add(graph1Button); -// funcButtonBox.add(Box.createVerticalStrut(10)); -// funcButtonBox.add(graph2Button); -// funcButtonBox.add(Box.createVerticalStrut(10)); -// funcButtonBox.add(alignmentButton); -// -// UiUtil.gbcSet(gbc, 0, 0, 5, 1, UiUtil.HOR, 0, 0, 5, 5, 5, 5, UiUtil.SE, 1.0, 0.0); -// cp.add(funcButtonBox, gbc); -// -// FixedJButton buttonO = new FixedJButton(rMan.getString("networkAlignment.ok")); -// buttonO.addActionListener(new ActionListener() { -// public void actionPerformed(ActionEvent ev) { -// try { -// if (filesAreExtracted()) { -// NetworkAlignmentDialog.this.setVisible(false); -// NetworkAlignmentDialog.this.dispose(); -// } else { -// JOptionPane.showMessageDialog(parent_, "Invalid"); -// } -// } catch (Exception ex) { -// ExceptionHandler.getHandler().displayException(ex); -// } -// } -// }); -// -// FixedJButton buttonC = new FixedJButton(rMan.getString("networkAlignment.cancel")); -// buttonC.addActionListener(new ActionListener() { -// public void actionPerformed(ActionEvent ev) { -// try { -// NetworkAlignmentDialog.this.setVisible(false); -// NetworkAlignmentDialog.this.dispose(); -// } catch (Exception ex) { -// ExceptionHandler.getHandler().displayException(ex); -// } -// } -// }); -// -// Box optButtonBox = Box.createHorizontalBox(); -// optButtonBox.add(buttonO); -// optButtonBox.add(Box.createHorizontalStrut(10)); -// optButtonBox.add(buttonC); -// -// UiUtil.gbcSet(gbc, 0, 1, 5, 1, UiUtil.HOR, 0, 0, 5, 5, 5, 5, UiUtil.SE, 1.0, 0.0); -// cp.add(optButtonBox, gbc); -// -// -// setLocationRelativeTo(parent); -// } -// -// /** -// * -// */ -// -// private boolean filesAreExtracted() { -// return (graph1_ != null) && (graph2_ != null) && (alignment_ != null); -// } -// -// /** -// * -// */ -// -// public NetworkAlignInfo getNAInfo() { -// return new NetworkAlignInfo(graph1_, graph2_, alignment_); -// } -// -//// /** -//// * -//// */ -//// -//// public File getGraph1() { -//// return graph1_; -//// } -//// -//// public File getGraph2() { -//// return graph2_; -//// } -//// -//// public File getAlignment() { -//// return alignment_; -//// } -// -// /** -// * * Loads the file -// */ -// -// private void loadFromFile(int mode) { -// CommandSet cmd = CommandSet.getCmds("mainWindow"); -// -// File file; -// -// switch (mode) { -// case GRAPH_ONE_FILE: -// file = cmd.getTheFile(".gw", null, "AttribDirectory", "filterName.gw"); -// break; -// case GRAPH_TWO_FILE: -// file = cmd.getTheFile(".gw", null, "AttribDirectory", "filterName.gw"); -// case ALIGNMENT_FILE: -// file = cmd.getTheFile(".align", null, "AttribDirectory", "filterName.align"); -// break; -// default: -// throw new IllegalArgumentException(); -// } -// -// if (file == null) { -// return; -// } -// -// if (!check(file)) { -// -// } -// -// switch (mode) { -// case GRAPH_ONE_FILE: -// graph1_ = new GraphNA(file); -// break; -// case GRAPH_TWO_FILE: -// graph2_ = new GraphNA(file); -// case ALIGNMENT_FILE: -// alignment_ = new AlignmentNA(file); -// break; -// default: -// throw new IllegalArgumentException(); -// } -// -// return; -// } -// -// private boolean check(File file) { // TO CHECK FILE -// return true; -// } -// -//// /** -//// * Loads the .gw graph (2) file -//// */ -//// -//// private void loadGraphTwoFile() { -//// CommandSet cmd = CommandSet.getCmds("mainWindow"); -//// File fileEda = cmd.getTheFile(".gw", null, "AttribDirectory", "filterName.gw"); -////// if (fileEda == null) { // NEED TO FIX THIS -////// return; -////// } -//// -//// graph2_ = fileEda; -//// } -//// -//// /** -//// * Loads the .align alignment file -//// */ -//// -//// private void loadAlignmentFile() { -//// CommandSet cmd = CommandSet.getCmds("mainWindow"); -//// File fileEda = cmd.getTheFile(".align", null, "AttribDirectory", "filterName.align"); -////// if (fileEda == null) { // NEED TO FIX THIS -////// return; -////// } -//// -//// alignment_ = fileEda; -//// } -// -//} - diff --git a/src/org/systemsbiology/biofabric/ui/display/BioFabricNavAndControl.java b/src/org/systemsbiology/biofabric/ui/display/BioFabricNavAndControl.java deleted file mode 100644 index 5480533..0000000 --- a/src/org/systemsbiology/biofabric/ui/display/BioFabricNavAndControl.java +++ /dev/null @@ -1,292 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.ui.display; - -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; - -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import javax.swing.JSplitPane; -import javax.swing.border.EmptyBorder; -import javax.swing.border.LineBorder; - -import org.systemsbiology.biofabric.cmd.CommandSet; -import org.systemsbiology.biofabric.util.ResourceManager; - - -/**************************************************************************** -** -** This is the BioFabric Control dashboard -*/ - -public class BioFabricNavAndControl extends JPanel { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - private FabricMagnifyingTool fmt_; - private BioFabricOverview bfo_; - private MouseOverView mvo_; - private FabricNavTool fnt_; - private FabricNavTool.LabeledFabricNavTool lfnt_; - private FabricLocation floc_; - private CardLayout clay_; - private boolean collapsed_; - private JPanel withControls_; - private JSplitPane spot_; - private double savedSplitFrac_; - private static final long serialVersionUID = 1L; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public BioFabricNavAndControl(boolean isMain, JFrame topWindow) { - - floc_ = new FabricLocation(); - - CommandSet fc = CommandSet.getCmds((isMain) ? "mainWindow" : "selectionWindow"); - fmt_ = new FabricMagnifyingTool(fc.getColorGenerator()); - fmt_.keyInstall((JPanel)topWindow.getContentPane()); - JPanel fmpan = new JPanel(); - fmpan.setLayout(new BorderLayout()); - fmpan.setBorder(new LineBorder(Color.black, 2)); - Font labelFont = new Font("SansSerif", Font.BOLD, 20); - JLabel magLab = new JLabel(ResourceManager.getManager().getString("biofabric.magnifier")); - magLab.setBorder(new EmptyBorder(0, 5, 0, 0)); - magLab.setOpaque(true); - magLab.setBackground(Color.white); - magLab.setFont(labelFont); - fmpan.add(magLab, BorderLayout.NORTH); - fmpan.add(fmt_, BorderLayout.CENTER); - - bfo_ = new BioFabricOverview(); - fmt_.setFabricOverview(bfo_); - - // This is a new feature that has no place to live, and no UI to install the needed data. - // It was used for showing brain region images corresponding to nodes in a demo. When the - // user runs the mouse over a node, it would show an image corresponding to a node. Over a link, - // the images corresponding to endpoints. One place to put this is to let the user choose whether - // to show the tour panel or the overview. It will need the user to provide the location of where - // to find the image files, plus the filename pieces before and after the node name. - // - mvo_ = new MouseOverView(); - mvo_.setIsAlive(false); - mvo_.setFileLocations("path", "filePrefix", "fileSuffix"); - - JPanel fopan = new JPanel(); - fopan.setLayout(new BorderLayout()); - fopan.setBorder(new LineBorder(Color.black, 2)); - JLabel overLab = new JLabel(ResourceManager.getManager().getString("biofabric.overview")); - overLab.setBorder(new EmptyBorder(0, 5, 0, 0)); - overLab.setOpaque(true); - overLab.setBackground(Color.white); - overLab.setFont(labelFont); - fopan.add(overLab, BorderLayout.NORTH); - fopan.add(bfo_, BorderLayout.CENTER); - - lfnt_ = new FabricNavTool.LabeledFabricNavTool(topWindow, labelFont); - fnt_ = lfnt_.getFabricNavTool(); - - spot_ = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, fopan, lfnt_); - - // See above comment about new mvo_ option. This is the code to directly replace the tour with the - // mouse overview. - // JPanel dmvo = new JPanel(); - // dmvo.setLayout(new GridLayout(1, 2)); - // dmvo.add(mvo_.getPanel(0)); - // dmvo.add(mvo_.getPanel(1)); - // spot_ = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, fopan, dmvo); - - spot_.setBorder(new EmptyBorder(0,0,0,0)); - spot_.setResizeWeight(1.0); - - JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, fmpan, spot_); - withControls_ = new JPanel(); - withControls_.setLayout(new BorderLayout()); - withControls_.add(floc_, BorderLayout.NORTH); - withControls_.add(sp, BorderLayout.CENTER); - - clay_ = new CardLayout(); - this.setLayout(clay_); - this.add(withControls_, "cntrl"); - this.add(new JPanel(), "blank"); - clay_.show(this, "cntrl"); - collapsed_ = false; - - return; - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Sizing - */ - - @Override - public Dimension getPreferredSize() { - if (collapsed_) { - return (new Dimension(0, 0)); - } else { - return (withControls_.getPreferredSize()); - } - } - - @Override - public Dimension getMinimumSize() { - if (collapsed_) { - return (new Dimension(0, 0)); - } else { - return (withControls_.getMinimumSize()); - } - } - - @Override - public Dimension getMaximumSize() { - if (collapsed_) { - return (new Dimension(0, 0)); - } else { - return (withControls_.getMaximumSize()); - } - } - - /*************************************************************************** - ** - ** Set bounds - */ - - @Override - public void setBounds(int x, int y, int width, int height) { - super.setBounds(x, y, width, height); - repaint(); - return; - } - - /*************************************************************************** - ** - ** Hide/show nav and controls - */ - - public boolean showTour(boolean show) { - if (show) { - spot_.setEnabled(true); - lfnt_.setToBlank(!show); - double need = (double)(spot_.getWidth() - lfnt_.getMinimumSize().width) / (double)spot_.getWidth(); - spot_.setDividerLocation(Math.min(savedSplitFrac_, need)); - if (lfnt_.getMinimumSize().height > this.getHeight()) { - return (true); - } - } else { - lfnt_.setToBlank(!show); - int lastLoc = spot_.getDividerLocation(); - savedSplitFrac_ = (double)lastLoc / (double)spot_.getWidth(); - spot_.setDividerLocation(1.0); - spot_.setEnabled(false); - } - return (false); - } - - /*************************************************************************** - ** - ** Get the FabricNavTool - */ - - public FabricNavTool getNavTool() { - return (fnt_); - } - - /*************************************************************************** - ** - ** Set to blank or populated - */ - - public void setToBlank(boolean val) { - clay_.show(this, (val) ? "blank" : "cntrl"); - collapsed_ = val; - return; - } - - /*************************************************************************** - ** - ** Get the FabricLocation - */ - - public FabricLocation getFabricLocation() { - return (floc_); - } - - /*************************************************************************** - ** - ** Get the Mouseover view: - */ - - public MouseOverView getMouseOverView() { - return (mvo_); - } - - /*************************************************************************** - ** - ** Get the FMT - */ - - public FabricMagnifyingTool getFMT() { - return (fmt_); - } - - /*************************************************************************** - ** - ** Get the Overview - */ - - public BioFabricOverview getOverview() { - return (bfo_); - } - - /*************************************************************************** - ** - ** Set the fabric panel - */ - - public void setFabricPanel(BioFabricPanel cp) { - fnt_.setFabricPanel(cp); - return; - } -} \ No newline at end of file diff --git a/src/org/systemsbiology/biofabric/ui/display/FabricNavTool.java b/src/org/systemsbiology/biofabric/ui/display/FabricNavTool.java deleted file mode 100644 index 5048be8..0000000 --- a/src/org/systemsbiology/biofabric/ui/display/FabricNavTool.java +++ /dev/null @@ -1,918 +0,0 @@ -/* -** Copyright (C) 2003-2014 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.ui.display; - -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GridLayout; -import java.awt.RenderingHints; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.font.FontRenderContext; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.text.MessageFormat; - -import javax.swing.Box; -import javax.swing.JCheckBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.border.EmptyBorder; -import javax.swing.border.LineBorder; - -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; - -/**************************************************************************** -** -** This is the navigator -*/ - -public class FabricNavTool extends JPanel { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - private static final int BIG_ = 0; - private static final int SMALL_ = 1; - private static final int NUM_PAN_ = 2; - - private BioFabricPanel bfp_; - private FixedJButton[] startAtCurrent_; - private FixedJButton[] chooseAStart_; - private InfoPanel[] infoPanel_; - private FixedJButton[] buttonUp_; - private FixedJButton[] buttonRight_; - private FixedJButton[] buttonFarRight_; - private FixedJButton[] buttonLeft_; - private FixedJButton[] buttonFarLeft_; - private FixedJButton[] buttonDown_; - private FixedJButton[] buttonZoom_; - private FixedJButton[] buttonLinkZone_; - private FixedJButton[] buttonClear_; - private JCheckBox[] selectedOnly_; - private BioFabricPanel.TourStatus currTstat_; - private boolean haveSelection_; - private boolean haveAModel_; - private boolean controlsEnabled_; - private JFrame topWindow_; - private boolean doSOReset_; - private int currPan_; - private CardLayout clay_; - private JPanel bigPan_; - private JPanel smallPan_; - private boolean neverSet_; - private static final long serialVersionUID = 1L; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public FabricNavTool(JFrame topWindow) { - - setBackground(Color.WHITE); - - buildButtons(); - controlsEnabled_ = true; - topWindow_ = topWindow; - doSOReset_ = false; - neverSet_ = true; - - clay_ = new CardLayout(); - setLayout(clay_); - currPan_ = BIG_; - haveAModel_ = false; - haveSelection_ = false; - smallPan_ = fillPanel(SMALL_); - add(smallPan_, "small"); - bigPan_ = fillPanel(BIG_); - add(bigPan_, "big"); - clay_.show(this, "big"); - clearTour(); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Sizing - */ - - @Override - public Dimension getPreferredSize() { - return (bigPan_.getPreferredSize()); - } - - @Override - public Dimension getMinimumSize() { - if (neverSet_) { - return (bigPan_.getMinimumSize()); - } - return (smallPan_.getMinimumSize()); - } - - @Override - public Dimension getMaximumSize() { - return (bigPan_.getMaximumSize()); - } - - /*************************************************************************** - ** - ** - */ - - @Override - public void setBounds(int x, int y, int width, int height) { - neverSet_ = false; - Dimension minBig = bigPan_.getMinimumSize(); - if ((currPan_ == BIG_) && ((minBig.height > height) || (minBig.width > width))) { - currPan_ = SMALL_; - clay_.show(this, "small"); - } else if ((currPan_ == SMALL_) && (minBig.height < height) && (minBig.width < width)) { - currPan_ = BIG_; - clay_.show(this, "big"); - } - super.setBounds(x, y, width, height); - repaint(); - return; - } - - /*************************************************************************** - ** - ** Reset the skip selections - */ - - public void resetSkipSelections() { - for (int i = 0; i < NUM_PAN_; i++) { - selectedOnly_[i].setSelected(false); - } - return; - } - - /*************************************************************************** - ** - ** Enable or disable the panel - */ - - public void enableControls(boolean enabled) { - controlsEnabled_ = enabled; - if (!enabled) { - disableControls(); - } else { - syncToState(); - } - return; - } - - /*************************************************************************** - ** - ** Let us know we have a model - */ - - public void haveAModel(boolean haveIt) { - haveAModel_ = haveIt; - for (int i = 0; i < NUM_PAN_; i++) { - chooseAStart_[i].setEnabled(controlsEnabled_ && haveAModel_); - infoPanel_[i].clear(); - } - - if (!haveAModel_) { - currTstat_ = null; - disableControls(); - } - repaint(); - return; - } - /*************************************************************************** - ** - ** Let us know we have a selection - */ - - public void haveASelection(boolean haveIt) { - for (int i = 0; i < NUM_PAN_; i++) { - startAtCurrent_[i].setEnabled(haveIt); - selectedOnly_[i].setEnabled(haveIt); - } - if (currTstat_ != null) { - currTstat_.currStopUnselected = bfp_.tourStopNowUnselected(); - } - haveSelection_ = haveIt; - repaint(); - return; - } - - /*************************************************************************** - ** - ** Enable/disable tour - */ - - private void clearTour() { - for (int i = 0; i < NUM_PAN_; i++) { - infoPanel_[i].clear(); - } - revalidate(); - disableControls(); - return; - } - - /*************************************************************************** - ** - ** Give valid answer to use selected only - */ - - private boolean calcSelectedOnly() { - return (selectedOnly_[currPan_].isEnabled() && selectedOnly_[currPan_].isSelected()); - } - - /*************************************************************************** - ** - ** Drawing routine - */ - - public void setFabricPanel(BioFabricPanel bfp) { - bfp_ = bfp; - return; - } - - /*************************************************************************** - ** - ** install Names - */ - - public void installNames(BioFabricPanel.TourStatus tstat) { - if (tstat == null) { - return; - } - currTstat_ = tstat.clone(); - syncToState(); - return; - } - - /*************************************************************************** - ** - ** Enable/disable tour - */ - - private void disableControls() { - for (int i = 0; i < NUM_PAN_; i++) { - buttonUp_[i].setEnabled(false); - buttonRight_[i].setEnabled(false); - buttonFarRight_[i].setEnabled(false); - buttonLeft_[i].setEnabled(false); - buttonFarLeft_[i].setEnabled(false); - buttonDown_[i].setEnabled(false); - buttonClear_[i].setEnabled(false); - buttonZoom_[i].setEnabled(false); - buttonLinkZone_[i].setEnabled(false); - infoPanel_[i].setEnabled(false); - selectedOnly_[i].setEnabled(false); - } - repaint(); - return; - } - - /*************************************************************************** - ** - ** Sync to state! - */ - - private void syncToState() { - for (int i = 0; i < NUM_PAN_; i++) { - chooseAStart_[i].setEnabled(haveAModel_); - } - if (currTstat_ == null) { - disableControls(); - return; - } - for (int i = 0; i < NUM_PAN_; i++) { - buttonZoom_[i].setEnabled(true); - buttonLinkZone_[i].setEnabled(true); - buttonClear_[i].setEnabled(true); - infoPanel_[i].setEnabled(true); - infoPanel_[i].installNames(currTstat_); - buttonUp_[i].setEnabled(currTstat_.upEnabled); - buttonRight_[i].setEnabled(currTstat_.rightEnabled); - buttonFarRight_[i].setEnabled(currTstat_.farRightEnabled); - buttonLeft_[i].setEnabled(currTstat_.leftEnabled); - buttonFarLeft_[i].setEnabled(currTstat_.farLeftEnabled); - buttonDown_[i].setEnabled(currTstat_.downEnabled); - selectedOnly_[i].setEnabled(haveSelection_); - startAtCurrent_[i].setEnabled(haveSelection_); - } - revalidate(); - repaint(); - return; - } - - - /*************************************************************************** - ** - ** Create pairs of buttons - */ - - private void buildButtons() { - infoPanel_ = new InfoPanel[NUM_PAN_]; - startAtCurrent_ = new FixedJButton[NUM_PAN_]; - chooseAStart_ = new FixedJButton[NUM_PAN_] ; - - buttonUp_ = new FixedJButton[NUM_PAN_]; - buttonRight_ = new FixedJButton[NUM_PAN_]; - buttonFarRight_ = new FixedJButton[NUM_PAN_]; - buttonLeft_ = new FixedJButton[NUM_PAN_]; - buttonFarLeft_ = new FixedJButton[NUM_PAN_]; - buttonDown_ = new FixedJButton[NUM_PAN_]; - buttonZoom_ = new FixedJButton[NUM_PAN_]; - buttonLinkZone_ = new FixedJButton[NUM_PAN_]; - buttonClear_ = new FixedJButton[NUM_PAN_]; - selectedOnly_ = new JCheckBox[NUM_PAN_]; - return; - } - - /*************************************************************************** - ** - ** Build correct buttons - */ - - private FixedJButton buildZeButton(int i, String label) { - if (i == SMALL_) { - return (FixedJButton.miniFactory(label, 12)); - } else { - return (new FixedJButton(label)); - } - } - - /*************************************************************************** - ** - ** Create a panel - */ - - private JPanel fillPanel(int i) { - - JPanel retval = new JPanel(); - retval.setBackground(Color.WHITE); - ResourceManager rMan = ResourceManager.getManager(); - retval.setLayout(new GridLayout(1,1)); - - String zeLabel = rMan.getString("navTool.startAtCurrent"); - startAtCurrent_[i] = buildZeButton(i, zeLabel); - startAtCurrent_[i].setToolTipText(zeLabel); - startAtCurrent_[i].addActionListener(new StartFromSel()); - startAtCurrent_[i].setEnabled(false); - - zeLabel = rMan.getString("navTool.chooseAStart"); - chooseAStart_[i] = buildZeButton(i, zeLabel); - chooseAStart_[i].setToolTipText(zeLabel); - chooseAStart_[i].addActionListener(new ChooseAStart()); - chooseAStart_[i].setEnabled(false); - - zeLabel = rMan.getString("navTool.up"); - buttonUp_[i] = buildZeButton(i, zeLabel); - buttonUp_[i].setToolTipText(zeLabel); - buttonUp_[i].addActionListener(new GoUp()); - - zeLabel = rMan.getString("navTool.right"); - buttonRight_[i] = buildZeButton(i, zeLabel); - buttonRight_[i].setToolTipText(zeLabel); - buttonRight_[i].addActionListener(new GoRight()); - - zeLabel = ">>"; - buttonFarRight_[i] = buildZeButton(i, ">>"); - buttonFarRight_[i].setToolTipText(zeLabel); - buttonFarRight_[i].addActionListener(new GoFarRight()); - - zeLabel = rMan.getString("navTool.left"); - buttonLeft_[i] = buildZeButton(i, zeLabel); - buttonLeft_[i].setToolTipText(zeLabel); - buttonLeft_[i].addActionListener(new GoLeft()); - - zeLabel = "<<"; - buttonFarLeft_[i] = buildZeButton(i, "<<"); - buttonFarLeft_[i].setToolTipText(zeLabel); - buttonFarLeft_[i].addActionListener(new GoFarLeft()); - - zeLabel = rMan.getString("navTool.down"); - buttonDown_[i] = buildZeButton(i, zeLabel); - buttonDown_[i].setToolTipText(zeLabel); - buttonDown_[i].addActionListener(new GoDown()); - - zeLabel = rMan.getString("navTool.clear"); - buttonClear_[i] = buildZeButton(i, zeLabel); - buttonClear_[i].setToolTipText(zeLabel); - buttonClear_[i].addActionListener(new ClearTour()); - - zeLabel = rMan.getString("navTool.zoom"); - buttonZoom_[i] = buildZeButton(i, zeLabel); - buttonZoom_[i].setToolTipText(zeLabel); - buttonZoom_[i].addActionListener(new Zoom()); - - zeLabel = rMan.getString("navTool.dropZone"); - buttonLinkZone_[i] = buildZeButton(i, zeLabel); - buttonLinkZone_[i].setToolTipText(zeLabel); - buttonLinkZone_[i].addActionListener(new ToDrain()); - - selectedOnly_[i] = new JCheckBox(rMan.getString("navTool.skip")); - selectedOnly_[i].setOpaque(true); - selectedOnly_[i].setBackground(Color.white); - selectedOnly_[i].addActionListener(new SelOnly()); - - selectedOnly_[i].setEnabled(false); - - Box cbuttonPanel = Box.createHorizontalBox(); - cbuttonPanel.add(Box.createHorizontalGlue()); - cbuttonPanel.add(startAtCurrent_[i]); - cbuttonPanel.add(Box.createHorizontalStrut(5)); - cbuttonPanel.add(chooseAStart_[i]); - cbuttonPanel.add(Box.createHorizontalGlue()); - - Box infoPanel = Box.createHorizontalBox(); - infoPanel.add(Box.createHorizontalStrut(5)); - infoPanel_[i] = new InfoPanel(); - infoPanel.add(infoPanel_[i]); - infoPanel.add(Box.createHorizontalStrut(5)); - - Box dbuttonPanel = Box.createHorizontalBox(); - dbuttonPanel.add(Box.createHorizontalGlue()); - dbuttonPanel.add(buttonUp_[i]); - dbuttonPanel.add(Box.createHorizontalGlue()); - - Box ebuttonPanel = Box.createHorizontalBox(); - ebuttonPanel.add(Box.createHorizontalGlue()); - ebuttonPanel.add(buttonFarLeft_[i]); - ebuttonPanel.add(Box.createHorizontalStrut(5)); - ebuttonPanel.add(buttonLeft_[i]); - ebuttonPanel.add(Box.createHorizontalStrut(5)); - ebuttonPanel.add(buttonRight_[i]); - ebuttonPanel.add(Box.createHorizontalStrut(5)); - ebuttonPanel.add(buttonFarRight_[i]); - ebuttonPanel.add(Box.createHorizontalGlue()); - - Box fbuttonPanel = Box.createHorizontalBox(); - fbuttonPanel.add(Box.createHorizontalGlue()); - fbuttonPanel.add(buttonDown_[i]); - fbuttonPanel.add(Box.createHorizontalGlue()); - - Box hbuttonPanel = Box.createHorizontalBox(); - hbuttonPanel.add(Box.createHorizontalGlue()); - hbuttonPanel.add(buttonClear_[i]); - hbuttonPanel.add(Box.createHorizontalStrut(5)); - hbuttonPanel.add(buttonZoom_[i]); - hbuttonPanel.add(Box.createHorizontalStrut(5)); - hbuttonPanel.add(buttonLinkZone_[i]); - hbuttonPanel.add(Box.createHorizontalGlue()); - - Box ibuttonPanel = Box.createHorizontalBox(); - ibuttonPanel.add(Box.createHorizontalGlue()); - ibuttonPanel.add(selectedOnly_[i]); - ibuttonPanel.add(Box.createHorizontalGlue()); - - Box gbuttonPanel = Box.createVerticalBox(); - gbuttonPanel.add(Box.createVerticalGlue()); - gbuttonPanel.add(cbuttonPanel); - // gbuttonPanel.add(Box.createVerticalStrut(1)); - gbuttonPanel.add(Box.createVerticalGlue()); - gbuttonPanel.add(infoPanel); - // gbuttonPanel.add(Box.createVerticalStrut(1)); - gbuttonPanel.add(Box.createVerticalGlue()); - gbuttonPanel.add(dbuttonPanel); - // gbuttonPanel.add(Box.createVerticalStrut(1)); - gbuttonPanel.add(Box.createVerticalGlue()); - gbuttonPanel.add(dbuttonPanel); - // gbuttonPanel.add(Box.createVerticalStrut(1)); - gbuttonPanel.add(Box.createVerticalGlue()); - gbuttonPanel.add(ebuttonPanel); - // gbuttonPanel.add(Box.createVerticalStrut(1)); - gbuttonPanel.add(Box.createVerticalGlue()); - gbuttonPanel.add(fbuttonPanel); - // gbuttonPanel.add(Box.createVerticalStrut(1)); - gbuttonPanel.add(Box.createVerticalGlue()); - gbuttonPanel.add(hbuttonPanel); - // gbuttonPanel.add(Box.createVerticalStrut(1)); - gbuttonPanel.add(Box.createVerticalGlue()); - gbuttonPanel.add(ibuttonPanel); - // gbuttonPanel.add(Box.createVerticalStrut(1)); - gbuttonPanel.add(Box.createVerticalGlue()); - - retval.add(gbuttonPanel); - return (retval); - } - - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class StartFromSel implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - BioFabricPanel.TourStatus tstat = bfp_.startTourFromSelection(calcSelectedOnly()); - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class ChooseAStart implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - bfp_.setToCollectTourStart(calcSelectedOnly()); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class GoUp implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - BioFabricPanel.TourStatus tstat = bfp_.goUp(calcSelectedOnly()); - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class GoRight implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - BioFabricPanel.TourStatus tstat = bfp_.goRight(calcSelectedOnly()); - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class GoFarRight implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - BioFabricPanel.TourStatus tstat = bfp_.goFarRight(calcSelectedOnly()); - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class GoLeft implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - BioFabricPanel.TourStatus tstat = bfp_.goLeft(calcSelectedOnly()); - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class GoFarLeft implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - BioFabricPanel.TourStatus tstat = bfp_.goFarLeft(calcSelectedOnly()); - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class GoDown implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - BioFabricPanel.TourStatus tstat = bfp_.goDown(calcSelectedOnly()); - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class ClearTour implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - bfp_.clearTour(); - clearTour(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class Zoom implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - bfp_.zoomToTourStop(); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class ToDrain implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - BioFabricPanel.TourStatus tstat = bfp_.tourToDrainZone(calcSelectedOnly()); - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Shared listener: - */ - - public class SelOnly implements ActionListener { - public void actionPerformed(ActionEvent ev) { - try { - if (doSOReset_) { - return; - } - if ((currTstat_ != null) && (currTstat_.currStopUnselected) && selectedOnly_[currPan_].isSelected()) { - ResourceManager rMan = ResourceManager.getManager(); - JOptionPane.showMessageDialog(topWindow_, rMan.getString("navTool.currLocUnselected"), - rMan.getString("navTool.currLocUnselectedTitle"), - JOptionPane.ERROR_MESSAGE); - doSOReset_ = true; - selectedOnly_[currPan_].setSelected(false); - doSOReset_ = false; - return; - } - boolean newVal = selectedOnly_[currPan_].isSelected(); - BioFabricPanel.TourStatus tstat = bfp_.getTourDirections(newVal); - doSOReset_ = true; - for (int i = 0; i < NUM_PAN_; i++) { - if (i != currPan_) { - selectedOnly_[i].setSelected(newVal); - } - } - doSOReset_ = false; - - installNames(tstat); - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - } - - /*************************************************************************** - ** - ** Labels the nodes - */ - - private class InfoPanel extends JPanel { - private static final long serialVersionUID = 1L; - - private Font myFont_; - private String nodeName_; - private String linkName_; - - InfoPanel() { - setBackground(new Color(255, 255, 255)); - myFont_ = new Font("SansSerif", Font.BOLD, 12); - } - - public void clear() { - nodeName_ = ""; - linkName_ = ""; - return; - } - - public void installNames(BioFabricPanel.TourStatus tstat) { - ResourceManager rMan = ResourceManager.getManager(); - nodeName_ = MessageFormat.format(rMan.getString("navTool.currNode"), new Object[] {currTstat_.nodeName}); - linkName_ = MessageFormat.format(rMan.getString("navTool.currLink"), new Object[] {currTstat_.linkName}); - return; - } - - @Override - public Dimension getPreferredSize() { - return (new Dimension(200, 50)); - } - - @Override - public Dimension getMinimumSize() { - return (new Dimension(100, 50)); - } - - @Override - public Dimension getMaximumSize() { - return (new Dimension(4000, 200)); - } - - public void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D)g; - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - AffineTransform saveTrans = g2.getTransform(); - g2.setFont(myFont_); - g2.setPaint(Color.BLACK); - FontRenderContext frc = g2.getFontRenderContext(); - Rectangle2D boundsN = myFont_.getStringBounds(nodeName_, frc); - Rectangle2D boundsL = myFont_.getStringBounds(linkName_, frc); - - double reduceN = boundsN.getWidth() / this.getWidth(); - double reduceL = boundsL.getWidth() / this.getWidth(); - double maxFactor = Math.max(reduceN, reduceL); - float useFactor = 1.0F; - - if (maxFactor > 1.0) { - double rmf = 1.0 / maxFactor; - useFactor = (float)maxFactor; - g2.translate(this.getWidth() / 2.0, this.getHeight() / 2.0); - g2.scale(rmf, rmf); - g2.translate(-this.getWidth() / 2.0, -this.getHeight() / 2.0); - } - - g2.drawString(nodeName_, (getWidth() / 2.0F) - ((float)boundsN.getWidth() / 2.0F), - (getHeight() / 2.0F) - (useFactor * getHeight() / 6.0F) + ((float)(boundsN.getHeight()) / 3.0F)); - g2.drawString(linkName_, (getWidth() / 2.0F) - ((float)boundsL.getWidth() / 2.0F), - (getHeight() / 2.0F) + (useFactor * getHeight() / 6.0F) + ((float)(boundsL.getHeight()) / 3.0F)); - g2.setTransform(saveTrans); - return; - } - } - - /*************************************************************************** - ** - ** Wrap a toggled panel around the basic tool: - */ - - public static class LabeledFabricNavTool extends JPanel { - - private FabricNavTool fnt_; - private JPanel livePan_; - private CardLayout clay_; - private boolean collapsed_; - - private static final long serialVersionUID = 1L; - - public LabeledFabricNavTool(JFrame topWindow, Font labelFont) { - fnt_ = new FabricNavTool(topWindow); - livePan_ = new JPanel(); - livePan_.setLayout(new BorderLayout()); - - livePan_.setBorder(new LineBorder(Color.black, 2)); - JLabel navLab = new JLabel(ResourceManager.getManager().getString("biofabric.tour")); - navLab.setBorder(new EmptyBorder(0, 5, 0, 0)); - navLab.setOpaque(true); - navLab.setBackground(Color.white); - navLab.setFont(labelFont); - livePan_.add(navLab, BorderLayout.NORTH); - livePan_.add(fnt_, BorderLayout.CENTER); - - clay_ = new CardLayout(); - setLayout(clay_); - add(livePan_, "live"); - add(new JPanel(), "blank"); - clay_.show(this, "live"); - collapsed_ = false; - } - - /*************************************************************************** - ** - ** get actual tool - */ - - public FabricNavTool getFabricNavTool() { - return (fnt_); - } - - /*************************************************************************** - ** - ** Set to blank or populated - */ - - public void setToBlank(boolean val) { - clay_.show(this, (val) ? "blank" : "live"); - collapsed_ = val; - return; - } - - /*************************************************************************** - ** - ** Sizing - */ - - @Override - public Dimension getPreferredSize() { - if (collapsed_) { - return (new Dimension(0, 0)); - } else { - return (livePan_.getPreferredSize()); - } - } - - @Override - public Dimension getMinimumSize() { - if (collapsed_) { - return (new Dimension(0, 0)); - } else { - return (livePan_.getMinimumSize()); - } - } - - @Override - public Dimension getMaximumSize() { - if (collapsed_) { - return (new Dimension(0, 0)); - } else { - return (livePan_.getMaximumSize()); - } - } - } -} diff --git a/src/org/systemsbiology/biofabric/ui/display/MouseOverViewPanel.java b/src/org/systemsbiology/biofabric/ui/display/MouseOverViewPanel.java deleted file mode 100644 index 9784d65..0000000 --- a/src/org/systemsbiology/biofabric/ui/display/MouseOverViewPanel.java +++ /dev/null @@ -1,320 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.ui.display; - -import java.awt.CardLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; - -import javax.imageio.ImageIO; -import javax.imageio.ImageReader; -import javax.imageio.stream.ImageInputStream; -import javax.swing.JPanel; - -/**************************************************************************** -** -** This panel gives a view for mouseovers -*/ - -public class MouseOverViewPanel extends JPanel { - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTANTS - // - //////////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE INSTANCE MEMBERS - // - //////////////////////////////////////////////////////////////////////////// - - private Dimension currSize_; - private HashMap imgs_; - private BufferedImage img_; - private BufferedImage scaledImg_; - private Point scaledImgOrigin_; - private CardLayout myCard_; - private ImagePanel pPan_; - private String path_ ; - private String filePrefix_; - private String fileSuffix_ ; - - private static final long serialVersionUID = 1L; - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Constructor - */ - - public MouseOverViewPanel() { - setBackground(Color.white); - imgs_ = new HashMap(); - scaledImg_ = null; - scaledImgOrigin_ = new Point(0, 0); - img_ = null; - myCard_ = new CardLayout(); - setLayout(myCard_); - - pPan_ = new ImagePanel(); - add(pPan_, "theView"); - JPanel blankPanel = new JPanel(); - blankPanel.setBackground(Color.white); - add(blankPanel, "Hiding"); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Sizing - */ - - @Override - public Dimension getPreferredSize() { - return (new Dimension(800, 100)); - } - - @Override - public Dimension getMinimumSize() { - return (new Dimension(10, 10)); - } - - @Override - public Dimension getMaximumSize() { - return (new Dimension(4000, 340)); - } - - /*************************************************************************** - ** - ** Handle size change - */ - - @Override - public void setBounds(int x, int y, int width, int height) { - super.setBounds(x, y, width, height); - currSize_ = new Dimension(width, height); - resizeImage(); - repaint(); - return; - } - - /*************************************************************************** - ** - ** Set the fragments of file to show: path + filePrefix + nodeName + fileSuffix. - */ - - public void setFileLocations(String path, String filePrefix, String fileSuffix) { - path_ = path; - filePrefix_ = filePrefix; - fileSuffix_ = fileSuffix; - return; - } - - /*************************************************************************** - ** - ** Show or hide the view - */ - - public void showView(boolean enabled) { - myCard_.show(this, (enabled) ? "theView" : "Hiding"); - return; - } - - /*************************************************************************** - ** - ** Install a model - */ - - public void showForNode(String nodeName) { - if (nodeName == null) { - installImage(null); - return; - } - BufferedImage bi = imgs_.get(nodeName); - if (bi != null) { - installImage(bi); - } else { - try { - loadAFile(nodeName); - } catch (IOException ioex) { - System.err.println("Handle file load failures: " + ioex.getLocalizedMessage()); - } - } - return; - } - - /*************************************************************************** - ** - ** Install a model - */ - - private void loadAFile(String nodeName) throws IOException { - File forFoo = new File(path_ + filePrefix_ + nodeName + fileSuffix_); - BufferedImage mvi = readImageFromFile(forFoo); - imgs_.put(nodeName, mvi); - installImage(mvi); - return; - } - - /*************************************************************************** - ** - ** Install a model - */ - - private void installImage(BufferedImage img) { - img_ = img; - scaledImg_ = null; - resizeImage(); - repaint(); - return; - } - - /*************************************************************************** - ** - ** resize image - */ - - private void resizeImage() { - if (img_ == null) { - return; - } - if (currSize_ == null) { - currSize_ = getSize(); - } - // - // Don't do this step if the overview is not currently bring displayed - // - if ((currSize_.width <= 0) || (currSize_.height <= 0)) { - return; - } - double imgAR = (double)img_.getWidth() / (double)img_.getHeight(); - double panelAR = currSize_.getWidth() / currSize_.getHeight(); - int imgHeight; - int imgWidth; - int startX; - int startY; - if (panelAR < imgAR) { // long image, tall panel - imgWidth = currSize_.width; - imgHeight = (int)(imgWidth / imgAR); - if (imgHeight == 0) { - imgHeight = 1; - } - startX = 0; - startY = (currSize_.height - imgHeight) / 2; - } else { - imgHeight = currSize_.height; - imgWidth = (int)(imgHeight * imgAR); - if (imgWidth == 0) { - imgWidth = 1; - } - startX = (currSize_.width - imgWidth) / 2; - startY = 0; - } - scaledImgOrigin_.setLocation(startX, startY); - scaledImg_ = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); - Graphics2D g2 = scaledImg_.createGraphics(); - g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - g2.drawImage(img_, 0, 0, imgWidth, imgHeight, null); - g2.dispose(); - return; - } - - /*************************************************************************** - ** - ** Read in an image. - */ - - public BufferedImage readImageFromFile(File readFile) throws IOException { - FileInputStream fis = new FileInputStream(readFile); - ImageInputStream iis = ImageIO.createImageInputStream(fis); - Iterator readers = ImageIO.getImageReaders(iis); - if (!readers.hasNext()) { - throw new IOException(); - } - ImageReader reader = readers.next(); - BufferedImage retval = ImageIO.read(iis); - return (retval); - } - - /*************************************************************************** - ** - ** Handles the drawing - */ - - private class ImagePanel extends JPanel { - private static final long serialVersionUID = 1L; - - /*************************************************************************** - ** - ** Constructor - */ - - public ImagePanel() { - setBackground(Color.white); - } - - /*************************************************************************** - ** - ** Drawing routine - */ - - public void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D)g; - if (img_ == null) { - return; - } - if (scaledImg_ == null) { - resizeImage(); - } - - g2.drawImage(scaledImg_, scaledImgOrigin_.x, scaledImgOrigin_.y, null); - return; - } - } -} diff --git a/src/org/systemsbiology/biofabric/util/NID.java b/src/org/systemsbiology/biofabric/util/NID.java deleted file mode 100644 index 74ec07c..0000000 --- a/src/org/systemsbiology/biofabric/util/NID.java +++ /dev/null @@ -1,187 +0,0 @@ -/* -** Copyright (C) 2003-2017 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.util; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class NID implements Cloneable, Comparable { - - private final String id_; - - public NID(String id) { - this.id_ = id; - } - - public NID(NID other) { - this.id_ = other.id_; - } - - public String getInternal() { - return (this.id_); - } - - @Override - public NID clone() { - try { - NID newVal = (NID)super.clone(); - return (newVal); - } catch (CloneNotSupportedException ex) { - throw new IllegalStateException(); - } - } - - @Override - public int hashCode() { - return (id_.hashCode()); - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return (false); - } - if (other == this) { - return (true); - } - if (!(other instanceof NID)) { - return (false); - } - NID otherMM = (NID)other; - return (this.id_.equals(otherMM.id_)); - } - - @Override - public String toString() { - return ("OID: " + id_); - } - - public int compareTo(NID other) { - return (this.id_.compareTo(other.id_)); - } - - // - // A class that can be used to order nodes using their names, with the NID only as a tie-breaker if names match. - - - public static class WithName implements Cloneable, Comparable { - - private final NID nid_; - private final String name_; - - public WithName(NID id, String name) { - this.name_ = name; - this.nid_ = id; - } - - public WithName(WithName other) { - this.nid_ = other.nid_; - this.name_ = other.name_; - } - - @Override - public NID clone() { - try { - NID newVal = (NID)super.clone(); - return (newVal); - } catch (CloneNotSupportedException ex) { - throw new IllegalStateException(); - } - } - - @Override - public int hashCode() { - return (nid_.hashCode()); - } - - public NID getNID() { - return (nid_); - } - - public String getName() { - return (name_); - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return (false); - } - if (other == this) { - return (true); - } - if (!(other instanceof WithName)) { - return (false); - } - WithName otherMM = (WithName)other; - boolean eq = this.nid_.equals(otherMM.nid_); - boolean neq = this.name_.equals(otherMM.name_); - if (eq && !neq) { - throw new IllegalStateException(); - } - return (eq); - } - - @Override - public String toString() { - return ("WithName: " + nid_ + " " + name_); - } - - // - // This is the meat of the class. Comparison depends on name. If names actually equal, we fall back on NID. Note we do - // NOT normalize the names: if there are case differences, those are better to use than arbitrary (but consistent) - // internal ID. - public int compareTo(WithName other) { - boolean eq = this.nid_.equals(other.nid_); - boolean neq = this.name_.equals(other.name_); - if (eq && !neq) { - throw new IllegalStateException(); - } - int nDiff = this.name_.compareTo(other.name_); - if (nDiff != 0) { - return (nDiff); - } - return (this.nid_.compareTo(other.nid_)); - } - } - - public static Collection addNames(Collection nids, Map idToName, Collection target) { - for (NID nid : nids) { - target.add(new WithName(nid, idToName.get(nid))); - } - return (target); - } - - - public static Set justNames(Collection nids) { - HashSet retval = new HashSet(); - for (NID.WithName nid : nids) { - String name = nid.getName(); - if (retval.contains(name)) { - throw new IllegalStateException(); - } - retval.add(name); - } - return (retval); - } - -} diff --git a/src/org/systemsbiology/biofabric/util/TrueObjChoiceContent.java b/src/org/systemsbiology/biofabric/util/TrueObjChoiceContent.java deleted file mode 100644 index 76f1e91..0000000 --- a/src/org/systemsbiology/biofabric/util/TrueObjChoiceContent.java +++ /dev/null @@ -1,96 +0,0 @@ -/* -** Copyright (C) 2003-2014 Institute for Systems Biology -** Seattle, Washington, USA. -** -** This library is free software; you can redistribute it and/or -** modify it under the terms of the GNU Lesser General Public -** License as published by the Free Software Foundation; either -** version 2.1 of the License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -package org.systemsbiology.biofabric.util; - -/**************************************************************************** -** -** Utility for choice menus -*/ - -public class TrueObjChoiceContent implements Comparable> { - - public String name; - public T val; - - public TrueObjChoiceContent(String name, T val) { - this.name = name; - this.val = val; - } - - public String toString() { - return (name); - } - - public boolean equals(Object other) { - if (this == other) { - return (true); - } - if (!(other instanceof TrueObjChoiceContent)) { - return (false); - } - TrueObjChoiceContent occ = (TrueObjChoiceContent)other; - if (this.val == null) { - if (occ.val != null) { - return (false); - } - } else if (!this.val.equals(occ.val)) { - return (false); - } - - if (name == null) { - return (occ.name == null); - } - - return (name.equals(occ.name)); - } - - public int hashCode() { - return ((val == null) ? 0 : val.hashCode()); - } - - public int compareTo(TrueObjChoiceContent otherOCC) { - String useValThis = (this.name == null) ? "" : this.name; - String useValOther = (otherOCC.name == null) ? "" : otherOCC.name; - - - int compName = useValThis.compareToIgnoreCase(useValOther); - if (compName != 0) { - return (compName); - } - compName = useValThis.compareTo(useValOther); - if (compName != 0) { - return (compName); - } - - if (this.val == null) { - return ((otherOCC.val == null) ? 0 : 1); - } - - if (otherOCC.val == null) { - return (1); - } - - if (this.val instanceof Comparable) { - return (((Comparable)this.val).compareTo(otherOCC.val)); - } else { - return (this.hashCode() - otherOCC.hashCode()); - } - } -} diff --git a/src/org/systemsbiology/biotapestry/.gitignore b/src/org/systemsbiology/biotapestry/.gitignore deleted file mode 100644 index 9bb88d3..0000000 --- a/src/org/systemsbiology/biotapestry/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/.DS_Store diff --git a/src/org/systemsbiology/biofabric/analysis/Link.java b/src/org/systemsbiology/biotapestry/analysis/Link.java similarity index 84% rename from src/org/systemsbiology/biofabric/analysis/Link.java rename to src/org/systemsbiology/biotapestry/analysis/Link.java index ea0d926..fa497d9 100644 --- a/src/org/systemsbiology/biofabric/analysis/Link.java +++ b/src/org/systemsbiology/biotapestry/analysis/Link.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.analysis; +package org.systemsbiology.biotapestry.analysis; import java.util.Collection; import java.util.Iterator; @@ -27,7 +27,7 @@ ** A Class */ -public class Link implements Cloneable, Comparable { +public class Link implements Cloneable, Comparable { protected String src_; protected String trg_; @@ -44,10 +44,9 @@ public Link(Link other) { this.trg_ = other.trg_; } - @Override - public Link clone() { + public Object clone() { try { - return ((Link)super.clone()); + return (super.clone()); } catch (CloneNotSupportedException cnse) { throw new IllegalStateException(); } @@ -61,12 +60,10 @@ public String getSrc() { return (src_); } - @Override public int hashCode() { return (src_.hashCode() + trg_.hashCode()); } - @Override public String toString() { return ("src = " + src_ + " trg = " + trg_); } @@ -75,11 +72,11 @@ public String toSymbolicString() { return (src_ + signSymbol() + trg_); } - public static String toSymbolicString(Collection links) { + public static String toSymbolicString(Collection links) { StringBuffer buf = new StringBuffer(); - Iterator lit = links.iterator(); + Iterator lit = links.iterator(); while (lit.hasNext()) { - Link lnk = lit.next(); + Link lnk = (Link)lit.next(); buf.append(lnk.toSymbolicString()); if (lit.hasNext()) { buf.append(", "); @@ -92,7 +89,6 @@ public String signSymbol() { return ("--"); } - @Override public boolean equals(Object other) { if (other == null) { return (false); @@ -107,10 +103,11 @@ public boolean equals(Object other) { return (this.src_.equals(otherLink.src_) && this.trg_.equals(otherLink.trg_)); } - public int compareTo(Link otherLink) { - if (this == otherLink) { + public int compareTo(Object o) { + if (this == o) { return (0); } + Link otherLink = (Link)o; if (!this.src_.equals(otherLink.src_)) { return (this.src_.compareToIgnoreCase(otherLink.src_)); diff --git a/src/org/systemsbiology/biotapestry/biofabric/.gitignore b/src/org/systemsbiology/biotapestry/biofabric/.gitignore deleted file mode 100644 index 9bb88d3..0000000 --- a/src/org/systemsbiology/biotapestry/biofabric/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/.DS_Store diff --git a/src/org/systemsbiology/biofabric/io/AttributeLoader.java b/src/org/systemsbiology/biotapestry/biofabric/AttributeLoader.java similarity index 68% rename from src/org/systemsbiology/biofabric/io/AttributeLoader.java rename to src/org/systemsbiology/biotapestry/biofabric/AttributeLoader.java index 950f6b0..5048992 100644 --- a/src/org/systemsbiology/biofabric/io/AttributeLoader.java +++ b/src/org/systemsbiology/biotapestry/biofabric/AttributeLoader.java @@ -17,22 +17,17 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.io; +package org.systemsbiology.biotapestry.biofabric; -import java.io.FileInputStream; +import java.io.FileReader; import java.io.BufferedReader; import java.io.File; -import java.io.InputStreamReader; import java.util.ArrayList; import java.io.IOException; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.NID; - /**************************************************************************** ** ** This loads attribute files @@ -85,15 +80,14 @@ public AttributeLoader() { ** Process an attribute input */ - public String readAttributes(File infile, boolean forNodes, Map results, - Map nodes, ReadStats stats) throws IOException { + public String readAttributes(File infile, boolean forNodes, Map results, ReadStats stats) throws IOException { Pattern nodePat = Pattern.compile("(.*)=(.*)"); Pattern linkPat = Pattern.compile("(.*\\S) (.*)\\((.*)\\) (\\S.*)=(.*)"); Matcher mainMatch = (forNodes) ? nodePat.matcher("") : linkPat.matcher(""); String retval = null; - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "UTF-8")); + BufferedReader in = new BufferedReader(new FileReader(infile)); String line = null; boolean isFirst = true; while ((line = in.readLine()) != null) { @@ -102,9 +96,6 @@ public String readAttributes(File infile, boolean forNodes, Map dupLines; - public ArrayList badLines; + public ArrayList dupLines; + public ArrayList badLines; public boolean shadowsPresent; public ReadStats() { - badLines = new ArrayList(); - dupLines = new ArrayList(); + badLines = new ArrayList(); + dupLines = new ArrayList(); } - } + } } diff --git a/src/org/systemsbiology/biofabric/props/BioFabric.properties b/src/org/systemsbiology/biotapestry/biofabric/BioFabric.properties similarity index 91% rename from src/org/systemsbiology/biofabric/props/BioFabric.properties rename to src/org/systemsbiology/biotapestry/biofabric/BioFabric.properties index 2ee57e6..11778b6 100644 --- a/src/org/systemsbiology/biofabric/props/BioFabric.properties +++ b/src/org/systemsbiology/biotapestry/biofabric/BioFabric.properties @@ -1,15 +1,3 @@ -breadthFirstLayout.title=Choose Starting Node -bFirst.useHighest=Use highest-degree node -bFirst.userSelect=Specify node -bFirst.selectName=Starting Node Name: -bFirst.badNode=Node not found -bFirst.badNodeTitle=Incorrect Node Name -command.Windows=Panels -command.WindowsMnem=P -command.ShowNavPanel=Show Navigation Panel -command.ShowNavPanelMnem=N -command.ShowTourAction=Show Network Tour Panel -command.ShowTourActionMnem=T command.DefaultLayout=Apply Default Layout command.exportMenu=Export command.exportMenuMnem=x @@ -100,16 +88,6 @@ gaggleSupport.failedToDisconnect=Failed to disconnect gaggleSupport.failedToLookupBoss=Failed to look up boss linkGroupEdit.title=Edit Link Groupings linkGroupEdit.suffix=Unique Link Suffix -linkGroupEdit.mode=Mode: -linkGroupEdit.orderPerNode=Order Per Node -linkGroupEdit.orderNetwork=Order Network -linkGroupEdit.loadFromFile=Load Links From File -networkAlignment.title=Network Alignment -networkAlignment.graph1=Graph 1: -networkAlignment.graph2=Graph 2: -networkAlignment.alignment=Alignment: -networkAlignment.ok=OK -networkAlignment.cancel=Cancel navTool.dropZone=Node Zone nodePopup.launchBrowser=Launch browser nsearch.noMatchMessage=No matches found @@ -119,8 +97,6 @@ rsedit.badRegionTitle=Illegal Link Group Definition rsedit.dupRegion=Duplicate Link Group Name rsedit.notCovering=Too Many or Too Few Tags to Assign all Links rsedit.badCoverageTitle=Invalid Link Group Assignment Set -rsedit.ambig=Ambiguous/Overlapping Group Assignments -rsedit.ambigTitle=Invalid Link Group Assignment Set netRelayout.wait=Network layout in progress... netRelayout.waitTitle=Please Wait fabricRead.badLineFormat={0} bad SIF line(s) (2 tokens) ignored @@ -130,9 +106,9 @@ fabricRead.dupLinkTitle=Duplicate or Synonymous Link(s) relDir.title=Specify Directional Relationships relDir.relation=Relation relDir.direction=Directional? -biofabric.overview=Overview -biofabric.tour=Tour -biofabric.magnifier=Magnifier +biofabric.overview=Network Overview +biofabric.tour=Network Tour +biofabric.magnifier=Network Magnifier netBuild.wait=Network build in progress... netBuild.waitTitle=Please Wait errorMsg.outOfMemory=The program has run out of memory.\nYou should exit the program now. @@ -200,14 +176,12 @@ command.LayoutNodesViaAttributes=Layout Using Node Attributes... command.LayoutNodesViaAttributesMnem=N command.LayoutLinksViaAttributes=Layout Using Link Attributes... command.LayoutLinksViaAttributesMnem=L -command.LayoutViaConnectivity=Node Similarity Layout... +command.LayoutViaConnectivity=Layout By Similar Connectivity... command.LayoutViaConnectivityMnem=C command.LayoutViaShapeMatch=Refine to Match Node Link Shapes... command.LayoutViaShapeMatchMnem=S command.SetLinkGroups=Specify Link Groups... command.SetLinkGroupsMnem=G -command.LayoutNetworkAlignment=Network Alignment -command.LayoutNetworkAlignmentMnem=N displayOptions.displayShadowLinks=Display Shadow Links displayOptions.shadeNodes=Node Zone Shading nsearch.discardCurrentSelections=Discard Current Selections @@ -254,6 +228,24 @@ command.EmptyNet=Clear Current Network command.EmptyNetMnem=E command.SetDisplayOptsMnem=y command.SetDisplayOpts=Set Display Options... +command.Gaggle=Gaggle +command.GaggleLowerGoose=Hide Selected Goose +command.GaggleLowerGooseMnem=H +command.GaggleMnem=G +command.GaggleProcessInboundMnem=P +command.GaggleProcessInbound=Process Pending Gaggle Requests +command.GaggleRaiseGooseMnem=S +command.GaggleRaiseGoose=Show Selected Goose +command.GaggleSendNameList=Send Selections as Name List +command.GaggleSendNameListMnem=L +command.GaggleSendNetwork=Send Selected Network +command.GaggleSendNetworkMnem=N +command.GaggleUpdateGeeseMnem=U +command.GaggleUpdateGeese=Update Goose List +command.GaggleConnect=Connect to Gaggle +command.GaggleDisconnect=Disconnect from Gaggle +command.GaggleConnectMnem=C +command.GaggleDisconnectMnem=D command.About=About... command.AboutMnem=A command.Edit=Edit @@ -322,8 +314,6 @@ navTool.zoom=Zoom navTool.skip=Skip unselected elements navTool.currLocUnselected=Current tour stop unselected: cannot change setting. navTool.currLocUnselectedTitle=Cannot Change Setting -navTool.currLink=On Link: {0} -navTool.currNode=On Node: {0} window.aboutTitle=About BioFabric netRecolor.wait=Network recoloring in progress... netRecolor.waitTitle=Please Wait diff --git a/src/org/systemsbiology/biofabric/app/BioFabricApplication.java b/src/org/systemsbiology/biotapestry/biofabric/BioFabricApplication.java similarity index 69% rename from src/org/systemsbiology/biofabric/app/BioFabricApplication.java rename to src/org/systemsbiology/biotapestry/biofabric/BioFabricApplication.java index 1407c0f..cb77dc6 100644 --- a/src/org/systemsbiology/biofabric/app/BioFabricApplication.java +++ b/src/org/systemsbiology/biotapestry/biofabric/BioFabricApplication.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2017 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -18,9 +18,8 @@ */ -package org.systemsbiology.biofabric.app; +package org.systemsbiology.biotapestry.biofabric; -import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.HashMap; @@ -28,12 +27,10 @@ import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.UiUtil; -import org.systemsbiology.biofabric.cmd.CommandSet; -import org.systemsbiology.biofabric.ui.dialogs.UpdateJavaDialog; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; /**************************************************************************** ** @@ -53,26 +50,10 @@ public class BioFabricApplication { // PRIVATE VARIABLES // //////////////////////////////////////////////////////////////////////////// - - private boolean forCyto_; + private BioFabricWindow bfw_; private BioFabricWindow selectionWindow_; - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC CONSTRUCTORS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Now supporting Cytoscape App usage - */ - - public BioFabricApplication(boolean forCyto) { - forCyto_ = forCyto; - } - //////////////////////////////////////////////////////////////////////////// // // PUBLIC METHODS @@ -85,14 +66,16 @@ public BioFabricApplication(boolean forCyto) { */ public void shutdownFabric() { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + goose.closeDown(); + } bfw_.stopBufferBuilding(); bfw_.dispose(); if (selectionWindow_ != null) { selectionWindow_.dispose(); } - if (!forCyto_) { - System.exit(0); - } + System.exit(0); } /*************************************************************************** @@ -131,40 +114,6 @@ public void raiseSelection() { return; } - /*************************************************************************** - ** - ** Launch operations. Now public to support Cytoscape App usage - */ - - public BioFabricWindow launch(Map args) { - boolean isAMac = System.getProperty("os.name").toLowerCase().startsWith("mac os x"); - if (isAMac) { - String verNum = System.getProperty("java.version").toLowerCase(); - if ((verNum.indexOf("1.4") == 0) || (verNum.indexOf("1.5") == 0)) { - UpdateJavaDialog ujw = new UpdateJavaDialog(); - ujw.setVisible(true); - if (!ujw.keepGoingAnyway()) { - return (null); - } - } - } - ResourceManager.initManager("org.systemsbiology.biofabric.props.BioFabric"); - bfw_ = new BioFabricWindow(args, this, true); - ExceptionHandler.getHandler().initialize(bfw_); - Dimension cbf = UiUtil.centerBigFrame(bfw_, 1600, 1200, 1.0, 0); - bfw_.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); - bfw_.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - shutdownFabric(); - } - }); - CommandSet.initCmds("mainWindow", this, bfw_, true); - bfw_.initWindow(cbf); - bfw_.setVisible(true); - initSelection(); - return (bfw_); - } - //////////////////////////////////////////////////////////////////////////// // // PUBLIC STATIC METHODS @@ -177,11 +126,11 @@ public void windowClosing(WindowEvent e) { */ public static void main(String argv[]) { - final HashMap args = new HashMap(); + final HashMap args = new HashMap(); if ((argv.length > 0) && argv[0].equalsIgnoreCase("-gaggle")) { args.put("doGaggle", new Boolean(true)); } - final BioFabricApplication su = new BioFabricApplication(false); + final BioFabricApplication su = new BioFabricApplication(); SwingUtilities.invokeLater(new Runnable() { public void run() { su.launch(args); @@ -189,21 +138,66 @@ public void run() { }); } + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + private BioFabricApplication() { + } + //////////////////////////////////////////////////////////////////////////// // // PRIVATE METHODS // //////////////////////////////////////////////////////////////////////////// + /*************************************************************************** + ** + ** Launch operations + */ + + + private void launch(Map args) { + boolean isAMac = System.getProperty("os.name").toLowerCase().startsWith("mac os x"); + if (isAMac) { + String verNum = System.getProperty("java.version").toLowerCase(); + if ((verNum.indexOf("1.4") == 0) || (verNum.indexOf("1.5") == 0)) { + UpdateJavaDialog ujw = new UpdateJavaDialog(); + ujw.setVisible(true); + if (!ujw.keepGoingAnyway()) { + return; + } + } + } + ResourceManager.initManager("org.systemsbiology.biotapestry.biofabric.BioFabric"); + bfw_ = new BioFabricWindow(args, this, true); + ExceptionHandler.getHandler().initialize(bfw_); + UiUtil.centerBigFrame(bfw_, 1600, 1200, 1.0, 0); + bfw_.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); + bfw_.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + shutdownFabric(); + } + }); + FabricCommands.initCmds("mainWindow", this, bfw_, true); + bfw_.initWindow(); + bfw_.setVisible(true); + initSelection(); + Boolean doGag = (Boolean)args.get("doGaggle"); + gooseLaunch(bfw_, (doGag != null) && doGag.booleanValue()); + return; + } + /*************************************************************************** ** ** init selection window */ private void initSelection() { - selectionWindow_ = new BioFabricWindow(new HashMap(), this, false); - Dimension swDim = new Dimension((int)(bfw_.getWidth() * .80), (int)(bfw_.getHeight() * .80)); - selectionWindow_.setSize(swDim.width, swDim.height); + selectionWindow_ = new BioFabricWindow(new HashMap(), this, false); + selectionWindow_.setSize((int)(bfw_.getWidth() * .80), (int)(bfw_.getHeight() * .80)); selectionWindow_.setLocationRelativeTo(bfw_); selectionWindow_.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); selectionWindow_.addWindowListener(new WindowAdapter() { @@ -211,8 +205,35 @@ public void windowClosing(WindowEvent e) { closeSelection(); } }); - CommandSet.initCmds("selectionWindow", this, selectionWindow_, false); - selectionWindow_.initWindow(swDim); + FabricCommands.initCmds("selectionWindow", this, selectionWindow_, false); + selectionWindow_.initWindow(); + return; + } + + /*************************************************************************** + ** + ** Drawing core + */ + + private void gooseLaunch(BioFabricWindow frame, boolean doGaggle) { + if (doGaggle) { + try { + Class gooseClass = Class.forName("org.systemsbiology.biotapestry.biofabric.FabricGoose"); + FabricGooseInterface liveGoose = (FabricGooseInterface)gooseClass.newInstance(); + liveGoose.setParameters(frame, "unknown"); + liveGoose.activate(); + FabricGooseManager.getManager().setGoose(liveGoose); + } catch (ClassNotFoundException cnfex) { + System.err.println("BTGoose class not found"); + FabricGooseManager.getManager().setGoose(new DeadFabricGoose()); + } catch (InstantiationException iex) { + System.err.println("BTGoose class not instantiated"); + } catch (IllegalAccessException iex) { + System.err.println("BTGoose class not instantiated"); + } + } else { + FabricGooseManager.getManager().setGoose(new DeadFabricGoose()); + } return; } -} +} \ No newline at end of file diff --git a/src/org/systemsbiology/biotapestry/biofabric/BioFabricNavAndControl.java b/src/org/systemsbiology/biotapestry/biofabric/BioFabricNavAndControl.java new file mode 100644 index 0000000..d784cda --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/BioFabricNavAndControl.java @@ -0,0 +1,182 @@ +/* +** Copyright (C) 2003-2011 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Font; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; + +import javax.swing.JSplitPane; +import javax.swing.border.LineBorder; +import org.systemsbiology.biotapestry.util.ResourceManager; + + +/**************************************************************************** +** +** This is the BioFabric Control dashboard +*/ + +public class BioFabricNavAndControl extends JPanel { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + private BioFabricPanel cp_; + private FabricMagnifyingTool fmt_; + private BioFabricOverview bfo_; + private FabricNavTool fnt_; + private FabricLocation floc_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE MEMBERS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Constructor + */ + + public BioFabricNavAndControl(boolean isMain, JFrame topWindow) { + + floc_ = new FabricLocation(); + + FabricCommands fc = FabricCommands.getCmds((isMain) ? "mainWindow" : "selectionWindow"); + fmt_ = new FabricMagnifyingTool(fc.getColorGenerator()); + fmt_.keyInstall((JPanel)topWindow.getContentPane()); + JPanel fmpan = new JPanel(); + fmpan.setLayout(new BorderLayout()); + fmpan.setBorder(new LineBorder(Color.black, 2)); + Font labelFont = new Font("SansSerif", Font.BOLD, 20); + JLabel magLab = new JLabel(ResourceManager.getManager().getString("biofabric.magnifier")); + magLab.setOpaque(true); + magLab.setBackground(Color.white); + magLab.setFont(labelFont); + fmpan.add(magLab, BorderLayout.NORTH); + fmpan.add(fmt_, BorderLayout.CENTER); + + bfo_ = new BioFabricOverview(); + fmt_.setFabricOverview(bfo_); + + JPanel fopan = new JPanel(); + fopan.setLayout(new BorderLayout()); + fopan.setBorder(new LineBorder(Color.black, 2)); + JLabel overLab = new JLabel(ResourceManager.getManager().getString("biofabric.overview")); + overLab.setOpaque(true); + overLab.setBackground(Color.white); + overLab.setFont(labelFont); + fopan.add(overLab, BorderLayout.NORTH); + fopan.add(bfo_, BorderLayout.CENTER); + + fnt_ = new FabricNavTool(topWindow); + JPanel fnpan = new JPanel(); + fnpan.setLayout(new BorderLayout()); + fnpan.setBorder(new LineBorder(Color.black, 2)); + JLabel navLab = new JLabel(ResourceManager.getManager().getString("biofabric.tour")); + navLab.setOpaque(true); + navLab.setBackground(Color.white); + navLab.setFont(labelFont); + fnpan.add(navLab, BorderLayout.NORTH); + fnpan.add(fnt_, BorderLayout.CENTER); + + JPanel buttonsAndStuff = new JPanel(); + buttonsAndStuff.setLayout(new BorderLayout()); + buttonsAndStuff.add(fopan, BorderLayout.CENTER); + buttonsAndStuff.add(fnpan, BorderLayout.EAST); + + JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, fmpan, buttonsAndStuff); + setLayout(new BorderLayout()); + add(floc_, BorderLayout.NORTH); + add(sp, BorderLayout.CENTER); + return; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Get the FabricNavTool + */ + + public FabricNavTool getNavTool() { + return (fnt_); + } + + /*************************************************************************** + ** + ** Get the FabricLocation + */ + + public FabricLocation getFabricLocation() { + return (floc_); + } + + /*************************************************************************** + ** + ** Get the FMT + */ + + public FabricMagnifyingTool getFMT() { + return (fmt_); + } + + /*************************************************************************** + ** + ** Get the Overview + */ + + public BioFabricOverview getOverview() { + return (bfo_); + } + + /*************************************************************************** + ** + ** Set the fabric panel + */ + + public void setFabricPanel(BioFabricPanel cp) { + cp_ = cp; + fnt_.setFabricPanel(cp); + return; + } +} \ No newline at end of file diff --git a/src/org/systemsbiology/biofabric/model/BioFabricNetwork.java b/src/org/systemsbiology/biotapestry/biofabric/BioFabricNetwork.java similarity index 50% rename from src/org/systemsbiology/biofabric/model/BioFabricNetwork.java rename to src/org/systemsbiology/biotapestry/biofabric/BioFabricNetwork.java index 7b405b0..ab9f536 100644 --- a/src/org/systemsbiology/biofabric/model/BioFabricNetwork.java +++ b/src/org/systemsbiology/biotapestry/biofabric/BioFabricNetwork.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2017 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,12 +17,13 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.model; +package org.systemsbiology.biotapestry.biofabric; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.TreeSet; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -34,24 +35,16 @@ import org.xml.sax.Attributes; -import org.systemsbiology.biofabric.analysis.Link; -import org.systemsbiology.biofabric.io.AttributeLoader; -import org.systemsbiology.biofabric.io.FabricFactory; -import org.systemsbiology.biofabric.layouts.DefaultEdgeLayout; -import org.systemsbiology.biofabric.layouts.DefaultLayout; -import org.systemsbiology.biofabric.parser.AbstractFactoryClient; -import org.systemsbiology.biofabric.parser.GlueStick; -import org.systemsbiology.biofabric.ui.FabricColorGenerator; -import org.systemsbiology.biofabric.ui.FabricDisplayOptions; -import org.systemsbiology.biofabric.ui.FabricDisplayOptionsManager; -import org.systemsbiology.biofabric.util.AttributeExtractor; -import org.systemsbiology.biofabric.util.CharacterEntityMapper; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.Indenter; -import org.systemsbiology.biofabric.util.MinMax; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.UiUtil; -import org.systemsbiology.biofabric.util.UniqueLabeller; +import org.systemsbiology.biotapestry.analysis.Link; +import org.systemsbiology.biotapestry.parser.AbstractFactoryClient; +import org.systemsbiology.biotapestry.parser.GlueStick; +import org.systemsbiology.biotapestry.util.AttributeExtractor; +import org.systemsbiology.biotapestry.util.CharacterEntityMapper; +import org.systemsbiology.biotapestry.util.DataUtil; +import org.systemsbiology.biotapestry.util.Indenter; +import org.systemsbiology.biotapestry.util.MinMax; +import org.systemsbiology.biotapestry.util.UiUtil; + /**************************************************************************** ** @@ -72,52 +65,18 @@ public class BioFabricNetwork { // //////////////////////////////////////////////////////////////////////////// - public enum BuildMode {DEFAULT_LAYOUT, - REORDER_LAYOUT , - CLUSTERED_LAYOUT , - SHADOW_LINK_CHANGE, - GROUP_PER_NODE_CHANGE, - BUILD_FOR_SUBMODEL, - BUILD_FROM_XML , - BUILD_FROM_SIF , - BUILD_FROM_GAGGLE , - NODE_ATTRIB_LAYOUT , - LINK_ATTRIB_LAYOUT, - NODE_CLUSTER_LAYOUT, - CONTROL_TOP_LAYOUT, - HIER_DAG_LAYOUT, - WORLD_BANK_LAYOUT, - GROUP_PER_NETWORK_CHANGE, - }; - - public enum LayoutMode { - UNINITIALIZED_MODE("notSet"), - PER_NODE_MODE("perNode"), - PER_NETWORK_MODE("perNetwork"); - - private String text; - - LayoutMode(String text) { - this.text = text; - } - - public String getText() { - return (text); - } - - public static LayoutMode fromString(String text) throws IOException { - if (text != null) { - for (LayoutMode lm : LayoutMode.values()) { - if (text.equalsIgnoreCase(lm.text)) { - return (lm); - } - } - } - throw new IOException(); - } - } - - + public static final int DEFAULT_LAYOUT = 0; + public static final int REORDER_LAYOUT = 1; + public static final int CLUSTERED_LAYOUT = 2; + public static final int SHADOW_LINK_CHANGE = 3; + public static final int LINK_GROUP_CHANGE = 4; + public static final int BUILD_FOR_SUBMODEL = 5; + public static final int BUILD_FROM_XML = 6; + public static final int BUILD_FROM_SIF = 7; + public static final int BUILD_FROM_GAGGLE = 8; + public static final int NODE_ATTRIB_LAYOUT = 9; + public static final int LINK_ATTRIB_LAYOUT = 10; + //////////////////////////////////////////////////////////////////////////// // // PRIVATE INSTANCE MEMBERS @@ -128,22 +87,22 @@ public static LayoutMode fromString(String text) throws IOException { // For mapping of selections: // - private HashMap rowToTargID_; + private HashMap rowToTarg_; private int rowCount_; // // Link and node definitions: // - private TreeMap fullLinkDefs_; - private TreeMap nonShadowedLinkMap_; - private HashMap nodeDefs_; + private TreeMap fullLinkDefs_; + private TreeMap nonShadowedLinkMap_; + private HashMap nodeDefs_; // // Grouping for links: // - private List linkGrouping_; + private List linkGrouping_; // // Columns assignments, shadow and non-shadow states: @@ -154,16 +113,6 @@ public static LayoutMode fromString(String text) throws IOException { private FabricColorGenerator colGen_; - - // - // Current Link Layout Mode, either PER_NODE or PER_NETWORK - // Default value is PER_NODE - // - - private LayoutMode layoutMode_; - - private UniqueLabeller nodeIDGenerator_; - //////////////////////////////////////////////////////////////////////////// // // PUBLIC CONSTRUCTORS @@ -176,39 +125,30 @@ public static LayoutMode fromString(String text) throws IOException { */ public BioFabricNetwork(BuildData bd) { - nodeIDGenerator_ = new UniqueLabeller(); - layoutMode_ = LayoutMode.UNINITIALIZED_MODE; - BuildMode mode = bd.getMode(); + int mode = bd.getMode(); switch (mode) { case DEFAULT_LAYOUT: case REORDER_LAYOUT: case CLUSTERED_LAYOUT: - case GROUP_PER_NODE_CHANGE: - case GROUP_PER_NETWORK_CHANGE: + case LINK_GROUP_CHANGE: case NODE_ATTRIB_LAYOUT: case LINK_ATTRIB_LAYOUT: - case NODE_CLUSTER_LAYOUT: - case CONTROL_TOP_LAYOUT: - case HIER_DAG_LAYOUT: - case WORLD_BANK_LAYOUT: RelayoutBuildData rbd = (RelayoutBuildData)bd; normalCols_ = new ColumnAssign(); shadowCols_ = new ColumnAssign(); - rowToTargID_ = new HashMap(); - fullLinkDefs_ = new TreeMap(); - nonShadowedLinkMap_ = new TreeMap(); - nodeDefs_ = new HashMap(); - linkGrouping_ = new ArrayList(rbd.linkGroups); + rowToTarg_ = new HashMap(); + fullLinkDefs_ = new TreeMap(); + nonShadowedLinkMap_ = new TreeMap(); + nodeDefs_ = new HashMap(); + linkGrouping_ = new ArrayList(); colGen_ = rbd.colGen; - layoutMode_ = rbd.layoutMode; relayoutNetwork(rbd); break; case BUILD_FOR_SUBMODEL: SelectBuildData sbd = (SelectBuildData)bd; colGen_ = sbd.fullNet.colGen_; - this.linkGrouping_ = new ArrayList(sbd.fullNet.linkGrouping_); - this.layoutMode_ = sbd.fullNet.layoutMode_; + this.linkGrouping_ = new ArrayList(sbd.fullNet.linkGrouping_); fillSubModel(sbd.fullNet, sbd.subNodes, sbd.subLinks); break; case BUILD_FROM_XML: @@ -216,28 +156,26 @@ public BioFabricNetwork(BuildData bd) { BioFabricNetwork built = ((PreBuiltBuildData)bd).bfn; this.normalCols_ = built.normalCols_; this.shadowCols_ = built.shadowCols_; - this.rowToTargID_ = built.rowToTargID_; + this.rowToTarg_ = built.rowToTarg_; this.fullLinkDefs_ = built.fullLinkDefs_; this.nonShadowedLinkMap_ = built.nonShadowedLinkMap_; this.nodeDefs_ = built.nodeDefs_; this.colGen_ = built.colGen_; this.rowCount_ = built.rowCount_; this.linkGrouping_ = built.linkGrouping_; - this.layoutMode_ = built.layoutMode_; break; case BUILD_FROM_SIF: case BUILD_FROM_GAGGLE: - RelayoutBuildData obd = (RelayoutBuildData)bd; + OrigBuildData obd = (OrigBuildData)bd; normalCols_ = new ColumnAssign(); shadowCols_ = new ColumnAssign(); - rowToTargID_ = new HashMap(); - fullLinkDefs_ = new TreeMap(); - nonShadowedLinkMap_ = new TreeMap(); - nodeDefs_ = new HashMap(); - linkGrouping_ = new ArrayList(); - layoutMode_ = LayoutMode.UNINITIALIZED_MODE; + rowToTarg_ = new HashMap(); + fullLinkDefs_ = new TreeMap(); + nonShadowedLinkMap_ = new TreeMap(); + nodeDefs_ = new HashMap(); + linkGrouping_ = new ArrayList(); colGen_ = obd.colGen; - processLinks(obd); + processLinks(obd.allLinks, obd.loneNodes, obd.colGen); break; default: throw new IllegalArgumentException(); @@ -250,36 +188,13 @@ public BioFabricNetwork(BuildData bd) { // //////////////////////////////////////////////////////////////////////////// - /*************************************************************************** - ** - ** Get map from normalized name to IDs (Moving to Cytoscape SUIDs, there - * can be multiple nodes for one name) - */ - - public Map> getNormNameToIDs() { - HashMap> retval = new HashMap>(); - Iterator kit = nodeDefs_.keySet().iterator(); - while (kit.hasNext()) { - NID.WithName key = kit.next(); - NodeInfo forKey = nodeDefs_.get(key); - String nameNorm = DataUtil.normKey(forKey.getNodeName()); - Set forName = retval.get(nameNorm); - if (forName == null) { - forName = new HashSet(); - retval.put(nameNorm, forName); - } - forName.add(key); - } - return (retval); - } - /*************************************************************************** ** ** Install link grouping */ - public void installLinkGroups(List linkTagList) { - linkGrouping_ = new ArrayList(linkTagList); + public void installLinkGroups(List linkTagList) { + linkGrouping_ = new ArrayList(linkTagList); return; } @@ -288,7 +203,7 @@ public void installLinkGroups(List linkTagList) { ** Get link grouping */ - public List getLinkGroups() { + public List getLinkGroups() { return (linkGrouping_); } @@ -297,94 +212,39 @@ public List getLinkGroups() { ** Given an attribute list giving node order, confirm it is valid: */ - public boolean checkNewNodeOrder(Map nodeAttributes) { + public boolean checkNewNodeOrder(Map nodeRows) { // // All existing targets must have a row, and all existing // rows need a target assigned! // - HashSet normedNames = new HashSet(); - Iterator rttvit = rowToTargID_.values().iterator(); + HashSet asUpper = new HashSet(); + Iterator rttvit = rowToTarg_.values().iterator(); while (rttvit.hasNext()) { - NID.WithName key = rttvit.next(); - NodeInfo ni = nodeDefs_.get(key); - normedNames.add(DataUtil.normKey(ni.getNodeName())); - } - - HashSet normedKeys = new HashSet(); - Iterator akit = nodeAttributes.keySet().iterator(); - while (akit.hasNext()) { - AttributeLoader.AttributeKey key = akit.next(); - normedKeys.add(DataUtil.normKey(key.toString())); + asUpper.add(((String)rttvit.next()).toUpperCase()); } - - if (!normedNames.equals(normedKeys)) { + if (!asUpper.equals(new HashSet(nodeRows.keySet()))) { return (false); } - TreeSet asInts = new TreeSet(); - Iterator nrvit = nodeAttributes.values().iterator(); + TreeSet asInts = new TreeSet(); + Iterator nrvit = nodeRows.values().iterator(); while (nrvit.hasNext()) { - String asStr = nrvit.next(); + String asStr = (String)nrvit.next(); try { asInts.add(Integer.valueOf(asStr)); } catch (NumberFormatException nfex) { return (false); } } - - if (!asInts.equals(new TreeSet(rowToTargID_.keySet()))) { + if (!asInts.equals(new TreeSet(rowToTarg_.keySet()))) { return (false); } return (true); } - /*************************************************************************** - ** - ** Given an attribute list giving node order, confirm it is valid: - */ - - public boolean checkNodeClusterAssignment(Map nodeClusters) { - - // - // All nodes must be assigned to a cluster - // - - HashSet asUpper = new HashSet(); - Iterator rttvit = rowToTargID_.values().iterator(); - /* - while (rttvit.hasNext()) { - - asUpper.add(new AttributeLoader.StringKey(rttvit.next().toUpperCase())); - - - this.nodeOrder = new HashMap(); - Map> nameToID = genNormNameToID(); - for (AttributeLoader.AttributeKey key : nodeOrder.keySet()) { - try { - Integer newRow = Integer.valueOf(nodeOrder.get(key)); - String normName = DataUtil.normKey(((AttributeLoader.StringKey)key).key); - Set ids = nameToID.get(normName); - if (ids.size() != 1) { - throw new IllegalStateException(); - } - NID id = ids.iterator().next(); - this.nodeOrder.put(id, newRow); - } catch (NumberFormatException nfex) { - throw new IllegalStateException(); - } - } - }*/ - UiUtil.fixMePrintout("Actually do something"); - // if (!asUpper.equals(new HashSet(nodeClusters.keySet()))) { - // return (false); - // } - - return (true); - } - /*************************************************************************** ** ** Given an attribute list giving link order, confirm it is valid, get back @@ -396,22 +256,22 @@ public boolean checkNodeClusterAssignment(Map checkNewLinkOrder(Map linkRows) { + public SortedMap checkNewLinkOrder(Map linkRows) { // // Recover the mapping that tells us what link relationships are // directed: // - HashMap relDir = new HashMap(); - Set allLinks = getAllLinks(true); - Iterator alit = allLinks.iterator(); + HashMap relDir = new HashMap(); + Set allLinks = getAllLinks(true); + Iterator alit = allLinks.iterator(); while (alit.hasNext()) { - FabricLink link = alit.next(); + FabricLink link = (FabricLink)alit.next(); FabricLink.AugRelation rel = link.getAugRelation(); boolean isDir = link.isDirected(); Boolean myVal = new Boolean(isDir); - Boolean currVal = relDir.get(rel); + Boolean currVal = (Boolean)relDir.get(rel); if (currVal != null) { if (!currVal.equals(myVal)) { throw new IllegalStateException(); @@ -426,13 +286,13 @@ public SortedMap checkNewLinkOrder(Map dirMap = new TreeMap(); - Iterator lrit = linkRows.keySet().iterator(); + TreeMap dirMap = new TreeMap(); + Iterator lrit = linkRows.keySet().iterator(); while (lrit.hasNext()) { FabricLink link = (FabricLink)lrit.next(); - String colNumStr = linkRows.get(link); - FabricLink dirCopy = link.clone(); - Boolean isDirected = relDir.get(dirCopy.getAugRelation()); + String colNumStr = (String)linkRows.get(link); + FabricLink dirCopy = (FabricLink)link.clone(); + Boolean isDirected = (Boolean)relDir.get(dirCopy.getAugRelation()); dirCopy.installDirection(isDirected); try { dirMap.put(Integer.valueOf(colNumStr), dirCopy); @@ -442,9 +302,9 @@ public SortedMap checkNewLinkOrder(Map alks = new TreeSet(allLinks); + TreeSet alks = new TreeSet(allLinks); // Ordered set of guys we have been handed: - TreeSet dmvs = new TreeSet(dirMap.values()); + TreeSet dmvs = new TreeSet(dirMap.values()); // Has to be the case that the link definitions are 1:1 and // onto, or we have an error: @@ -456,8 +316,8 @@ public SortedMap checkNewLinkOrder(Map ldks = new TreeSet(fullLinkDefs_.keySet()); - TreeSet dmks = new TreeSet(dirMap.keySet()); + TreeSet ldks = new TreeSet(fullLinkDefs_.keySet()); + TreeSet dmks = new TreeSet(dirMap.keySet()); if (!ldks.equals(dmks)) { return (null); @@ -471,11 +331,11 @@ public SortedMap checkNewLinkOrder(Map getAllLinks(boolean withShadows) { - HashSet allLinks = new HashSet(); - Iterator ldit = fullLinkDefs_.keySet().iterator(); + public Set getAllLinks(boolean withShadows) { + HashSet allLinks = new HashSet(); + Iterator ldit = fullLinkDefs_.keySet().iterator(); while (ldit.hasNext()) { - Integer col = ldit.next(); + Integer col = (Integer)ldit.next(); LinkInfo li = getLinkDefinition(col, true); // just get everybody... FabricLink link = li.getLink(); if (withShadows || !link.isShadow()) { @@ -490,7 +350,7 @@ public Set getAllLinks(boolean withShadows) { ** Get ordered linkInfo iterator */ - public Iterator getOrderedLinkInfo(boolean withShadows) { + public Iterator getOrderedLinkInfo(boolean withShadows) { return ((withShadows) ? fullLinkDefs_.keySet().iterator() : nonShadowedLinkMap_.keySet().iterator()); } @@ -499,26 +359,33 @@ public Iterator getOrderedLinkInfo(boolean withShadows) { ** Process a link set */ - private void processLinks(RelayoutBuildData rbd) { + private void processLinks(Set allLinks, Set loneNodes, FabricColorGenerator colGen) { // // Note the allLinks Set has pruned out duplicates and synonymous non-directional links // - - List targetIDs = (new DefaultLayout()).doNodeLayout(rbd, null); + + List targets = defaultNodeOrder(allLinks, loneNodes); // // Now have the ordered list of targets we are going to display. + // Build target->row maps and the inverse: // - fillNodesFromOrder(targetIDs, rbd.colGen, rbd.clustAssign); + fillNodesFromOrder(targets, colGen); + // + // Now each link is given a vertical extent. + // + + TreeMap rankedLinks = new TreeMap(); + Map relsForPair = generateLinkExtents(allLinks, rankedLinks); + // // This now assigns the link to its column. Note that we order them // so that the shortest vertical link is drawn first! // - (new DefaultEdgeLayout()).layoutEdges(rbd); - specifiedLinkToColumn(rbd.colGen, rbd.linkOrder, false); + defaultLinkToColumn(rankedLinks, relsForPair, colGen); // // Determine the start & end of each target row needed to handle the incoming @@ -531,7 +398,7 @@ private void processLinks(RelayoutBuildData rbd) { // For the lone nodes, they are assigned into the last column: // - loneNodesToLastColumn(rbd.loneNodeIDs); + loneNodesToLastColumn(loneNodes); return; } @@ -541,22 +408,23 @@ private void processLinks(RelayoutBuildData rbd) { */ private void relayoutNetwork(RelayoutBuildData rbd) { - BuildMode mode = rbd.getMode(); - installLinkGroups(rbd.linkGroups); - setLayoutMode(rbd.layoutMode); - boolean specifiedNodeOrder = (mode == BuildMode.NODE_ATTRIB_LAYOUT) || - (mode == BuildMode.DEFAULT_LAYOUT) || - (mode == BuildMode.CONTROL_TOP_LAYOUT) || - (mode == BuildMode.HIER_DAG_LAYOUT) || - (mode == BuildMode.WORLD_BANK_LAYOUT) || - (mode == BuildMode.NODE_CLUSTER_LAYOUT) || - (mode == BuildMode.CLUSTERED_LAYOUT) || - (mode == BuildMode.REORDER_LAYOUT); - List targetIDs; - if (specifiedNodeOrder) { - targetIDs = specifiedIDOrder(rbd.allNodeIDs, rbd.nodeOrder); + int mode = rbd.getMode(); + FabricColorGenerator colGen = rbd.colGen; + SortedMap linkOrder = rbd.linkOrder; + List linkGroups = (mode == LINK_GROUP_CHANGE) ? rbd.newLinkGroups : rbd.existingLinkGroups; + installLinkGroups(linkGroups); + boolean installNonStandardNodeOrder = (mode == NODE_ATTRIB_LAYOUT) || + (mode == CLUSTERED_LAYOUT) || + (mode == REORDER_LAYOUT); + boolean installDefaultNodeOrder = (mode == DEFAULT_LAYOUT); + + List targets; + if (installNonStandardNodeOrder) { + targets = specifiedOrder(rbd.allNodes, rbd.nodeOrder); + } else if (installDefaultNodeOrder) { + targets = defaultNodeOrder(rbd.allLinks, rbd.loneNodes); } else { - targetIDs = rbd.existingIDOrder; + targets = rbd.existingOrder; } // @@ -564,32 +432,31 @@ private void relayoutNetwork(RelayoutBuildData rbd) { // Build target->row maps and the inverse: // - fillNodesFromOrder(targetIDs, rbd.colGen, rbd.clustAssign); + fillNodesFromOrder(targets, colGen); // - // Ordering of links: + // Now each link is given a vertical extent. // - - if ((rbd.linkOrder == null) || rbd.linkOrder.isEmpty() || (mode == BuildMode.GROUP_PER_NODE_CHANGE) || (mode == BuildMode.GROUP_PER_NETWORK_CHANGE)) { - if ((rbd.nodeOrder == null) || rbd.nodeOrder.isEmpty()) { - rbd.nodeOrder = new HashMap(); - int numT = targetIDs.size(); - for (int i = 0; i < numT; i++) { - NID.WithName targID = targetIDs.get(i); - rbd.nodeOrder.put(targID, Integer.valueOf(i)); - } - } - (new DefaultEdgeLayout()).layoutEdges(rbd); - } - + + TreeMap rankedLinks = new TreeMap(); + Map relsForPair = generateLinkExtents(rbd.allLinks, rankedLinks); + // - // This now assigns the link to its column, based on user specification + // Ordering of links: // - specifiedLinkToColumn(rbd.colGen, rbd.linkOrder, ((mode == BuildMode.LINK_ATTRIB_LAYOUT) || - (mode == BuildMode.NODE_CLUSTER_LAYOUT) || - (mode == BuildMode.GROUP_PER_NODE_CHANGE) || - (mode == BuildMode.GROUP_PER_NETWORK_CHANGE))); + if (linkOrder == null) { + // + // This now assigns the link to its column. Note that we order them + // so that the shortest vertical link is drawn first! + // + defaultLinkToColumn(rankedLinks, relsForPair, colGen); + } else { + // + // This now assigns the link to its column, based on user specification + // + specifiedLinkToColumn(colGen, linkOrder, (mode == LINK_ATTRIB_LAYOUT)); + } // // Determine the start & end of each target row needed to handle the incoming @@ -602,24 +469,31 @@ private void relayoutNetwork(RelayoutBuildData rbd) { // For the lone nodes, they are assigned into the last column: // - loneNodesToLastColumn(rbd.loneNodeIDs); + loneNodesToLastColumn(rbd.loneNodes); return; } /*************************************************************************** ** - ** Get specified node ID order list from attribute map + ** Get specified node order list from attribute map */ - private List specifiedIDOrder(Set allNodeIDs, Map newOrder) { - TreeMap forRetval = new TreeMap(); - Iterator rttvit = allNodeIDs.iterator(); + private List specifiedOrder(Set allNodes, Map newOrder) { + + TreeMap forRetval = new TreeMap(); + Iterator rttvit = allNodes.iterator(); while (rttvit.hasNext()) { - NID.WithName key = rttvit.next(); - Integer val = newOrder.get(key); - forRetval.put(val, key); + String key = (String)rttvit.next(); + String asUpperKey = key.toUpperCase(); + String valAsStr = (String)newOrder.get(asUpperKey); + try { + Integer newRow = Integer.valueOf(valAsStr); + forRetval.put(newRow, key); + } catch (NumberFormatException nfex) { + throw new IllegalStateException(); + } } - return (new ArrayList(forRetval.values())); + return (new ArrayList(forRetval.values())); } /*************************************************************************** @@ -627,13 +501,13 @@ private List specifiedIDOrder(Set allNodeIDs, Map existingIDOrder() { - ArrayList retval = new ArrayList(); - Iterator rtit = new TreeSet(rowToTargID_.keySet()).iterator(); + public List existingOrder() { + ArrayList retval = new ArrayList(); + Iterator rtit = new TreeSet(rowToTarg_.keySet()).iterator(); while (rtit.hasNext()) { - Integer row = rtit.next(); - NID.WithName nodeID = rowToTargID_.get(row); - retval.add(nodeID); + Integer row = (Integer)rtit.next(); + String node = (String)rowToTarg_.get(row); + retval.add(node); } return (retval); } @@ -643,12 +517,12 @@ public List existingIDOrder() { ** Get existing link order */ - public SortedMap getExistingLinkOrder() { - TreeMap retval = new TreeMap(); - Iterator ldit = fullLinkDefs_.keySet().iterator(); + public SortedMap getExistingLinkOrder() { + TreeMap retval = new TreeMap(); + Iterator ldit = fullLinkDefs_.keySet().iterator(); while (ldit.hasNext()) { - Integer col = ldit.next(); - LinkInfo li = fullLinkDefs_.get(col); + Integer col = (Integer)ldit.next(); + LinkInfo li = (LinkInfo)fullLinkDefs_.get(col); FabricLink link = li.getLink(); retval.put(col, link); } @@ -660,8 +534,8 @@ public SortedMap getExistingLinkOrder() { ** Get existing order */ - public Iterator getRows() { - return (rowToTargID_.keySet().iterator()); + public Iterator getRows() { + return (rowToTarg_.keySet().iterator()); } /*************************************************************************** @@ -669,16 +543,16 @@ public Iterator getRows() { ** Process a link set */ - private void specifiedLinkToColumn(FabricColorGenerator colGen, SortedMap linkOrder, boolean userSpec) { + private void specifiedLinkToColumn(FabricColorGenerator colGen, SortedMap linkOrder, boolean userSpec) { normalCols_.columnCount = 0; shadowCols_.columnCount = 0; int numColors = colGen.getNumColors(); - Iterator frkit = linkOrder.keySet().iterator(); + Iterator frkit = linkOrder.keySet().iterator(); while (frkit.hasNext()) { - Integer nextCol = frkit.next(); - FabricLink nextLink = linkOrder.get(nextCol); - Integer useForSDef = Integer.valueOf(shadowCols_.columnCount); + Integer nextCol = (Integer)frkit.next(); + FabricLink nextLink = (FabricLink)linkOrder.get(nextCol); + Integer useForSDef = new Integer(shadowCols_.columnCount); Integer[] colCounts = addLinkDef(nextLink, numColors, normalCols_.columnCount, shadowCols_.columnCount, colGen); shadowCols_.columnCount = colCounts[0].intValue(); if (colCounts[1] != null) { @@ -686,11 +560,11 @@ private void specifiedLinkToColumn(FabricColorGenerator colGen, SortedMap dzst = nit.getDrainZones(true); - if (dzst.size() == 0) { - dzst = (new ArrayList()); - dzst.add(new MinMax().init()); - nit.addDrainZone(dzst.get(0), true); + MinMax dzst = nit.getDrainZone(true); + if (dzst == null) { + dzst = (new MinMax()).init(); + nit.setDrainZone(dzst, true); } - dzst.get(0).update(linf.getUseColumn(true)); + dzst.update(linf.getUseColumn(true)); - List dznt = nit.getDrainZones(false); - if (dznt.size() == 0) { - dznt.add((new MinMax()).init()); - nit.addDrainZone(dznt.get(0), false); + MinMax dznt = nit.getDrainZone(false); + if (dznt == null) { + dznt = (new MinMax()).init(); + nit.setDrainZone(dznt, false); } - dznt.get(0).update(linf.getUseColumn(false)); + dznt.update(linf.getUseColumn(false)); } else { - List dzsb = nib.getDrainZones(true); - if (dzsb.size() == 0) { - dzsb.add((new MinMax()).init()); - nib.addDrainZone(dzsb.get(0), true); + MinMax dzsb = nib.getDrainZone(true); + if (dzsb == null) { + dzsb = (new MinMax()).init(); + nib.setDrainZone(dzsb, true); } - dzsb.get(0).update(linf.getUseColumn(true)); + dzsb.update(linf.getUseColumn(true)); } - }*/ + } } - // WJRL 2/7/17: Actually, this should handle *all* drain zone calculations now, correct?? - // if (userSpec || this.linkGrouping_!= null) { // Not sure this works 100% of the time -Rishi Desai 1/17/2017 - setDrainZonesWithMultipleLabels(true); - setDrainZonesWithMultipleLabels(false); - // } else { - // setDrainZonesByContig(true); - // setDrainZonesByContig(false); - // } + if (userSpec) { + setDrainZonesByContig(true); + setDrainZonesByContig(false); + } return; } /*************************************************************************** - ** Calculates each MinMax region for every node's zero or more drain zones ** - */ - - private void setDrainZonesWithMultipleLabels(boolean forShadow) { - - List links = getLinkDefList(forShadow); - Map> nodeToZones = new TreeMap>(); - - for (int startIdx = 0; startIdx < links.size(); startIdx++) { - - LinkInfo startLI = links.get(startIdx); - - for (int endIdx = startIdx + 1; endIdx < links.size(); endIdx++) { - - LinkInfo currLI = links.get(endIdx); - - if (! isContiguous(startLI, currLI)) { - - endIdx--; // backtrack, because end of drain zone has been reached - - MinMax mm = new MinMax(startIdx, endIdx); - NID.WithName name = findZoneNode(mm, forShadow); - - if (nodeToZones.get(name) == null) { - nodeToZones.put(name, new ArrayList()); - } - nodeToZones.get(name).add(mm); - - startIdx += (endIdx - startIdx); // add drain zone length to start index - break; - - } else if (endIdx == links.size() - 1) { - - MinMax mm = new MinMax(startIdx, endIdx); - NID.WithName name = findZoneNode(mm, forShadow); - - if (nodeToZones.get(name) == null) { - nodeToZones.put(name, new ArrayList()); - } - nodeToZones.get(name).add(mm); - - startIdx += (endIdx - startIdx); - } - - } - } - -// for (Map.Entry> entry: nodeToZones.entrySet()) { -// String s = entry.getKey() + " "; -// for (MinMax mm : entry.getValue()) { -// s += "(" + mm.min + " " + mm.max + ")"; -// } -// -// System.out.println(s); -// } -// System.out.println('\n'); - - for (Map.Entry> entry : nodeToZones.entrySet()) { - - NodeInfo ni = getNodeDefinition(entry.getKey()); - ni.setDrainZones(entry.getValue(), forShadow); - } - - } - - /*************************************************************************** - ** Returns true if two links are part of the same drain zone - ** - */ - - private boolean isContiguous(LinkInfo A, LinkInfo B) { - - NID.WithName mainA; - if (A.isShadow()) { - mainA = getNodeIDForRow(A.bottomRow()); - } else { - mainA = getNodeIDForRow(A.topRow()); - } - - NID.WithName mainB; - if (B.isShadow()) { - mainB = getNodeIDForRow(B.bottomRow()); - } else { - mainB = getNodeIDForRow(B.topRow()); - } - - return mainA.equals(mainB); - } - - /*************************************************************************** - ** Given an interval MinMax([A,B]) of links, calculates the node - ** associated with the drain zone's interval - */ - - private NID.WithName findZoneNode(MinMax mm, boolean forShadow) { - - List links = getLinkDefList(forShadow); - - Map count = new TreeMap(); - - for (int i = mm.min; i <= mm.max; i++) { - - LinkInfo li = links.get(i); - - NID.WithName main; - if (li.isShadow()) { - main = getNodeIDForRow(li.bottomRow()); - } else { - main = getNodeIDForRow(li.topRow()); - } - - if (count.get(main) == null) { - count.put(main, 0); - } - - count.put(main, count.get(main) + 1); - } - - NID.WithName keyMax = null; - - for (Map.Entry entry : count.entrySet()) { - - if (keyMax == null || entry.getValue() > count.get(keyMax)) { - keyMax = entry.getKey(); - } - } - - return keyMax; - } - - /*************************************************************************** - ** ** Helper */ - private void updateContigs(NID.WithName nodeID, HashMap> runsPerNode, - Integer lastCol, Integer col) { + private void updateContigs(String nodeName, HashMap runsPerNode, Integer lastCol, Integer col) { int colVal = col.intValue(); - SortedMap runs = runsPerNode.get(nodeID); + TreeMap runs = (TreeMap)runsPerNode.get(nodeName); if (runs == null) { - runs = new TreeMap(); - runsPerNode.put(nodeID, runs); + runs = new TreeMap(); + runsPerNode.put(nodeName, runs); } - MinMax currRun = runs.get(lastCol); + MinMax currRun = (MinMax)runs.get(lastCol); if (currRun == null) { currRun = new MinMax(colVal); runs.put(col, currRun); @@ -909,16 +641,16 @@ private void updateContigs(NID.WithName nodeID, HashMap> runsPerNode, boolean forShadow) { - Iterator rpnit = runsPerNode.keySet().iterator(); + private void runsToDrain(HashMap runsPerNode, boolean forShadow) { + Iterator rpnit = runsPerNode.keySet().iterator(); while (rpnit.hasNext()) { - NID.WithName nodeID = rpnit.next(); - SortedMap runs = runsPerNode.get(nodeID); + String nodeName = (String)rpnit.next(); + TreeMap runs = (TreeMap)runsPerNode.get(nodeName); MinMax maxRun = null; int maxSize = Integer.MIN_VALUE; - Iterator rit = runs.values().iterator(); + Iterator rit = runs.values().iterator(); while (rit.hasNext()) { - MinMax aRun = rit.next(); + MinMax aRun = (MinMax)rit.next(); int runLen = aRun.max - aRun.min + 1; if (runLen > maxSize) { maxSize = runLen; @@ -928,8 +660,8 @@ private void runsToDrain(HashMap> runsP } } if (maxRun != null) { - NodeInfo nit = nodeDefs_.get(nodeID); - nit.addDrainZone(maxRun.clone(), forShadow); + NodeInfo nit = (NodeInfo)nodeDefs_.get(nodeName); + nit.setDrainZone((MinMax)maxRun.clone(), forShadow); } } return; @@ -943,18 +675,18 @@ private void runsToDrain(HashMap> runsP private void setDrainZonesByContig(boolean withShadows) { - HashMap> runsPerNode = new HashMap>(); + HashMap runsPerNode = new HashMap(); - Iterator olit = getOrderedLinkInfo(withShadows); - Integer lastCol = Integer.valueOf(-1); + Iterator olit = getOrderedLinkInfo(withShadows); + Integer lastCol = new Integer(-1); while (olit.hasNext()) { - Integer col = olit.next(); + Integer col = (Integer)olit.next(); LinkInfo linf = getLinkDefinition(col, withShadows); - NID.WithName topNodeID = rowToTargID_.get(Integer.valueOf(linf.topRow())); - updateContigs(topNodeID, runsPerNode, lastCol, col); + String topNodeName = (String)rowToTarg_.get(new Integer(linf.topRow())); + updateContigs(topNodeName, runsPerNode, lastCol, col); if (withShadows && linf.isShadow()) { - NID.WithName botNodeID = rowToTargID_.get(Integer.valueOf(linf.bottomRow())); - updateContigs(botNodeID, runsPerNode, lastCol, col); + String botNodeName = (String)rowToTarg_.get(new Integer(linf.bottomRow())); + updateContigs(botNodeName, runsPerNode, lastCol, col); } lastCol = col; } @@ -984,28 +716,57 @@ public void writeXML(PrintWriter out, Indenter ind) { // Dump the nodes, then the links: // - Iterator r2tit = (new TreeSet(rowToTargID_.keySet())).iterator(); + Iterator r2tit = (new TreeSet(rowToTarg_.keySet())).iterator(); ind.indent(); out.println(""); ind.up(); while (r2tit.hasNext()) { - Integer row = r2tit.next(); - NID.WithName nodeID = rowToTargID_.get(row); - NodeInfo ni = getNodeDefinition(nodeID); - ni.writeXML(out, ind, row.intValue()); + Integer row = (Integer)r2tit.next(); + String targ = (String)rowToTarg_.get(row); + NodeInfo ni = getNodeDefinition(targ); + ind.indent(); + out.print(""); } ind.down().indent(); out.println(""); if (!linkGrouping_.isEmpty()) { - Iterator lgit = linkGrouping_.iterator(); + Iterator lgit = linkGrouping_.iterator(); ind.indent(); - out.print(""); + out.println(""); ind.up(); while (lgit.hasNext()) { - String grpTag = lgit.next(); + String grpTag = (String)lgit.next(); ind.indent(); out.print(""); } - HashMap inverse = new HashMap(); - Iterator nsit = nonShadowedLinkMap_.keySet().iterator(); + HashMap inverse = new HashMap(); + Iterator nsit = nonShadowedLinkMap_.keySet().iterator(); while (nsit.hasNext()) { - Integer key = nsit.next(); + Integer key = (Integer)nsit.next(); inverse.put(nonShadowedLinkMap_.get(key), key); } - Iterator ldit = fullLinkDefs_.keySet().iterator(); + Iterator ldit = fullLinkDefs_.keySet().iterator(); ind.indent(); out.println(""); ind.up(); while (ldit.hasNext()) { - Integer col = ldit.next(); + Integer col = (Integer)ldit.next(); LinkInfo li = getLinkDefinition(col, true); FabricLink link = li.getLink(); ind.indent(); - out.print(" r2tit = new TreeSet(rowToTargID_.keySet()).iterator(); + Iterator r2tit = new TreeSet(rowToTarg_.keySet()).iterator(); while (r2tit.hasNext()) { - Integer row = r2tit.next(); - NID.WithName nodeID = rowToTargID_.get(row); - NodeInfo ni = getNodeDefinition(nodeID); - out.print(ni.getNodeName()); + Integer row = (Integer)r2tit.next(); + String targ = (String)rowToTarg_.get(row); + out.print(targ); out.print(" = "); out.println(row); } @@ -1091,12 +851,12 @@ public void writeNOA(PrintWriter out) { public void writeEDA(PrintWriter out) { out.println("Link Column"); - Iterator ldit = fullLinkDefs_.keySet().iterator(); + Iterator ldit = fullLinkDefs_.keySet().iterator(); while (ldit.hasNext()) { - Integer col = ldit.next(); + Integer col = (Integer)ldit.next(); LinkInfo li = getLinkDefinition(col, true); FabricLink link = li.getLink(); - out.print(link.toEOAString(nodeDefs_)); + out.print(link.toEOAString()); out.print(" = "); out.println(col); } @@ -1108,8 +868,8 @@ public void writeEDA(PrintWriter out) { ** Get Node Definition */ - public NodeInfo getNodeDefinition(NID.WithName targID) { - NodeInfo node = nodeDefs_.get(targID); + public NodeInfo getNodeDefinition(String targ) { + NodeInfo node = (NodeInfo)nodeDefs_.get(targ); return (node); } @@ -1121,11 +881,11 @@ public NodeInfo getNodeDefinition(NID.WithName targID) { public LinkInfo getLinkDefinition(Integer colObj, boolean forShadow) { if (forShadow) { - return (fullLinkDefs_.get(colObj)); + return ((LinkInfo)fullLinkDefs_.get(colObj)); } else { - Integer mapped = nonShadowedLinkMap_.get(colObj); + Integer mapped = (Integer)nonShadowedLinkMap_.get(colObj); if (mapped != null) { - return (fullLinkDefs_.get(mapped)); + return ((LinkInfo)fullLinkDefs_.get(mapped)); } else { return (null); } @@ -1137,9 +897,9 @@ public LinkInfo getLinkDefinition(Integer colObj, boolean forShadow) { ** Get Target For Column */ - public NID.WithName getTargetIDForColumn(Integer colVal, boolean forShadow) { + public String getTargetForColumn(Integer colVal, boolean forShadow) { ColumnAssign useCA = (forShadow) ? shadowCols_ : normalCols_; - NID.WithName target = useCA.columnToTarget.get(colVal); + String target = (String)useCA.columnToTarget.get(colVal); return (target); } @@ -1148,32 +908,29 @@ public NID.WithName getTargetIDForColumn(Integer colVal, boolean forShadow) { ** Get Drain zone For Column */ - public NID.WithName getDrainForColumn(Integer colVal, boolean forShadow) { - /* + public String getDrainForColumn(Integer colVal, boolean forShadow) { int col = colVal.intValue(); ColumnAssign useCA = (forShadow) ? shadowCols_ : normalCols_; - NID.WithName targetID = useCA.columnToTarget.get(colVal); - NID.WithName sourceID = useCA.columnToSource.get(colVal); - if (targetID != null) { - NodeInfo nit = nodeDefs_.get(targetID); + String target = (String)useCA.columnToTarget.get(colVal); + String source = (String)useCA.columnToSource.get(colVal); + if (target != null) { + NodeInfo nit = (NodeInfo)nodeDefs_.get(target); MinMax tdz = nit.getDrainZone(forShadow); if (tdz != null) { if ((col >= tdz.min) && (col <= tdz.max)) { - return (targetID); + return (target); } } } - if (sourceID != null) { - NodeInfo nis = nodeDefs_.get(sourceID); + if (source != null) { + NodeInfo nis = (NodeInfo)nodeDefs_.get(source); MinMax sdz = nis.getDrainZone(forShadow); if (sdz != null) { if ((col >= sdz.min) && (col <= sdz.max)) { - return (sourceID); + return (source); } } } - */ - UiUtil.fixMePrintout("THIS NEEDS TO BE IMPLEMENTED"); return (null); } @@ -1182,9 +939,9 @@ public NID.WithName getDrainForColumn(Integer colVal, boolean forShadow) { ** Get Source For Column */ - public NID.WithName getSourceIDForColumn(Integer colVal, boolean forShadow) { + public String getSourceForColumn(Integer colVal, boolean forShadow) { ColumnAssign useCA = (forShadow) ? shadowCols_ : normalCols_; - NID.WithName source = useCA.columnToSource.get(colVal); + String source = (String)useCA.columnToSource.get(colVal); return (source); } @@ -1193,8 +950,8 @@ public NID.WithName getSourceIDForColumn(Integer colVal, boolean forShadow) { ** Get node for row */ - public NID.WithName getNodeIDForRow(Integer rowObj) { - NID.WithName node = rowToTargID_.get(rowObj); + public String getNodeForRow(Integer rowObj) { + String node = (String)rowToTarg_.get(rowObj); return (node); } @@ -1231,8 +988,8 @@ public int getRowCount() { ** Get node defs */ - public List getNodeDefList() { - return (new ArrayList(nodeDefs_.values())); + public List getNodeDefList() { + return (new ArrayList(nodeDefs_.values())); } /*************************************************************************** @@ -1240,14 +997,8 @@ public List getNodeDefList() { ** Get all node names */ - public Set getNodeSetIDs() { - HashSet retval = new HashSet(); - Iterator nsit = nodeDefs_.values().iterator(); - while (nsit.hasNext()) { - NodeInfo ni = nsit.next(); - retval.add(new NID.WithName(ni.getNodeID(), ni.getNodeName())); - } - return (retval); + public Set getNodeSet() { + return (new HashSet(nodeDefs_.keySet())); } /*************************************************************************** @@ -1255,52 +1006,33 @@ public Set getNodeSetIDs() { ** Get link defs */ - public List getLinkDefList(boolean forShadow) { + public List getLinkDefList(boolean forShadow) { if (forShadow) { - return (new ArrayList(fullLinkDefs_.values())); + return (new ArrayList(fullLinkDefs_.values())); } else { - ArrayList retval = new ArrayList(); - Iterator nsit = nonShadowedLinkMap_.keySet().iterator(); + ArrayList retval = new ArrayList(); + Iterator nsit = nonShadowedLinkMap_.keySet().iterator(); while (nsit.hasNext()) { - Integer linkID = nsit.next(); - Integer mappedID = nonShadowedLinkMap_.get(linkID); + Integer linkID = (Integer)nsit.next(); + Integer mappedID = (Integer)nonShadowedLinkMap_.get(linkID); retval.add(fullLinkDefs_.get(mappedID)); } return (retval); } } - /*************************************************************************** - ** - ** Set Layout Mode (PER_NODE or PER_NETWORK) - */ - - public void setLayoutMode(LayoutMode mode) { - layoutMode_ = mode; - } - - /*************************************************************************** - ** - ** Get Layout Mode (PER_NODE or PER_NETWORK) - */ - - public LayoutMode getLayoutMode() { - return layoutMode_; - } - /*************************************************************************** ** ** Get node matches */ - public Set nodeMatches(boolean fullMatch, String searchString) { - HashSet retval = new HashSet(); - Iterator nkit = nodeDefs_.keySet().iterator(); + public Set nodeMatches(boolean fullMatch, String searchString) { + HashSet retval = new HashSet(); + Iterator nkit = nodeDefs_.keySet().iterator(); while (nkit.hasNext()) { - NID.WithName nodeID = nkit.next(); - String nodeName = nodeDefs_.get(nodeID).getNodeName(); + String nodeName = (String)nkit.next(); if (matches(searchString, nodeName, fullMatch)) { - retval.add(nodeID); + retval.add(nodeName); } } return (retval); @@ -1311,22 +1043,22 @@ public Set nodeMatches(boolean fullMatch, String searchString) { ** Get first neighbors of node, along with info blocks */ - public void getFirstNeighbors(NID.WithName nodeID, Set nodeSet, List nodes, List links) { - Iterator ldit = fullLinkDefs_.values().iterator(); + public void getFirstNeighbors(String nodeName, Set nodeSet, List nodes, List links) { + Iterator ldit = fullLinkDefs_.values().iterator(); while (ldit.hasNext()) { - LinkInfo linf = ldit.next(); - if (linf.getSource().equals(nodeID)) { + LinkInfo linf = (LinkInfo)ldit.next(); + if (linf.getSource().equals(nodeName)) { nodeSet.add(linf.getTarget()); links.add(linf); - } else if (linf.getTarget().equals(nodeID)) { + } else if (linf.getTarget().equals(nodeName)) { nodeSet.add(linf.getSource()); links.add(linf); } } - Iterator nsit = nodeSet.iterator(); + Iterator nsit = nodeSet.iterator(); while (nsit.hasNext()) { - NID.WithName nextID = nsit.next(); - nodes.add(nodeDefs_.get(nextID)); + String name = (String)nsit.next(); + nodes.add(nodeDefs_.get(name)); } return; } @@ -1336,14 +1068,14 @@ public void getFirstNeighbors(NID.WithName nodeID, Set nodeSet, Li ** Get first neighbors of node */ - public Set getFirstNeighbors(NID.WithName nodeID) { - HashSet nodeSet = new HashSet(); - Iterator ldit = fullLinkDefs_.values().iterator(); + public Set getFirstNeighbors(String nodeName) { + HashSet nodeSet = new HashSet(); + Iterator ldit = fullLinkDefs_.values().iterator(); while (ldit.hasNext()) { - LinkInfo linf = ldit.next(); - if (linf.getSource().equals(nodeID)) { + LinkInfo linf = (LinkInfo)ldit.next(); + if (linf.getSource().equals(nodeName)) { nodeSet.add(linf.getTarget()); - } else if (linf.getTarget().equals(nodeID)) { + } else if (linf.getTarget().equals(nodeName)) { nodeSet.add(linf.getSource()); } } @@ -1355,22 +1087,22 @@ public Set getFirstNeighbors(NID.WithName nodeID) { ** Add first neighbors of node set */ - public void addFirstNeighbors(Set nodeSet, Set columnSet, Set linkSet, boolean forShadow) { - HashSet newNodes = new HashSet(); - Iterator ldit = fullLinkDefs_.values().iterator(); + public void addFirstNeighbors(Set nodeSet, Set columnSet, Set linkSet, boolean forShadow) { + HashSet newNodes = new HashSet(); + Iterator ldit = fullLinkDefs_.values().iterator(); while (ldit.hasNext()) { - LinkInfo linf = ldit.next(); + LinkInfo linf = (LinkInfo)ldit.next(); if (!forShadow && linf.isShadow()) { continue; } if (nodeSet.contains(linf.getSource())) { newNodes.add(linf.getTarget()); - columnSet.add(Integer.valueOf(linf.getUseColumn(forShadow))); + columnSet.add(new Integer(linf.getUseColumn(forShadow))); linkSet.add(linf.getLink()); } if (nodeSet.contains(linf.getTarget())) { newNodes.add(linf.getSource()); - columnSet.add(Integer.valueOf(linf.getUseColumn(forShadow))); + columnSet.add(new Integer(linf.getUseColumn(forShadow))); linkSet.add(linf.getLink()); } } @@ -1393,32 +1125,33 @@ private boolean matches(String searchString, String nodeName, boolean isFull) { } } + /*************************************************************************** ** ** Count of links per targ: */ - private Map linkCountPerTarg(Set targets, List linkList) { - HashMap retval = new HashMap(); - Iterator lcit = linkList.iterator(); + private Map linkCountPerTarg(Set targets, List linkList) { + HashMap retval = new HashMap(); + Iterator lcit = linkList.iterator(); while (lcit.hasNext()) { - LinkInfo linf = lcit.next(); - NID.WithName src = linf.getSource(); - NID.WithName trg = linf.getTarget(); + LinkInfo linf = (LinkInfo)lcit.next(); + String src = linf.getSource(); + String trg = linf.getTarget(); if (targets.contains(src)) { - Integer count = retval.get(src); + Integer count = (Integer)retval.get(src); if (count == null) { - retval.put(src, Integer.valueOf(1)); + retval.put(src, new Integer(1)); } else { - retval.put(src, Integer.valueOf(count.intValue() + 1)); + retval.put(src, new Integer(count.intValue() + 1)); } } if (!src.equals(trg) && targets.contains(trg)) { - Integer count = retval.get(trg); + Integer count = (Integer)retval.get(trg); if (count == null) { - retval.put(trg, Integer.valueOf(1)); + retval.put(trg, new Integer(1)); } else { - retval.put(trg, Integer.valueOf(count.intValue() + 1)); + retval.put(trg, new Integer(count.intValue() + 1)); } } } @@ -1432,25 +1165,25 @@ private Map linkCountPerTarg(Set targets, L ** both endpoint drains are on display, then both will be shown. */ - private List pruneToMinSubModel(BioFabricNetwork bfn, List targetList, List linkList) { + private List pruneToMinSubModel(BioFabricNetwork bfn, List targetList, List linkList) { - HashSet targSet = new HashSet(); - Iterator tlit = targetList.iterator(); + HashSet targSet = new HashSet(); + Iterator tlit = targetList.iterator(); while (tlit.hasNext()) { - NodeInfo ninf = tlit.next(); - targSet.add(new NID.WithName(ninf.getNodeID(), ninf.getNodeName())); + NodeInfo ninf = (NodeInfo)tlit.next(); + targSet.add(ninf.nodeName); } - - Map subCounts = linkCountPerTarg(targSet, linkList); - Map fullCounts = linkCountPerTarg(bfn.getNodeSetIDs(), bfn.getLinkDefList(true)); + + Map subCounts = linkCountPerTarg(targSet, linkList); + Map fullCounts = linkCountPerTarg(bfn.getNodeSet(), bfn.getLinkDefList(true)); - HashSet skipThem = new HashSet(); - HashSet ditchThem = new HashSet(); - Iterator lcit = linkList.iterator(); + HashSet skipThem = new HashSet(); + HashSet ditchThem = new HashSet(); + Iterator lcit = linkList.iterator(); while (lcit.hasNext()) { - LinkInfo linf = lcit.next(); - NID.WithName topNode = bfn.getNodeIDForRow(Integer.valueOf(linf.topRow())); - NID.WithName botNode = bfn.getNodeIDForRow(Integer.valueOf(linf.bottomRow())); + LinkInfo linf = (LinkInfo)lcit.next(); + String topNode = (String)bfn.getNodeForRow(new Integer(linf.topRow())); + String botNode = (String)bfn.getNodeForRow(new Integer(linf.bottomRow())); boolean topStays = subCounts.get(topNode).equals(fullCounts.get(topNode)); boolean botStays = subCounts.get(botNode).equals(fullCounts.get(botNode)); if ((topStays && botStays) || (!topStays && !botStays)) { // Nobody gets ditched! @@ -1458,29 +1191,29 @@ private List pruneToMinSubModel(BioFabricNetwork bfn, List t } FabricLink link1 = linf.getLink(); int col1 = linf.getUseColumn(true); - skipThem.add(Integer.valueOf(col1)); - Iterator lc2it = linkList.iterator(); + skipThem.add(new Integer(col1)); + Iterator lc2it = linkList.iterator(); while (lc2it.hasNext()) { - LinkInfo linf2 = lc2it.next(); + LinkInfo linf2 = (LinkInfo)lc2it.next(); int col2 = linf2.getUseColumn(true); - if (skipThem.contains(Integer.valueOf(col2))) { + if (skipThem.contains(new Integer(col2))) { continue; } if (linf2.getLink().shadowPair(link1)) { // got a shadow pair! int maxLink = Math.max(col1, col2); int minLink = Math.min(col1, col2); - ditchThem.add(Integer.valueOf((topStays) ? maxLink : minLink)); + ditchThem.add(new Integer((topStays) ? maxLink : minLink)); break; } } } - ArrayList retval = new ArrayList(); - Iterator lcit3 = linkList.iterator(); + ArrayList retval = new ArrayList(); + Iterator lcit3 = linkList.iterator(); while (lcit3.hasNext()) { - LinkInfo linf = lcit3.next(); + LinkInfo linf = (LinkInfo)lcit3.next(); int col = linf.getUseColumn(true); - if (!ditchThem.contains(Integer.valueOf(col))) { + if (!ditchThem.contains(new Integer(col))) { retval.add(linf); } } @@ -1492,35 +1225,35 @@ private List pruneToMinSubModel(BioFabricNetwork bfn, List t ** Fill out model with submodel data */ - private void fillSubModel(BioFabricNetwork bfn, List targetList, List linkList) { + private void fillSubModel(BioFabricNetwork bfn, List targetList, List linkList) { boolean doPrune = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getMinShadowSubmodelLinks(); if (doPrune) { linkList = pruneToMinSubModel(bfn, targetList, linkList); } - HashMap lastColForNode = new HashMap(); - HashMap lastShadColForNode = new HashMap(); - Iterator lcit = linkList.iterator(); + HashMap lastColForNode = new HashMap(); + HashMap lastShadColForNode = new HashMap(); + Iterator lcit = linkList.iterator(); while (lcit.hasNext()) { - LinkInfo linf = lcit.next(); + LinkInfo linf = (LinkInfo)lcit.next(); if (!linf.isShadow()) { - Integer lastCol = lastColForNode.get(linf.getTarget()); + Integer lastCol = (Integer)lastColForNode.get(linf.getTarget()); if ((lastCol == null) || (lastCol.intValue() < linf.getUseColumn(false))) { - lastColForNode.put(linf.getTarget(), Integer.valueOf(linf.getUseColumn(false))); + lastColForNode.put(linf.getTarget(), new Integer(linf.getUseColumn(false))); } - lastCol = lastColForNode.get(linf.getSource()); + lastCol = (Integer)lastColForNode.get(linf.getSource()); if ((lastCol == null) || (lastCol.intValue() < linf.getUseColumn(false))) { - lastColForNode.put(linf.getSource(), Integer.valueOf(linf.getUseColumn(false))); + lastColForNode.put(linf.getSource(), new Integer(linf.getUseColumn(false))); } } - Integer lastColShad = lastShadColForNode.get(linf.getTarget()); + Integer lastColShad = (Integer)lastShadColForNode.get(linf.getTarget()); if ((lastColShad == null) || (lastColShad.intValue() < linf.getUseColumn(true))) { - lastShadColForNode.put(linf.getTarget(), Integer.valueOf(linf.getUseColumn(true))); + lastShadColForNode.put(linf.getTarget(), new Integer(linf.getUseColumn(true))); } - lastColShad = lastShadColForNode.get(linf.getSource()); + lastColShad = (Integer)lastShadColForNode.get(linf.getSource()); if ((lastColShad == null) || (lastColShad.intValue() < linf.getUseColumn(true))) { - lastShadColForNode.put(linf.getSource(), Integer.valueOf(linf.getUseColumn(true))); + lastShadColForNode.put(linf.getSource(), new Integer(linf.getUseColumn(true))); } } @@ -1529,56 +1262,56 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< // First record the "full scale" entries: // - TreeSet needRows = new TreeSet(); - TreeSet needColumns = new TreeSet(); - TreeSet needColumnsShad = new TreeSet(); + TreeSet needRows = new TreeSet(); + TreeSet needColumns = new TreeSet(); + TreeSet needColumnsShad = new TreeSet(); - Iterator tgit = targetList.iterator(); + Iterator tgit = targetList.iterator(); while (tgit.hasNext()) { - NodeInfo targetInf = tgit.next(); - needRows.add(Integer.valueOf(targetInf.nodeRow)); - needColumns.add(Integer.valueOf(targetInf.getColRange(false).min)); - needColumnsShad.add(Integer.valueOf(targetInf.getColRange(true).min)); + NodeInfo targetInf = (NodeInfo)tgit.next(); + needRows.add(new Integer(targetInf.nodeRow)); + needColumns.add(new Integer(targetInf.getColRange(false).min)); + needColumnsShad.add(new Integer(targetInf.getColRange(true).min)); } - Iterator cit = linkList.iterator(); + Iterator cit = linkList.iterator(); while (cit.hasNext()) { - LinkInfo linf = cit.next(); - needRows.add(Integer.valueOf(linf.getStartRow())); - needRows.add(Integer.valueOf(linf.getEndRow())); + LinkInfo linf = (LinkInfo)cit.next(); + needRows.add(new Integer(linf.getStartRow())); + needRows.add(new Integer(linf.getEndRow())); if (!linf.isShadow()) { - needColumns.add(Integer.valueOf(linf.getUseColumn(false))); + needColumns.add(new Integer(linf.getUseColumn(false))); } - needColumnsShad.add(Integer.valueOf(linf.getUseColumn(true))); + needColumnsShad.add(new Integer(linf.getUseColumn(true))); } // // Create full-scale to mini-scale mappings: // - TreeMap rowMap = new TreeMap(); - TreeMap columnMap = new TreeMap(); - TreeMap shadColumnMap = new TreeMap(); + TreeMap rowMap = new TreeMap(); + TreeMap columnMap = new TreeMap(); + TreeMap shadColumnMap = new TreeMap(); int rowCount = 0; - Iterator mrit = needRows.iterator(); + Iterator mrit = needRows.iterator(); while (mrit.hasNext()) { - Integer fullRow = mrit.next(); - rowMap.put(fullRow, Integer.valueOf(rowCount++)); + Integer fullRow = (Integer)mrit.next(); + rowMap.put(fullRow, new Integer(rowCount++)); } int colCount = 0; - Iterator mcit = needColumns.iterator(); + Iterator mcit = needColumns.iterator(); while (mcit.hasNext()) { - Integer fullCol = mcit.next(); - columnMap.put(fullCol, Integer.valueOf(colCount++)); + Integer fullCol = (Integer)mcit.next(); + columnMap.put(fullCol, new Integer(colCount++)); } int shadColCount = 0; - Iterator ncsit = needColumnsShad.iterator(); + Iterator ncsit = needColumnsShad.iterator(); while (ncsit.hasNext()) { - Integer fullCol = ncsit.next(); - shadColumnMap.put(fullCol, Integer.valueOf(shadColCount++)); + Integer fullCol = (Integer)ncsit.next(); + shadColumnMap.put(fullCol, new Integer(shadColCount++)); } // @@ -1586,18 +1319,18 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< // compressed rows and columns: // - ArrayList modTargetList = new ArrayList(); - ArrayList modLinkList = new ArrayList(); + ArrayList modTargetList = new ArrayList(); + ArrayList modLinkList = new ArrayList(); int maxShadLinkCol = Integer.MIN_VALUE; int maxLinkCol = Integer.MIN_VALUE; cit = linkList.iterator(); while (cit.hasNext()) { - BioFabricNetwork.LinkInfo linf = cit.next(); - Integer startRowObj = rowMap.get(Integer.valueOf(linf.getStartRow())); - Integer endRowObj = rowMap.get(Integer.valueOf(linf.getEndRow())); - Integer miniColObj = (linf.isShadow()) ? Integer.valueOf(Integer.MIN_VALUE) : columnMap.get(Integer.valueOf(linf.getUseColumn(false))); - Integer miniColShadObj = shadColumnMap.get(Integer.valueOf(linf.getUseColumn(true))); + BioFabricNetwork.LinkInfo linf = (BioFabricNetwork.LinkInfo)cit.next(); + Integer startRowObj = (Integer)rowMap.get(new Integer(linf.getStartRow())); + Integer endRowObj = (Integer)rowMap.get(new Integer(linf.getEndRow())); + Integer miniColObj = (linf.isShadow()) ? new Integer(Integer.MIN_VALUE) : (Integer)columnMap.get(new Integer(linf.getUseColumn(false))); + Integer miniColShadObj = (Integer)shadColumnMap.get(new Integer(linf.getUseColumn(true))); int miniColVal = miniColObj.intValue(); if (miniColVal > maxLinkCol) { maxLinkCol = miniColVal; @@ -1607,8 +1340,8 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< maxShadLinkCol = miniColShadVal; } - LinkInfo miniLinf = new LinkInfo(linf.getLink(), startRowObj.intValue(), endRowObj.intValue(), - miniColObj.intValue(), miniColShadObj.intValue(), linf.getColorKey()); + BioFabricNetwork.LinkInfo miniLinf = new BioFabricNetwork.LinkInfo(linf.getLink(), startRowObj.intValue(), endRowObj.intValue(), + miniColObj.intValue(), miniColShadObj.intValue(), linf.getColorKey()); modLinkList.add(miniLinf); } if (maxLinkCol == Integer.MIN_VALUE) { @@ -1626,18 +1359,18 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< int minShadTrgCol = Integer.MAX_VALUE; tgit = targetList.iterator(); while (tgit.hasNext()) { - NodeInfo infoFull = tgit.next(); - Integer miniRowObj = rowMap.get(Integer.valueOf(infoFull.nodeRow)); - NodeInfo infoMini = new NodeInfo(infoFull.getNodeID(), infoFull.getNodeName(), miniRowObj.intValue(), infoFull.colorKey); + BioFabricNetwork.NodeInfo infoFull = (BioFabricNetwork.NodeInfo)tgit.next(); + Integer miniRowObj = (Integer)rowMap.get(new Integer(infoFull.nodeRow)); + BioFabricNetwork.NodeInfo infoMini = new BioFabricNetwork.NodeInfo(infoFull.nodeName, miniRowObj.intValue(), infoFull.colorKey); - Integer minCol = columnMap.get(Integer.valueOf(infoFull.getColRange(false).min)); + Integer minCol = (Integer)columnMap.get(new Integer(infoFull.getColRange(false).min)); infoMini.updateMinMaxCol(minCol.intValue(), false); int miniColVal = minCol.intValue(); if (miniColVal < minTrgCol) { minTrgCol = miniColVal; } - Integer minShadCol = shadColumnMap.get(Integer.valueOf(infoFull.getColRange(true).min)); + Integer minShadCol = (Integer)shadColumnMap.get(new Integer(infoFull.getColRange(true).min)); infoMini.updateMinMaxCol(minShadCol.intValue(), true); int miniShadColVal = minShadCol.intValue(); if (miniShadColVal < minShadTrgCol) { @@ -1645,21 +1378,21 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< } int maxCol; - Integer lastCol = lastColForNode.get(infoFull.getNodeID()); + Integer lastCol = (Integer)lastColForNode.get(infoFull.nodeName); if (lastCol == null) { maxCol = maxLinkCol; } else { - Integer maxColObj = columnMap.get(lastCol); + Integer maxColObj = (Integer)columnMap.get(lastCol); maxCol = maxColObj.intValue(); } infoMini.updateMinMaxCol(maxCol, false); int maxShadCol; - Integer lastShadCol = lastShadColForNode.get(infoFull.getNodeID()); + Integer lastShadCol = (Integer)lastShadColForNode.get(infoFull.nodeName); if (lastShadCol == null) { maxShadCol = maxShadLinkCol; } else { - Integer maxShadColObj = shadColumnMap.get(lastShadCol); + Integer maxShadColObj = (Integer)shadColumnMap.get(lastShadCol); maxShadCol = maxShadColObj.intValue(); } infoMini.updateMinMaxCol(maxShadCol, true); @@ -1670,32 +1403,31 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< minTrgCol = 0; } - rowToTargID_ = new HashMap(); - nodeDefs_ = new HashMap(); + rowToTarg_ = new HashMap(); + nodeDefs_ = new HashMap(); rowCount_ = modTargetList.size(); for (int i = 0; i < rowCount_; i++) { - NodeInfo infoMini = modTargetList.get(i); - NID.WithName nwn = new NID.WithName(infoMini.getNodeID(), infoMini.getNodeName()); - rowToTargID_.put(Integer.valueOf(infoMini.nodeRow), nwn); - nodeDefs_.put(nwn, infoMini); + BioFabricNetwork.NodeInfo infoMini = (BioFabricNetwork.NodeInfo)modTargetList.get(i); + rowToTarg_.put(new Integer(infoMini.nodeRow), infoMini.nodeName); + nodeDefs_.put(infoMini.nodeName, infoMini); } normalCols_ = new ColumnAssign(); shadowCols_ = new ColumnAssign(); - fullLinkDefs_ = new TreeMap(); - nonShadowedLinkMap_ = new TreeMap(); + fullLinkDefs_ = new TreeMap(); + nonShadowedLinkMap_ = new TreeMap(); int numMll = modLinkList.size(); for (int i = 0; i < numMll; i++) { - BioFabricNetwork.LinkInfo infoMini = modLinkList.get(i); + BioFabricNetwork.LinkInfo infoMini = (BioFabricNetwork.LinkInfo)modLinkList.get(i); - Integer useShadCol = Integer.valueOf(infoMini.getUseColumn(true)); + Integer useShadCol = new Integer(infoMini.getUseColumn(true)); fullLinkDefs_.put(useShadCol, infoMini); shadowCols_.columnToSource.put(useShadCol, infoMini.getSource()); shadowCols_.columnToTarget.put(useShadCol, infoMini.getTarget()); if (!infoMini.isShadow()) { - Integer useCol = Integer.valueOf(infoMini.getUseColumn(false)); + Integer useCol = new Integer(infoMini.getUseColumn(false)); nonShadowedLinkMap_.put(useCol, useShadCol); normalCols_.columnToSource.put(useCol, infoMini.getSource()); normalCols_.columnToTarget.put(useCol, infoMini.getTarget()); @@ -1718,10 +1450,10 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< // with a link has a drain zone // - Iterator ndkit = nodeDefs_.keySet().iterator(); + Iterator ndkit = nodeDefs_.keySet().iterator(); while (ndkit.hasNext()) { - NID.WithName node = ndkit.next(); - NodeInfo srcNI = nodeDefs_.get(node); + String node = (String)ndkit.next(); + NodeInfo srcNI = (NodeInfo)nodeDefs_.get(node); // // Non-shadow calcs: @@ -1731,7 +1463,7 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< int startCol = range.max; int endCol = range.min; for (int i = startCol; i >= endCol; i--) { - LinkInfo linf = getLinkDefinition(Integer.valueOf(i), false); + LinkInfo linf = (LinkInfo)getLinkDefinition(new Integer(i), false); // done when no longer contiguous: if ((linf == null) || (!linf.getSource().equals(node) && !linf.getTarget().equals(node))) { break; @@ -1749,7 +1481,7 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< } } if (srcDrain != null) { - srcNI.addDrainZone(srcDrain, false); + srcNI.setDrainZone(srcDrain, false); } // @@ -1761,7 +1493,7 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< int startColShad = shadowRange.min; int endColShad = shadowRange.max; for (int i = startColShad; i <= endColShad; i++) { - LinkInfo linf = getLinkDefinition(Integer.valueOf(i), true); + LinkInfo linf = (LinkInfo)getLinkDefinition(new Integer(i), true); if (linf == null) { continue; } @@ -1785,21 +1517,299 @@ private void fillSubModel(BioFabricNetwork bfn, List targetList, List< } } if (shadowSrcDrain != null) { - srcNI.addDrainZone(shadowSrcDrain, true); + srcNI.setDrainZone(shadowSrcDrain, true); } } return; } + /*************************************************************************** + ** + ** Calculate default node order + */ + + private List defaultNodeOrder(Set allLinks, Set loneNodes) { + // + // Note the allLinks Set has pruned out duplicates and synonymous non-directional links + // + // + // Build a target list, top to bottom, that adds the node with the most + // links first, and adds those link targets ASAP: + // + + HashMap linkCounts = new HashMap(); + HashMap targsPerSource = new HashMap(); + ArrayList targets = new ArrayList(); + + HashSet targsToGo = new HashSet(); + Iterator alit = allLinks.iterator(); + while (alit.hasNext()) { + FabricLink nextLink = (FabricLink)alit.next(); + String source = nextLink.getSrc(); + String target = nextLink.getTrg(); + HashSet targs = (HashSet)targsPerSource.get(source); + if (targs == null) { + targs = new HashSet(); + targsPerSource.put(source, targs); + } + targs.add(target); + targs = (HashSet)targsPerSource.get(target); + if (targs == null) { + targs = new HashSet(); + targsPerSource.put(target, targs); + } + targs.add(source); + targsToGo.add(source); + targsToGo.add(target); + Integer srcCount = (Integer)linkCounts.get(source); + linkCounts.put(source, (srcCount == null) ? new Integer(1) : new Integer(srcCount.intValue() + 1)); + Integer trgCount = (Integer)linkCounts.get(target); + linkCounts.put(target, (trgCount == null) ? new Integer(1) : new Integer(trgCount.intValue() + 1)); + } + + // + // Rank the nodes by link count: + // + + TreeMap countRank = new TreeMap(Collections.reverseOrder()); + Iterator lcit = linkCounts.keySet().iterator(); + while (lcit.hasNext()) { + String src = (String)lcit.next(); + Integer count = (Integer)linkCounts.get(src); + TreeSet perCount = (TreeSet)countRank.get(count); + if (perCount == null) { + perCount = new TreeSet(); + countRank.put(count, perCount); + } + perCount.add(src); + } + + // + // Get all kids added in. Now doing this without recursion; seeing blown + // stacks for huge networks! + // + + while (!targsToGo.isEmpty()) { + Iterator crit = countRank.keySet().iterator(); + while (crit.hasNext()) { + Integer key = (Integer)crit.next(); + TreeSet perCount = (TreeSet)countRank.get(key); + Iterator pcit = perCount.iterator(); + while (pcit.hasNext()) { + String node = (String)pcit.next(); + if (targsToGo.contains(node)) { + ArrayList queue = new ArrayList(); + targsToGo.remove(node); + targets.add(node); + addMyKidsNR(targets, targsPerSource, linkCounts, targsToGo, node, queue); + } + } + } + } + + // + // + // Tag on lone nodes. If a node is by itself, but also shows up in the links, + // we drop it: + // + + HashSet remains = new HashSet(loneNodes); + remains.removeAll(targets); + targets.addAll(new TreeSet(remains)); + return (targets); + } + + + /*************************************************************************** + ** + ** Process a link set + */ + + private void defaultLinkToColumn(TreeMap rankedLinks, Map relsForPair, FabricColorGenerator colGen) { + int numColors = colGen.getNumColors(); + + // + // This now assigns the link to its column. Note that we order them + // so that the shortest vertical link is drawn first! + // + + ArrayList rels = new ArrayList(linkGrouping_); + if (rels.isEmpty()) { + rels.add(""); + } + int numRel = rels.size(); + + normalCols_.columnCount = 0; + shadowCols_.columnCount = 0; + // For each top row... + for (int k = 0; k < rowCount_; k++) { + Integer topRow = new Integer(k); + int currMin = normalCols_.columnCount; + int currShadMin = shadowCols_.columnCount; + for (int i = 0; i < numRel; i++) { + String relOnly = (String)rels.get(i); + if (relOnly.equals("")) { + relOnly = null; + } + shadowLinkToColumn(topRow.intValue(), rankedLinks, relsForPair, colGen, relOnly); + TreeSet perSrc = (TreeSet)rankedLinks.get(topRow); + if (perSrc == null) { + continue; + } + Iterator psit = perSrc.iterator(); + + // Drain the bottoms rows, in increasing order... + while (psit.hasNext()) { + Integer botRow = (Integer)psit.next(); + String topNode = (String)rowToTarg_.get(topRow); + String botNode = (String)rowToTarg_.get(botRow); + // Dumping links in order of the relation sort (alphabetical)... + SortedMap forPair1 = (SortedMap)relsForPair.get(new Link(topNode, botNode)); + if (forPair1 != null) { + Iterator fp1it = forPair1.values().iterator(); + while (fp1it.hasNext()) { + FabricLink nextLink = (FabricLink)fp1it.next(); + if (!nextLink.isShadow()) { + String augR = nextLink.getAugRelation().relation; + if ((relOnly == null) || (augR.indexOf(relOnly) == (augR.length() - relOnly.length()))) { + Integer[] colAssign = addLinkDef(nextLink, numColors, normalCols_.columnCount, shadowCols_.columnCount, colGen); + if (colAssign[1] == null) { + throw new IllegalStateException(); + } + shadowCols_.columnCount = colAssign[0].intValue(); + normalCols_.columnCount = colAssign[1].intValue(); + } + } + } + } + // With directed links from above coming before directed links from below... + if (!topNode.equals(botNode)) { // DO NOT DUPLICATE FEEDBACK LINKS! + SortedMap forPair2 = (SortedMap)relsForPair.get(new Link(botNode, topNode)); + if (forPair2 != null) { + Iterator fp2it = forPair2.values().iterator(); + while (fp2it.hasNext()) { + FabricLink nextLink = (FabricLink)fp2it.next(); + if (!nextLink.isShadow()) { + String augR = nextLink.getAugRelation().relation; + if ((relOnly == null) || (augR.indexOf(relOnly) == (augR.length() - relOnly.length()))) { + Integer[] colAssign = addLinkDef(nextLink, numColors, normalCols_.columnCount, shadowCols_.columnCount, colGen); + if (colAssign[1] == null) { + throw new IllegalStateException(); + } + shadowCols_.columnCount = colAssign[0].intValue(); + normalCols_.columnCount = colAssign[1].intValue(); + } + } + } + } + } + } + } + int currMaxNorm = normalCols_.columnCount - 1; + int currMaxShad = shadowCols_.columnCount - 1; + + // + // We only have drain zones if the maximum column we are working with actually + // hosts a link to/from the row we are working with: + // + + NodeInfo srcNI = (NodeInfo)nodeDefs_.get(rowToTarg_.get(topRow)); + int topRowVal = topRow.intValue(); + LinkInfo linf = getLinkDefinition(new Integer(currMaxNorm), false); + + if ((linf != null) && (linf.topRow() == topRowVal)) { + srcNI.setDrainZone(new MinMax(currMin, currMaxNorm), false); + } + linf = getLinkDefinition(new Integer(currMaxShad), true); + if ((linf != null) && ((linf.topRow() == topRowVal) || (linf.bottomRow() == topRowVal))) { + srcNI.setDrainZone(new MinMax(currShadMin, currMaxShad), true); + } + } + return; + } + + /*************************************************************************** + ** + ** Get shadow links into their columns: + */ + private void shadowLinkToColumn(int currDrainRow, TreeMap rankedLinks, + Map relsForPair, FabricColorGenerator colGen, String relOnly) { + int numColors = colGen.getNumColors(); + + Iterator rlit = rankedLinks.keySet().iterator(); + // For each top row... + while (rlit.hasNext()) { + Integer topRow = (Integer)rlit.next(); + TreeSet perSrc = (TreeSet)rankedLinks.get(topRow); + Iterator psit = perSrc.iterator(); + // Drain ONLY the bottom row that ends on our row... + while (psit.hasNext()) { + Integer botRow = (Integer)psit.next(); + if (botRow.intValue() != currDrainRow) { + continue; + } + // We NEVER create shadow feedback links. They are insanely redundant. + if (topRow.equals(botRow)) { + continue; + } + + String topNode = (String)rowToTarg_.get(topRow); + String botNode = (String)rowToTarg_.get(botRow); + // Dumping links in order of the relation sort (alphabetical)... + SortedMap forPair1 = (SortedMap)relsForPair.get(new Link(topNode, botNode)); + if (forPair1 != null) { + Iterator fp1it = forPair1.values().iterator(); + while (fp1it.hasNext()) { + // But ONLY if they are shadow links: + FabricLink nextLink = (FabricLink)fp1it.next(); + if (nextLink.isShadow()) { + String augR = nextLink.getAugRelation().relation; + if ((relOnly == null) || (augR.indexOf(relOnly) == (augR.length() - relOnly.length()))) { + Integer[] colAssign = addLinkDef(nextLink, numColors, Integer.MIN_VALUE, shadowCols_.columnCount, colGen); + if (colAssign[1] != null) { + throw new IllegalStateException(); + } + shadowCols_.columnCount = colAssign[0].intValue(); + } + } + } + } + // With directed links from above coming before directed links from below... + // This test should now always be true, given we are never doing feedback.... + if (!topNode.equals(botNode)) { // DO NOT DUPLICATE FEEDBACK LINKS! + SortedMap forPair2 = (SortedMap)relsForPair.get(new Link(botNode, topNode)); + if (forPair2 != null) { + Iterator fp2it = forPair2.values().iterator(); + while (fp2it.hasNext()) { + FabricLink nextLink = (FabricLink)fp2it.next(); + if (nextLink.isShadow()) { + String augR = nextLink.getAugRelation().relation; + if ((relOnly == null) || (augR.indexOf(relOnly) == (augR.length() - relOnly.length()))) { + Integer[] colAssign = addLinkDef(nextLink, numColors, Integer.MIN_VALUE, shadowCols_.columnCount, colGen); + if (colAssign[1] != null) { + throw new IllegalStateException(); + } + shadowCols_.columnCount = colAssign[0].intValue(); + } + } + } + } + } else { + throw new IllegalStateException(); // Now should never get here for shadow links... + } + } + } + return; + } + /*************************************************************************** ** ** Fill out node info from order */ - private void fillNodesFromOrder(List targetIDs, - FabricColorGenerator colGen, Map clustAssign) { + private void fillNodesFromOrder(List targets, FabricColorGenerator colGen) { // // Now have the ordered list of targets we are going to display. // Build target->row maps and the inverse: @@ -1808,19 +1818,15 @@ private void fillNodesFromOrder(List targetIDs, int numColors = colGen.getNumColors(); int currRow = 0; - Iterator trit = targetIDs.iterator(); + Iterator trit = targets.iterator(); while (trit.hasNext()) { - NID.WithName targetID = trit.next(); - Integer rowObj = Integer.valueOf(currRow); - rowToTargID_.put(rowObj, targetID); - String colorKey = colGen.getGeneColor(currRow % numColors); - NodeInfo nextNI = new NodeInfo(targetID.getNID(), targetID.getName(), currRow++, colorKey); - if (clustAssign != null) { - nextNI.setCluster(clustAssign.get(targetID)); - } - nodeDefs_.put(targetID, nextNI); + String target = (String)trit.next(); + Integer rowObj = new Integer(currRow); + rowToTarg_.put(rowObj, target); + String colorKey = colGen.getGeneColor(currRow % numColors); + nodeDefs_.put(target, new NodeInfo(target, currRow++, colorKey)); } - rowCount_ = targetIDs.size(); + rowCount_ = targets.size(); return; } @@ -1830,13 +1836,79 @@ private void fillNodesFromOrder(List targetIDs, */ void addNodeInfoForIO(NodeInfo nif) { - NID.WithName nwn = new NID.WithName(nif.getNodeID(), nif.getNodeName()); - nodeDefs_.put(nwn, nif); + nodeDefs_.put(nif.nodeName, nif); rowCount_ = nodeDefs_.size(); - rowToTargID_.put(Integer.valueOf(nif.nodeRow), nwn); + rowToTarg_.put(new Integer(nif.nodeRow), nif.nodeName); return; } + /*************************************************************************** + ** + ** Generate vertical extents for links: + ** + ** Returns Map relsForPair: + ** Maps each simple source/target "Link" to sorted map + ** Sorted map maps each link relation to the associated FabricLink, ordered by + ** how the AugRelation comparator works + ** + ** Fills in empty SortedMap rankedLinks: + ** Maps each top link row to an ordered set of link maximums + */ + + private Map generateLinkExtents(Set allLinks, TreeMap rankedLinks) { + // + // Now each link is given a vertical extent. + // + + HashMap relsForPair = new HashMap(); + // HashMap directedMap = new HashMap(); + Iterator alit = allLinks.iterator(); + while (alit.hasNext()) { + FabricLink nextLink = (FabricLink)alit.next(); + String source = nextLink.getSrc(); + String target = nextLink.getTrg(); + // boolean directed = nextLink.isDirected(); + // directedMap.put(new Link(source, target), new Boolean(directed)); + Link key = new Link(source, target); + TreeMap rels = (TreeMap)relsForPair.get(key); + if (rels == null) { + rels = new TreeMap(); + relsForPair.put(key, rels); + } + rels.put(nextLink.getAugRelation(), nextLink); + int[] link = new int[2]; + NodeInfo srcInfo = (NodeInfo)nodeDefs_.get(source); + if (srcInfo == null) { + System.err.println("Bad source: " + source + " from link " + nextLink + " key " + key); + throw new IllegalStateException(); + } + NodeInfo trgInfo = (NodeInfo)nodeDefs_.get(target); + if (trgInfo == null) { + System.err.println("Bad target: " + target + " from link " + nextLink + " key " + key); + throw new IllegalStateException(); + } + link[0] = srcInfo.nodeRow; + link[1] = trgInfo.nodeRow; + int min; + int max; + if (link[0] < link[1]) { + min = link[0]; + max = link[1]; + } else { + min = link[1]; + max = link[0]; + } + Integer minObj = new Integer(min); + TreeSet perSrc = (TreeSet)rankedLinks.get(minObj); // min == node row! + if (perSrc == null) { + perSrc = new TreeSet(); + rankedLinks.put(minObj, perSrc); + } + perSrc.add(new Integer(max)); // Have the ordered set of link maxes + } + return (relsForPair); + } + /*************************************************************************** ** ** Determine the start & end of each target row needed to handle the incoming @@ -1844,26 +1916,26 @@ void addNodeInfoForIO(NodeInfo nif) { */ private void trimTargetRows() { - Iterator fldit = fullLinkDefs_.keySet().iterator(); + Iterator fldit = fullLinkDefs_.keySet().iterator(); while (fldit.hasNext()) { - Integer colNum = fldit.next(); - LinkInfo li = fullLinkDefs_.get(colNum); + Integer colNum = (Integer)fldit.next(); + LinkInfo li = (LinkInfo)fullLinkDefs_.get(colNum); shadowCols_.columnToSource.put(colNum, li.getSource()); shadowCols_.columnToTarget.put(colNum, li.getTarget()); - NodeInfo srcNI = nodeDefs_.get(li.getSource()); - NodeInfo trgNI = nodeDefs_.get(li.getTarget()); + NodeInfo srcNI = (NodeInfo)nodeDefs_.get(li.getSource()); + NodeInfo trgNI = (NodeInfo)nodeDefs_.get(li.getTarget()); srcNI.updateMinMaxCol(colNum.intValue(), true); trgNI.updateMinMaxCol(colNum.intValue(), true); } - Iterator nslit = nonShadowedLinkMap_.keySet().iterator(); + Iterator nslit = nonShadowedLinkMap_.keySet().iterator(); while (nslit.hasNext()) { - Integer colNum = nslit.next(); - Integer mappedCol = nonShadowedLinkMap_.get(colNum); - LinkInfo li = fullLinkDefs_.get(mappedCol); + Integer colNum = (Integer)nslit.next(); + Integer mappedCol = (Integer)nonShadowedLinkMap_.get(colNum); + LinkInfo li = (LinkInfo)fullLinkDefs_.get(mappedCol); normalCols_.columnToSource.put(colNum, li.getSource()); normalCols_.columnToTarget.put(colNum, li.getTarget()); - NodeInfo srcNI = nodeDefs_.get(li.getSource()); - NodeInfo trgNI = nodeDefs_.get(li.getTarget()); + NodeInfo srcNI = (NodeInfo)nodeDefs_.get(li.getSource()); + NodeInfo trgNI = (NodeInfo)nodeDefs_.get(li.getTarget()); srcNI.updateMinMaxCol(colNum.intValue(), false); trgNI.updateMinMaxCol(colNum.intValue(), false); } @@ -1875,11 +1947,11 @@ private void trimTargetRows() { ** For the lone nodes, they are assigned into the last column: */ - private void loneNodesToLastColumn(Set loneNodeIDs) { - Iterator lnit = loneNodeIDs.iterator(); + private void loneNodesToLastColumn(Set loneNodes) { + Iterator lnit = loneNodes.iterator(); while (lnit.hasNext()) { - NID.WithName loneID = lnit.next(); - NodeInfo loneNI = nodeDefs_.get(loneID); + String lone = (String)lnit.next(); + NodeInfo loneNI = (NodeInfo)nodeDefs_.get(lone); loneNI.updateMinMaxCol(normalCols_.columnCount - 1, false); loneNI.updateMinMaxCol(shadowCols_.columnCount - 1, true); } @@ -1891,25 +1963,25 @@ private void loneNodesToLastColumn(Set loneNodeIDs) { ** Pretty icky hack: */ - private Set getLoneNodes() { - HashSet retval = new HashSet(); - Iterator lnit = nodeDefs_.keySet().iterator(); + private Set getLoneNodes() { + HashSet retval = new HashSet(); + Iterator lnit = nodeDefs_.keySet().iterator(); boolean checkDone = false; while (lnit.hasNext()) { - NID.WithName loneID = lnit.next(); - NodeInfo loneNI = nodeDefs_.get(loneID); + String lone = (String)lnit.next(); + NodeInfo loneNI = (NodeInfo)nodeDefs_.get(lone); int min = loneNI.getColRange(true).min; int max = loneNI.getColRange(true).max; if ((min == max) && (min == (shadowCols_.columnCount - 1))) { if (!checkDone) { - if (shadowCols_.columnToSource.get(Integer.valueOf(min)) != null) { + if (shadowCols_.columnToSource.get(new Integer(min)) != null) { return (retval); } else { checkDone = true; } } - retval.add(loneID); + retval.add(loneNI.nodeName); } } return (retval); @@ -1925,15 +1997,15 @@ private Set getLoneNodes() { private Integer[] addLinkDef(FabricLink nextLink, int numColors, int noShadowCol, int shadowCol, FabricColorGenerator colGen) { Integer[] retval = new Integer[2]; String key = colGen.getGeneColor(shadowCol % numColors); - int srcRow = nodeDefs_.get(nextLink.getSrcID()).nodeRow; - int trgRow = nodeDefs_.get(nextLink.getTrgID()).nodeRow; + int srcRow = ((NodeInfo)nodeDefs_.get(nextLink.getSrc())).nodeRow; + int trgRow = ((NodeInfo)nodeDefs_.get(nextLink.getTrg())).nodeRow; LinkInfo linf = new LinkInfo(nextLink, srcRow, trgRow, noShadowCol, shadowCol, key); - Integer shadowKey = Integer.valueOf(shadowCol); + Integer shadowKey = new Integer(shadowCol); fullLinkDefs_.put(shadowKey, linf); - retval[0] = Integer.valueOf(shadowCol + 1); + retval[0] = new Integer(shadowCol + 1); if (!linf.isShadow()) { - nonShadowedLinkMap_.put(Integer.valueOf(noShadowCol), shadowKey); - retval[1] = Integer.valueOf(noShadowCol + 1); + nonShadowedLinkMap_.put(new Integer(noShadowCol), shadowKey); + retval[1] = new Integer(noShadowCol + 1); } return (retval); } @@ -1945,7 +2017,7 @@ private Integer[] addLinkDef(FabricLink nextLink, int numColors, int noShadowCol void addLinkInfoForIO(LinkInfo linf) { int useColVal = linf.getUseColumn(true); - Integer useCol = Integer.valueOf(useColVal); + Integer useCol = new Integer(useColVal); fullLinkDefs_.put(useCol, linf); if (useColVal > shadowCols_.columnCount) { shadowCols_.columnCount = useColVal; @@ -1955,7 +2027,7 @@ void addLinkInfoForIO(LinkInfo linf) { if (!linf.isShadow()) { int useNColVal = linf.getUseColumn(false); - Integer useNCol = Integer.valueOf(useNColVal); + Integer useNCol = new Integer(useNColVal); nonShadowedLinkMap_.put(useNCol, useCol); if (useNColVal > normalCols_.columnCount) { normalCols_.columnCount = useNColVal; @@ -1978,64 +2050,70 @@ void addLinkGroupForIO(String tag) { /*************************************************************************** ** - ** Set color generator (I/0) - */ - - void setColorGenerator(FabricColorGenerator fcg) { - colGen_ = fcg; - return; - } - - /*************************************************************************** - ** - ** Answer if we have node cluster assignments + ** Node ordering */ - public boolean nodeClustersAssigned() { - if (nodeDefs_.isEmpty()) { - return (false); - } - NodeInfo ni = nodeDefs_.values().iterator().next(); - return (ni.getCluster() != null); - } + private ArrayList orderMyKids(Map targsPerSource, Map linkCounts, HashSet targsToGo, String node) { + HashSet targs = (HashSet)targsPerSource.get(node); + TreeMap kidMap = new TreeMap(Collections.reverseOrder()); + Iterator tait = targs.iterator(); + while (tait.hasNext()) { + String nextTarg = (String)tait.next(); + Integer count = (Integer)linkCounts.get(nextTarg); + TreeSet perCount = (TreeSet)kidMap.get(count); + if (perCount == null) { + perCount = new TreeSet(); + kidMap.put(count, perCount); + } + perCount.add(nextTarg); + } + + ArrayList myKidsToProc = new ArrayList(); + Iterator kmit = kidMap.values().iterator(); + while (kmit.hasNext()) { + TreeSet perCount = (TreeSet)kmit.next(); + Iterator pcit = perCount.iterator(); + while (pcit.hasNext()) { + String kid = (String)pcit.next(); + if (targsToGo.contains(kid)) { + myKidsToProc.add(kid); + } + } + } + return (myKidsToProc); + } /*************************************************************************** ** - ** Return node cluster assignment + ** Node ordering, non-recursive: */ - public Map nodeClusterAssigment() { - HashMap retval = new HashMap(); - if (nodeDefs_.isEmpty()) { - return (retval); - } - for (NodeInfo ni : nodeDefs_.values()) { - String cluster = ni.getCluster(); - if (cluster == null) { - throw new IllegalStateException(); - } - retval.put(new NID.WithName(ni.getNodeID(), ni.getNodeName()), cluster); - } - return (retval); - } - + private void addMyKidsNR(ArrayList targets, Map targsPerSource, Map linkCounts, HashSet targsToGo, String node, ArrayList queue) { + queue.add(node); + while (!queue.isEmpty()) { + node = (String)queue.remove(0); + ArrayList myKids = orderMyKids(targsPerSource, linkCounts, targsToGo, node); + Iterator ktpit = myKids.iterator(); + while (ktpit.hasNext()) { + String kid = (String)ktpit.next(); + if (targsToGo.contains(kid)) { + targsToGo.remove(kid); + targets.add(kid); + queue.add(kid); + } + } + } + return; + } + /*************************************************************************** ** - ** Set node cluster assignment + ** Set color generator (I/0) */ - public void setNodeClusterAssigment(Map assign) { - if (nodeDefs_.isEmpty()) { - throw new IllegalStateException(); - } - for (NodeInfo ni : nodeDefs_.values()) { - String cluster = assign.get(ni.getNodeID()); - if (cluster == null) { - throw new IllegalArgumentException(); - } - ni.setCluster(cluster); - } - return; + void setColorGenerator(FabricColorGenerator fcg) { + colGen_ = fcg; + return; } /*************************************************************************** @@ -2046,11 +2124,11 @@ public void setNodeClusterAssigment(Map assign) { BioFabricNetwork() { normalCols_ = new ColumnAssign(); shadowCols_ = new ColumnAssign(); - rowToTargID_ = new HashMap(); - fullLinkDefs_ = new TreeMap(); - nonShadowedLinkMap_ = new TreeMap(); - nodeDefs_ = new HashMap(); - linkGrouping_ = new ArrayList(); + rowToTarg_ = new HashMap(); + fullLinkDefs_ = new TreeMap(); + nonShadowedLinkMap_ = new TreeMap(); + nodeDefs_ = new HashMap(); + linkGrouping_ = new ArrayList(); colGen_ = null; } @@ -2067,8 +2145,8 @@ public static class LinkInfo { private int shadowColumn_; private String colorKey_; - public LinkInfo(FabricLink flink, int startRow, int endRow, int noShadowColumn, int shadowColumn, String colorKey) { - myLink_ = flink.clone(); + LinkInfo(FabricLink flink, int startRow, int endRow, int noShadowColumn, int shadowColumn, String colorKey) { + myLink_ = (FabricLink)flink.clone(); startRow_ = startRow; endRow_ = endRow; noShadowColumn_ = noShadowColumn; @@ -2076,15 +2154,15 @@ public LinkInfo(FabricLink flink, int startRow, int endRow, int noShadowColumn, colorKey_ = colorKey; } - public int getStartRow() { + int getStartRow() { return (startRow_); } - public int getEndRow() { + int getEndRow() { return (endRow_); } - public int getUseColumn(boolean shadowEnabled) { + int getUseColumn(boolean shadowEnabled) { if (!shadowEnabled && myLink_.isShadow()) { // FIX ME: Seen this case with submodel creation? throw new IllegalStateException(); @@ -2092,39 +2170,39 @@ public int getUseColumn(boolean shadowEnabled) { return ((shadowEnabled) ? shadowColumn_ : noShadowColumn_); } - public String getColorKey() { + String getColorKey() { return (colorKey_); } - public FabricLink getLink() { + FabricLink getLink() { return (myLink_); } - public NID.WithName getSource() { - return (myLink_.getSrcID()); + String getSource() { + return (myLink_.getSrc()); } - public NID.WithName getTarget() { - return (myLink_.getTrgID()); + String getTarget() { + return (myLink_.getTrg()); } - public FabricLink.AugRelation getAugRelation() { + FabricLink.AugRelation getAugRelation() { return (myLink_.getAugRelation()); } - public boolean isShadow() { + boolean isShadow() { return (myLink_.isShadow()); } - public boolean isDirected() { + boolean isDirected() { return (myLink_.isDirected()); } - public int bottomRow() { + int bottomRow() { return (Math.max(startRow_, endRow_)); } - public int topRow() { + int topRow() { return (Math.min(startRow_, endRow_)); } @@ -2139,66 +2217,41 @@ public boolean inLinkRowRange(int row) { */ public static class NodeInfo { - private NID nodeID_; - private String nodeName_; + public String nodeName; public int nodeRow; public String colorKey; - private String cluster_; private MinMax colRangeSha_; private MinMax colRangePln_; + private MinMax plainDrainZone_; + private MinMax shadowDrainZone_; - private List shadowDrainZones_; - private List plainDrainZones_; - - NodeInfo(NID nodeID, String nodeName, int nodeRow, String colorKey) { - nodeID_ = nodeID; - nodeName_ = nodeName; + NodeInfo(String nodeName, int nodeRow, String colorKey) { + this.nodeName = nodeName; this.nodeRow = nodeRow; this.colorKey = colorKey; colRangeSha_ = new MinMax(); colRangeSha_.init(); colRangePln_ = new MinMax(); colRangePln_.init(); - shadowDrainZones_ = new ArrayList(); - cluster_ = null; - plainDrainZones_ = new ArrayList(); + plainDrainZone_ = null; + shadowDrainZone_ = null; } - - public String getNodeName() { - return (nodeName_); - } - - public NID getNodeID() { - return (nodeID_); - } - public NID.WithName getNodeIDWithName() { - return (new NID.WithName(nodeID_, nodeName_)); - } - - public List getDrainZones(boolean forShadow) { - return (forShadow) ? new ArrayList(shadowDrainZones_) : new ArrayList(plainDrainZones_); + MinMax getDrainZone(boolean forShadow) { + return (forShadow) ? shadowDrainZone_ : plainDrainZone_; } - public void addDrainZone(MinMax zone, boolean forShadow) { + void setDrainZone(MinMax zone, boolean forShadow) { if (forShadow) { - shadowDrainZones_.add(zone); + shadowDrainZone_ = zone; } else { - plainDrainZones_.add(zone); + plainDrainZone_ = zone; } return; } - public void setDrainZones(List zones, boolean forShadow) { - if (forShadow) { - shadowDrainZones_ = new ArrayList(zones); - } else { - plainDrainZones_ = new ArrayList(zones); - } - } - - public MinMax getColRange(boolean forShadow) { + MinMax getColRange(boolean forShadow) { return (forShadow) ? colRangeSha_ : colRangePln_; } @@ -2207,65 +2260,6 @@ void updateMinMaxCol(int i, boolean forShadow) { useMM.update(i); return; } - - public void setCluster(String cluster) { - cluster_ = cluster; - return; - } - - public String getCluster() { - return (cluster_); - } - - /*************************************************************************** - ** - ** Dump the node using XML ; XML DOESN'T FUNCTION PROPERLY HERE!!!- RISHI - * CAME BACK HERE 1/7/16 - */ - - public void writeXML(PrintWriter out, Indenter ind, int row) { - ind.indent(); - out.print(""); - } } /*************************************************************************** @@ -2274,13 +2268,13 @@ public void writeXML(PrintWriter out, Indenter ind, int row) { */ public static abstract class BuildData { - protected BuildMode mode; + protected int mode; - public BuildData(BuildMode mode) { + public BuildData(int mode) { this.mode = mode; } - public BuildMode getMode() { + public int getMode() { return (mode); } @@ -2297,7 +2291,7 @@ public boolean canRestore() { public static class PreBuiltBuildData extends BuildData { BioFabricNetwork bfn; - public PreBuiltBuildData(BioFabricNetwork bfn, BuildMode mode) { + public PreBuiltBuildData(BioFabricNetwork bfn, int mode) { super(mode); this.bfn = bfn; } @@ -2308,108 +2302,63 @@ public PreBuiltBuildData(BioFabricNetwork bfn, BuildMode mode) { ** For passing around build data */ + public static class OrigBuildData extends BuildData { + Set allLinks; + Set loneNodes; + FabricColorGenerator colGen; + + public OrigBuildData(Set allLinks, Set loneNodes, FabricColorGenerator colGen, int mode) { + super(mode); + this.allLinks = allLinks; + this.loneNodes = loneNodes; + this.colGen = colGen; + } + } + + /*************************************************************************** + ** + ** For passing around build data + */ + public static class RelayoutBuildData extends BuildData { - public BioFabricNetwork bfn; - public Set allLinks; - public Set loneNodeIDs; - public FabricColorGenerator colGen; - public Map nodeOrder; - public List existingIDOrder; - public SortedMap linkOrder; - public List linkGroups; - public Set allNodeIDs; - public Map clustAssign; - public LayoutMode layoutMode; - public UniqueLabeller idGen; - - public RelayoutBuildData(BioFabricNetwork fullNet, BuildMode mode) { + BioFabricNetwork bfn; + Set allLinks; + Set loneNodes; + FabricColorGenerator colGen; + Map nodeOrder; + List existingOrder; + SortedMap linkOrder; + List existingLinkGroups; + List newLinkGroups; + Set allNodes; + + public RelayoutBuildData(BioFabricNetwork fullNet, int mode) { super(mode); this.bfn = fullNet; this.allLinks = fullNet.getAllLinks(true); this.colGen = fullNet.colGen_; this.nodeOrder = null; - this.existingIDOrder = fullNet.existingIDOrder(); - this.linkOrder = null; - this.linkGroups = fullNet.linkGrouping_; - this.loneNodeIDs = fullNet.getLoneNodes(); - this.allNodeIDs = fullNet.nodeDefs_.keySet(); - this.clustAssign = (fullNet.nodeClustersAssigned()) ? fullNet.nodeClusterAssigment() : null; - this.layoutMode = fullNet.getLayoutMode(); - this.idGen = fullNet.nodeIDGenerator_; - } - - public RelayoutBuildData(UniqueLabeller idGen, - Set allLinks, Set loneNodeIDs, - Map clustAssign, - FabricColorGenerator colGen, BuildMode mode) { - super(mode); - this.bfn = null; - this.allLinks = allLinks; - this.colGen = colGen; - this.nodeOrder = null; - this.existingIDOrder = null; + this.existingOrder = fullNet.existingOrder(); this.linkOrder = null; - this.linkGroups = new ArrayList(); - this.clustAssign = clustAssign; - this.loneNodeIDs = loneNodeIDs; - this.allNodeIDs = null; - this.layoutMode = LayoutMode.PER_NODE_MODE; - this.idGen = idGen; - } - - public Map> genNormNameToID() { - HashMap> retval = new HashMap>(); - Iterator nit = this.allNodeIDs.iterator(); - while (nit.hasNext()) { - NID.WithName nodeID = nit.next(); - String name = nodeID.getName(); - String nameNorm = DataUtil.normKey(name); - Set forName = retval.get(nameNorm); - if (forName == null) { - forName = new HashSet(); - retval.put(nameNorm, forName); - } - forName.add(nodeID); - } - return (retval); - } - - public void setNodeOrderFromAttrib(Map nodeOrderIn) { - this.nodeOrder = new HashMap(); - Map> nameToID = genNormNameToID(); - for (AttributeLoader.AttributeKey key : nodeOrderIn.keySet()) { - try { - Integer newRow = Integer.valueOf(nodeOrderIn.get(key)); - String keyName = ((AttributeLoader.StringKey)key).key; - String normName = DataUtil.normKey(keyName); - Set ids = nameToID.get(normName); - if (ids.size() != 1) { - throw new IllegalStateException(); - } - NID.WithName id = ids.iterator().next(); - this.nodeOrder.put(id, newRow); - } catch (NumberFormatException nfex) { - throw new IllegalStateException(); - } - } - return; + this.existingLinkGroups = fullNet.linkGrouping_; + this.loneNodes = fullNet.getLoneNodes(); + this.allNodes = fullNet.nodeDefs_.keySet(); } - public void setNodeOrder(Map nodeOrder) { + public void setNodeOrder(Map nodeOrder) { this.nodeOrder = nodeOrder; return; } - - public void setLinkOrder(SortedMap linkOrder) { + + public void setLinkOrder(SortedMap linkOrder) { this.linkOrder = linkOrder; return; } - - public void setGroupOrderAndMode(List groupOrder, LayoutMode mode) { - this.linkGroups = groupOrder; - this.layoutMode = mode; + + public void setLinkGroups(List linkGroups) { + this.newLinkGroups = linkGroups; return; - } + } } /*************************************************************************** @@ -2419,11 +2368,11 @@ public void setGroupOrderAndMode(List groupOrder, LayoutMode mode) { public static class SelectBuildData extends BuildData { BioFabricNetwork fullNet; - List subNodes; - List subLinks; + List subNodes; + List subLinks; - public SelectBuildData(BioFabricNetwork fullNet, List subNodes, List subLinks) { - super(BuildMode.BUILD_FOR_SUBMODEL); + public SelectBuildData(BioFabricNetwork fullNet, List subNodes, List subLinks) { + super(BUILD_FOR_SUBMODEL); this.fullNet = fullNet; this.subNodes = subNodes; this.subLinks = subLinks; @@ -2452,14 +2401,14 @@ static class DoubleRanked { ** For storing column assignments */ - public static class ColumnAssign { - public HashMap columnToSource; - public HashMap columnToTarget; - public int columnCount; + static private class ColumnAssign { + HashMap columnToSource; + HashMap columnToTarget; + int columnCount; ColumnAssign() { - this.columnToSource = new HashMap(); - this.columnToTarget = new HashMap(); + this.columnToSource = new HashMap(); + this.columnToTarget = new HashMap(); this.columnCount = 0; } } @@ -2475,20 +2424,20 @@ public static class ColumnAssign { ** Extract relations */ - public static SortedMap extractRelations(List allLinks) { - HashSet flipSet = new HashSet(); - HashSet flipRels = new HashSet(); - HashSet rels = new HashSet(); - Iterator alit = allLinks.iterator(); + public static SortedMap extractRelations(List allLinks) { + HashSet flipSet = new HashSet(); + HashSet flipRels = new HashSet(); + HashSet rels = new HashSet(); + Iterator alit = allLinks.iterator(); while (alit.hasNext()) { - FabricLink nextLink = alit.next(); + FabricLink nextLink = (FabricLink)alit.next(); FabricLink.AugRelation relation = nextLink.getAugRelation(); if (!nextLink.isFeedback()) { // Autofeedback not flippable FabricLink flipLink = nextLink.flipped(); if (flipSet.contains(flipLink)) { flipRels.add(relation); } else { - flipSet.add(nextLink); + flipSet.add(flipLink); } } rels.add(relation); @@ -2499,12 +2448,12 @@ public static SortedMap extractRelations(List relMap = new TreeMap(); + TreeMap relMap = new TreeMap(); Boolean noDir = new Boolean(false); Boolean haveDir = new Boolean(true); - Iterator rit = rels.iterator(); + Iterator rit = rels.iterator(); while (rit.hasNext()) { - FabricLink.AugRelation rel = rit.next(); + FabricLink.AugRelation rel = (FabricLink.AugRelation)rit.next(); relMap.put(rel, (flipRels.contains(rel)) ? haveDir : noDir); } return (relMap); @@ -2515,36 +2464,17 @@ public static SortedMap extractRelations(List allLinks, Map relMap) { - Iterator alit = allLinks.iterator(); + public static void assignDirections(List allLinks, Map relMap) { + Iterator alit = allLinks.iterator(); while (alit.hasNext()) { - FabricLink nextLink = alit.next(); + FabricLink nextLink = (FabricLink)alit.next(); FabricLink.AugRelation rel = nextLink.getAugRelation(); - Boolean isDir = relMap.get(rel); + Boolean isDir = (Boolean)relMap.get(rel); nextLink.installDirection(isDir); } return; } - /*************************************************************************** - ** - ** Helper to drop to map to single name: useful - */ - - public static Map reduceNameSetToOne(Map> mapsToSets) { - HashMap retval = new HashMap(); - Iterator alit = mapsToSets.keySet().iterator(); - while (alit.hasNext()) { - String nextName = alit.next(); - Set forName = mapsToSets.get(nextName); - if (forName.size() != 1) { - throw new IllegalStateException(); - } - retval.put(nextName, forName.iterator().next()); - } - return (retval); - } - /*************************************************************************** ** ** This culls a set of links to remove non-directional synonymous and @@ -2552,11 +2482,10 @@ public static Map reduceNameSetToOne(Map allLinks, Set retval, Set culled) { - FabricLink.FabLinkComparator flc = new FabricLink.FabLinkComparator(); - Iterator alit = allLinks.iterator(); + public static void preprocessLinks(List allLinks, Set retval, Set culled) { + Iterator alit = allLinks.iterator(); while (alit.hasNext()) { - FabricLink nextLink = alit.next(); + FabricLink nextLink = (FabricLink)alit.next(); if (retval.contains(nextLink)) { culled.add(nextLink); } else if (!nextLink.isDirected()) { @@ -2564,7 +2493,7 @@ public static void preprocessLinks(List allLinks, Set re FabricLink flipLink = nextLink.flipped(); if (retval.contains(flipLink)) { // Make the order consistent for a given src & pair! - if (flc.compare(nextLink, flipLink) < 0) { + if (nextLink.compareTo(flipLink) < 0) { retval.remove(flipLink); culled.add(flipLink); retval.add(nextLink); @@ -2598,7 +2527,7 @@ public NetworkDataWorker(FabricFactory.FactoryWhiteboard whiteboard) { installWorker(new FabricDisplayOptions.FabricDisplayOptionsWorker(whiteboard), null); installWorker(new NodeInfoWorker(whiteboard), new MyNodeGlue()); installWorker(new LinkInfoWorker(whiteboard), new MyLinkGlue()); - installWorker(new LinkGroupWorker(whiteboard), null); + installWorker(new LinkGroupTagWorker(whiteboard), new MyGroupGlue()); } protected Object localProcessElement(String elemName, Attributes attrs) throws IOException { @@ -2646,33 +2575,8 @@ public Object glueKidToParent(Object kidObj, AbstractFactoryClient parentWorker, board.bfn.addLinkGroupForIO(board.groupTag); return (null); } - } - - public static class LinkGroupWorker extends AbstractFactoryClient { - - public LinkGroupWorker(FabricFactory.FactoryWhiteboard board) { - super(board); - FabricFactory.FactoryWhiteboard whiteboard = (FabricFactory.FactoryWhiteboard)sharedWhiteboard_; - myKeys_.add("linkGroups"); - installWorker(new LinkGroupTagWorker(whiteboard), new MyGroupGlue()); - } - - protected Object localProcessElement(String elemName, Attributes attrs) throws IOException { - LayoutMode retval = null; - if (elemName.equals("linkGroups")) { - String target = AttributeExtractor.extractAttribute(elemName, attrs, "linkGroups", "mode", false); - if (target == null) { - target = LayoutMode.PER_NODE_MODE.getText(); - } - FabricFactory.FactoryWhiteboard board = (FabricFactory.FactoryWhiteboard)this.sharedWhiteboard_; - retval = LayoutMode.valueOf(target); - board.bfn.setLayoutMode(retval); - - } - return (retval); - } - } - + } + /*************************************************************************** ** ** For XML I/O @@ -2688,46 +2592,23 @@ public LinkInfoWorker(FabricFactory.FactoryWhiteboard board) { protected Object localProcessElement(String elemName, Attributes attrs) throws IOException { Object retval = null; FabricFactory.FactoryWhiteboard board = (FabricFactory.FactoryWhiteboard)this.sharedWhiteboard_; - board.linkInfo = buildFromXML(elemName, attrs, board); + board.linkInfo = buildFromXML(elemName, attrs); retval = board.linkInfo; return (retval); } - private LinkInfo buildFromXML(String elemName, Attributes attrs, FabricFactory.FactoryWhiteboard board) throws IOException { - String src = AttributeExtractor.extractAttribute(elemName, attrs, "link", "src", false); + private LinkInfo buildFromXML(String elemName, Attributes attrs) throws IOException { + String src = AttributeExtractor.extractAttribute(elemName, attrs, "link", "src", true); src = CharacterEntityMapper.unmapEntities(src, false); - String trg = AttributeExtractor.extractAttribute(elemName, attrs, "link", "trg", false); + String trg = AttributeExtractor.extractAttribute(elemName, attrs, "link", "trg", true); trg = CharacterEntityMapper.unmapEntities(trg, false); - - String srcID = AttributeExtractor.extractAttribute(elemName, attrs, "link", "srcID", false); - - String trgID = AttributeExtractor.extractAttribute(elemName, attrs, "link", "trgID", false); - - NID.WithName srcNID; - if (src != null) { - srcNID = board.legacyMap.get(DataUtil.normKey(src)); - } else if (srcID != null) { - srcNID = board.wnMap.get(new NID(srcID)); - } else { - throw new IOException(); - } - - NID.WithName trgNID; - if (trg != null) { - trgNID = board.legacyMap.get(DataUtil.normKey(trg)); - } else if (trgID != null) { - trgNID = board.wnMap.get(new NID(trgID)); - } else { - throw new IOException(); - } - String rel = AttributeExtractor.extractAttribute(elemName, attrs, "link", "rel", true); rel = CharacterEntityMapper.unmapEntities(rel, false); String directed = AttributeExtractor.extractAttribute(elemName, attrs, "link", "directed", true); Boolean dirObj = Boolean.valueOf(directed); String shadow = AttributeExtractor.extractAttribute(elemName, attrs, "link", "shadow", true); Boolean shadObj = Boolean.valueOf(shadow); - FabricLink flink = new FabricLink(srcNID, trgNID, rel, shadObj.booleanValue(), dirObj); + FabricLink flink = new FabricLink(src, trg, rel, shadObj.booleanValue(), dirObj); String col = AttributeExtractor.extractAttribute(elemName, attrs, "link", "column", false); String shadowCol = AttributeExtractor.extractAttribute(elemName, attrs, "link", "shadowCol", true); String srcRow = AttributeExtractor.extractAttribute(elemName, attrs, "link", "srcRow", true); @@ -2785,7 +2666,6 @@ private String buildFromXML(String elemName, Attributes attrs) throws IOExceptio public static class NodeInfoWorker extends AbstractFactoryClient { - public NodeInfoWorker(FabricFactory.FactoryWhiteboard board) { super(board); myKeys_.add("node"); @@ -2794,33 +2674,14 @@ public NodeInfoWorker(FabricFactory.FactoryWhiteboard board) { protected Object localProcessElement(String elemName, Attributes attrs) throws IOException { Object retval = null; FabricFactory.FactoryWhiteboard board = (FabricFactory.FactoryWhiteboard)this.sharedWhiteboard_; - board.nodeInfo = buildFromXML(elemName, attrs, board); + board.nodeInfo = buildFromXML(elemName, attrs); retval = board.nodeInfo; return (retval); } - private NodeInfo buildFromXML(String elemName, Attributes attrs, FabricFactory.FactoryWhiteboard board) throws IOException { + private NodeInfo buildFromXML(String elemName, Attributes attrs) throws IOException { String name = AttributeExtractor.extractAttribute(elemName, attrs, "node", "name", true); name = CharacterEntityMapper.unmapEntities(name, false); - - String nidStr = AttributeExtractor.extractAttribute(elemName, attrs, "node", "nid", false); - - NID nid; - NID.WithName nwn; - if (nidStr != null) { - boolean ok = board.ulb.addExistingLabel(nidStr); - if (!ok) { - throw new IOException(); - } - nid = new NID(nidStr); - nwn = new NID.WithName(nid, name); - } else { - nid = board.ulb.getNextOID(); - nwn = new NID.WithName(nid, name); - board.legacyMap.put(DataUtil.normKey(name), nwn); - } - board.wnMap.put(nid, nwn); - String row = AttributeExtractor.extractAttribute(elemName, attrs, "node", "row", true); String minCol = AttributeExtractor.extractAttribute(elemName, attrs, "node", "minCol", true); String maxCol = AttributeExtractor.extractAttribute(elemName, attrs, "node", "maxCol", true); @@ -2831,17 +2692,10 @@ private NodeInfo buildFromXML(String elemName, Attributes attrs, FabricFactory.F String minDrainSha = AttributeExtractor.extractAttribute(elemName, attrs, "node", "drainMinSha", false); String maxDrainSha = AttributeExtractor.extractAttribute(elemName, attrs, "node", "drainMaxSha", false); String color = AttributeExtractor.extractAttribute(elemName, attrs, "node", "color", true); - String cluster = AttributeExtractor.extractAttribute(elemName, attrs, "node", "cluster", false); - cluster = CharacterEntityMapper.unmapEntities(cluster, false); - NodeInfo retval; try { int nodeRow = Integer.valueOf(row).intValue(); - retval = new NodeInfo(nid, name, nodeRow, color); - if (cluster != null) { - UiUtil.fixMePrintout("Make cluster assign a list"); - retval.setCluster(cluster); - } + retval = new NodeInfo(name, nodeRow, color); int min = Integer.valueOf(minCol).intValue(); int max = Integer.valueOf(maxCol).intValue(); @@ -2856,12 +2710,12 @@ private NodeInfo buildFromXML(String elemName, Attributes attrs, FabricFactory.F if (minDrain != null) { int minDrVal = Integer.valueOf(minDrain).intValue(); int maxDrVal = Integer.valueOf(maxDrain).intValue(); - retval.addDrainZone(new MinMax(minDrVal, maxDrVal), false); + retval.setDrainZone(new MinMax(minDrVal, maxDrVal), false); } if (minDrainSha != null) { int minDrValSha = Integer.valueOf(minDrainSha).intValue(); int maxDrValSha = Integer.valueOf(maxDrainSha).intValue(); - retval.addDrainZone(new MinMax(minDrValSha, maxDrValSha), true); + retval.setDrainZone(new MinMax(minDrValSha, maxDrValSha), true); } } catch (NumberFormatException nfex) { throw new IOException(); diff --git a/src/org/systemsbiology/biofabric/ui/display/BioFabricOverview.java b/src/org/systemsbiology/biotapestry/biofabric/BioFabricOverview.java similarity index 51% rename from src/org/systemsbiology/biofabric/ui/display/BioFabricOverview.java rename to src/org/systemsbiology/biotapestry/biofabric/BioFabricOverview.java index 09c1982..41250a4 100644 --- a/src/org/systemsbiology/biofabric/ui/display/BioFabricOverview.java +++ b/src/org/systemsbiology/biotapestry/biofabric/BioFabricOverview.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,10 +17,9 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.display; +package org.systemsbiology.biotapestry.biofabric; import java.awt.BasicStroke; -import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; @@ -67,7 +66,6 @@ public class BioFabricOverview extends JPanel { private Dimension currSize_; private BufferedImage img_; private BufferedImage scaledImg_; - @SuppressWarnings("unused") private Point navFocus_; private Point scaledImgOrigin_; private Rectangle worldRect_; @@ -78,10 +76,6 @@ public class BioFabricOverview extends JPanel { private Rectangle2D viewInWorld_; private Rectangle magInWorld_; private boolean hideMag_; - private CardLayout myCard_; - private PaintPanel pPan_; - - private static final long serialVersionUID = 1L; //////////////////////////////////////////////////////////////////////////// // @@ -102,16 +96,6 @@ public BioFabricOverview() { scaledImgOrigin_ = new Point(0, 0); mouseIn_ = false; hideMag_ = true; - - - myCard_ = new CardLayout(); - setLayout(myCard_); - - pPan_ = new PaintPanel(); - add(pPan_, "theView"); - JPanel blankPanel = new JPanel(); - blankPanel.setBackground(Color.white); - add(blankPanel, "Hiding"); } //////////////////////////////////////////////////////////////////////////// @@ -120,32 +104,11 @@ public BioFabricOverview() { // //////////////////////////////////////////////////////////////////////////// - /*************************************************************************** - ** - ** Sizing - */ - - @Override - public Dimension getPreferredSize() { - return (new Dimension(800, 100)); - } - - @Override - public Dimension getMinimumSize() { - return (new Dimension(10, 10)); - } - - @Override - public Dimension getMaximumSize() { - return (new Dimension(4000, 340)); - } - /*************************************************************************** ** ** Handle size change */ - @Override public void setBounds(int x, int y, int width, int height) { super.setBounds(x, y, width, height); currSize_ = new Dimension(width, height); @@ -156,17 +119,64 @@ public void setBounds(int x, int y, int width, int height) { /*************************************************************************** ** - ** Show or hide the view + ** resize image */ - public void showView(boolean enabled) { - myCard_.show(this, (enabled) ? "theView" : "Hiding"); - return; - } + private void resizeImage() { + if (img_ == null) { + return; + } + if (currSize_ == null) { + currSize_ = getSize(); + } + // + // Don't do this step if the overview is not currently bring displayed + // + if ((currSize_.width <= 0) || (currSize_.height <= 0)) { + return; + } + double imgAR = (double)img_.getWidth() / (double)img_.getHeight(); + double panelAR = (double)currSize_.getWidth() / (double)currSize_.getHeight(); + int imgHeight; + int imgWidth; + int startX; + int startY; + if (panelAR < imgAR) { // long image, tall panel + imgWidth = currSize_.width; + imgHeight = (int)((double)imgWidth / imgAR); + startX = 0; + startY = (currSize_.height - imgHeight) / 2; + } else { + imgHeight = currSize_.height; + imgWidth = (int)((double)imgHeight * imgAR); + startX = (currSize_.width - imgWidth) / 2; + startY = 0; + } + scaledImgOrigin_.setLocation(startX, startY); + scaledImg_ = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); + Graphics2D g2 = scaledImg_.createGraphics(); + g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); + g2.drawImage(img_, 0, 0, imgWidth, imgHeight, null); + g2.dispose(); + double zoomHW = (double)imgWidth / worldRect_.getWidth(); + double zoomVW = (double)imgHeight / worldRect_.getHeight(); + if (zoomHW < zoomVW) { + zoom_ = zoomHW; + } else { + zoom_ = zoomVW; + } + + transform_ = new AffineTransform(); + transform_.translate((worldRect_.getWidth() / 2.0) * zoom_, (worldRect_.getHeight() / 2.0) * zoom_); + transform_.scale(zoom_, zoom_); + transform_.translate(-worldRect_.getCenterX(), -worldRect_.getCenterY()); + return; + } + /*************************************************************************** ** - ** Set current mouse location + ** Drawing routine */ public void setMouse(Point2D center, Point cprc) { @@ -179,7 +189,7 @@ public void setMouse(Point2D center, Point cprc) { /*************************************************************************** ** - ** Set the viewport location + ** Drawing routine */ public void setViewInWorld(Rectangle2D viewInWorld) { @@ -190,7 +200,7 @@ public void setViewInWorld(Rectangle2D viewInWorld) { /*************************************************************************** ** - ** Set magnifier location + ** Drawing routine */ public void setMagnifyView(Rectangle magInWorld) { @@ -201,7 +211,7 @@ public void setMagnifyView(Rectangle magInWorld) { /*************************************************************************** ** - ** Set if mouse in in view + ** Drawing routine */ public void setMouseIn(boolean isIn, boolean magIgnoring) { @@ -224,196 +234,173 @@ public void installImage(BufferedImage img, Rectangle worldRect) { repaint(); return; } - + /*************************************************************************** ** - ** resize image + ** Drawing routine */ - - private void resizeImage() { + + public void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D)g; if (img_ == null) { return; } - if (currSize_ == null) { - currSize_ = getSize(); - } - // - // Don't do this step if the overview is not currently bring displayed - // - if ((currSize_.width <= 0) || (currSize_.height <= 0)) { - return; + if (scaledImg_ == null) { + resizeImage(); } - double imgAR = (double)img_.getWidth() / (double)img_.getHeight(); - double panelAR = currSize_.getWidth() / currSize_.getHeight(); - int imgHeight; - int imgWidth; - int startX; - int startY; - if (panelAR < imgAR) { // long image, tall panel - imgWidth = currSize_.width; - imgHeight = (int)(imgWidth / imgAR); - if (imgHeight == 0) { - imgHeight = 1; - } - startX = 0; - startY = (currSize_.height - imgHeight) / 2; - } else { - imgHeight = currSize_.height; - imgWidth = (int)(imgHeight * imgAR); - if (imgWidth == 0) { - imgWidth = 1; - } - startX = (currSize_.width - imgWidth) / 2; - startY = 0; - } - scaledImgOrigin_.setLocation(startX, startY); - scaledImg_ = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); - Graphics2D g2 = scaledImg_.createGraphics(); - g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - g2.drawImage(img_, 0, 0, imgWidth, imgHeight, null); - g2.dispose(); + + g2.drawImage(scaledImg_, scaledImgOrigin_.x, scaledImgOrigin_.y, null); + drawFloater(g); + return; + } - double zoomHW = imgWidth / worldRect_.getWidth(); - double zoomVW = imgHeight / worldRect_.getHeight(); - if (zoomHW < zoomVW) { - zoom_ = zoomHW; - } else { - zoom_ = zoomVW; + /*************************************************************************** + ** + ** Drawing core + */ + + private void drawFloater(Graphics g) { + Graphics2D g2 = (Graphics2D)g; + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + BasicStroke selectedStroke = new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER); + g2.setStroke(selectedStroke); + g2.setPaint(Color.GREEN); + + if ((mousePoint_ != null) && mouseIn_) { + Point viewP = pointToViewport(mousePoint_); + Ellipse2D circ = new Ellipse2D.Double(viewP.x + scaledImgOrigin_.x - MOUSE_RADIUS_, + viewP.y + scaledImgOrigin_.y - MOUSE_RADIUS_, + 2.0 * MOUSE_RADIUS_, 2.0 * MOUSE_RADIUS_); + g2.draw(circ); + g2.drawLine((int)(viewP.x + scaledImgOrigin_.x - MOUSE_XHAIR_), + (int)(viewP.y + scaledImgOrigin_.y), + (int)(viewP.x + scaledImgOrigin_.x + MOUSE_XHAIR_), + (int)(viewP.y + scaledImgOrigin_.y)); + g2.drawLine((int)(viewP.x + scaledImgOrigin_.x), + (int)(viewP.y + scaledImgOrigin_.y - MOUSE_XHAIR_), + (int)(viewP.x + scaledImgOrigin_.x), + (int)(viewP.y + scaledImgOrigin_.y + MOUSE_XHAIR_)); } - transform_ = new AffineTransform(); - transform_.translate((worldRect_.getWidth() / 2.0) * zoom_, (worldRect_.getHeight() / 2.0) * zoom_); - transform_.scale(zoom_, zoom_); - transform_.translate(-worldRect_.getCenterX(), -worldRect_.getCenterY()); + if (viewInWorld_ != null) { + Point2D viwUL = new Point2D.Double(viewInWorld_.getMinX(), viewInWorld_.getMinY()); + Point viewUL = pointToViewport(viwUL); + Point2D viwLR = new Point2D.Double(viewInWorld_.getMaxX(), viewInWorld_.getMaxY()); + Point viewLR = pointToViewport(viwLR); + int vw = viewLR.x - viewUL.x; + int vh = viewLR.y - viewUL.y; + int vcx = (viewUL.x + viewLR.x) / 2; + int vcy = (viewUL.y + viewLR.y) / 2; + g2.drawRect((int)(viewUL.x + scaledImgOrigin_.x), + (int)(viewUL.y + scaledImgOrigin_.y), vw, vh); + g2.drawLine((int)(vcx + scaledImgOrigin_.x - BOX_XHAIR_), + (int)(vcy + scaledImgOrigin_.y), + (int)(vcx + scaledImgOrigin_.x + BOX_XHAIR_), + (int)(vcy + scaledImgOrigin_.y)); + g2.drawLine((int)(vcx + scaledImgOrigin_.x), + (int)(vcy + scaledImgOrigin_.y - BOX_XHAIR_), + (int)(vcx + scaledImgOrigin_.x), + (int)(vcy + scaledImgOrigin_.y + BOX_XHAIR_)); + + + + } + + if ((magInWorld_ != null) && !hideMag_) { + g2.setPaint(Color.RED); + Point2D viwUL = new Point2D.Double(magInWorld_.getMinX(), magInWorld_.getMinY()); + Point viewUL = pointToViewport(viwUL); + Point2D viwLR = new Point2D.Double(magInWorld_.getMaxX(), magInWorld_.getMaxY()); + Point viewLR = pointToViewport(viwLR); + int vw = viewLR.x - viewUL.x; + int vh = viewLR.y - viewUL.y; + int vcx = (viewUL.x + viewLR.x) / 2; + int vcy = (viewUL.y + viewLR.y) / 2; + g2.drawRect((int)(viewUL.x + scaledImgOrigin_.x), + (int)(viewUL.y + scaledImgOrigin_.y), vw, vh); + g2.drawLine((int)(vcx + scaledImgOrigin_.x - BOX_XHAIR_), + (int)(vcy + scaledImgOrigin_.y), + (int)(vcx + scaledImgOrigin_.x + BOX_XHAIR_), + (int)(vcy + scaledImgOrigin_.y)); + g2.drawLine((int)(vcx + scaledImgOrigin_.x), + (int)(vcy + scaledImgOrigin_.y - BOX_XHAIR_), + (int)(vcx + scaledImgOrigin_.x), + (int)(vcy + scaledImgOrigin_.y + BOX_XHAIR_)); + } return; - } - + } + /*************************************************************************** ** - ** Handles the drawing - */ + ** Gets given point in viewport coordinates X + */ - private class PaintPanel extends JPanel { - private static final long serialVersionUID = 1L; + public Point pointToViewport(Point2D worldPoint) { + Point2D newPoint = new Point2D.Double(worldPoint.getX(), worldPoint.getY()); + transform_.transform(newPoint, newPoint); + int x = (int)((double)Math.round(newPoint.getX())); + int y = (int)((double)Math.round(newPoint.getY())); + Point pt = new Point(x, y); + return (pt); + } - /*************************************************************************** - ** - ** Constructor - */ + /*************************************************************************** + ** + ** Useful for selection - public PaintPanel() { - setBackground(Color.white); - } - - /*************************************************************************** - ** - ** Drawing routine - */ - - public void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D)g; - if (img_ == null) { - return; - } - if (scaledImg_ == null) { - resizeImage(); - } - - g2.drawImage(scaledImg_, scaledImgOrigin_.x, scaledImgOrigin_.y, null); - drawFloater(g); - return; + + public Rectangle valsToRect(int sx, int sy, int ex, int ey, boolean convert) { + int x, y, width, height, endx, endy; + if (convert) { + Point locs = new Point(sx, sy); + Point spt = transToRowCol(locs); + Point loce = new Point(ex, ey); + Point ept = transToRowCol(loce); + Point2D start = new Point2D.Double(spt.x, spt.y); + Point2D end = new Point2D.Double(ept.x, ept.y); + x = (int)start.getX(); + y = (int)start.getY(); + width = (int)end.getX() - x; + height = (int)end.getY() - y; + endx = (int)end.getX(); + endy = (int)end.getY(); + } else { + x = sx; + y = sy; + width = ex - sx; + height = ey - sy; + endx = ex; + endy = ey; } - - /*************************************************************************** - ** - ** Gets given point in viewport coordinates - */ - - private Point pointToViewport(Point2D worldPoint) { - Point2D newPoint = new Point2D.Double(worldPoint.getX(), worldPoint.getY()); - transform_.transform(newPoint, newPoint); - int x = (int)(Math.round(newPoint.getX())); - int y = (int)(Math.round(newPoint.getY())); - Point pt = new Point(x, y); - return (pt); - } - - /*************************************************************************** - ** - ** Drawing core - */ - - private void drawFloater(Graphics g) { - Graphics2D g2 = (Graphics2D)g; - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - BasicStroke selectedStroke = new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER); - g2.setStroke(selectedStroke); - g2.setPaint(Color.GREEN); - - if ((mousePoint_ != null) && mouseIn_) { - Point viewP = pointToViewport(mousePoint_); - Ellipse2D circ = new Ellipse2D.Double(viewP.x + scaledImgOrigin_.x - MOUSE_RADIUS_, - viewP.y + scaledImgOrigin_.y - MOUSE_RADIUS_, - 2.0 * MOUSE_RADIUS_, 2.0 * MOUSE_RADIUS_); - g2.draw(circ); - g2.drawLine((int)(viewP.x + scaledImgOrigin_.x - MOUSE_XHAIR_), - (viewP.y + scaledImgOrigin_.y), - (int)(viewP.x + scaledImgOrigin_.x + MOUSE_XHAIR_), - (viewP.y + scaledImgOrigin_.y)); - g2.drawLine((viewP.x + scaledImgOrigin_.x), - (int)(viewP.y + scaledImgOrigin_.y - MOUSE_XHAIR_), - (viewP.x + scaledImgOrigin_.x), - (int)(viewP.y + scaledImgOrigin_.y + MOUSE_XHAIR_)); - } - - if (viewInWorld_ != null) { - Point2D viwUL = new Point2D.Double(viewInWorld_.getMinX(), viewInWorld_.getMinY()); - Point viewUL = pointToViewport(viwUL); - Point2D viwLR = new Point2D.Double(viewInWorld_.getMaxX(), viewInWorld_.getMaxY()); - Point viewLR = pointToViewport(viwLR); - int vw = viewLR.x - viewUL.x; - int vh = viewLR.y - viewUL.y; - int vcx = (viewUL.x + viewLR.x) / 2; - int vcy = (viewUL.y + viewLR.y) / 2; - g2.drawRect((viewUL.x + scaledImgOrigin_.x), - (viewUL.y + scaledImgOrigin_.y), vw, vh); - g2.drawLine((int)(vcx + scaledImgOrigin_.x - BOX_XHAIR_), - (vcy + scaledImgOrigin_.y), - (int)(vcx + scaledImgOrigin_.x + BOX_XHAIR_), - (vcy + scaledImgOrigin_.y)); - g2.drawLine((vcx + scaledImgOrigin_.x), - (int)(vcy + scaledImgOrigin_.y - BOX_XHAIR_), - (vcx + scaledImgOrigin_.x), - (int)(vcy + scaledImgOrigin_.y + BOX_XHAIR_)); - - - + + int rx, ry, rw, rh; + if ((width != 0) && (height != 0)) { + if (width < 0) { + rx = endx; + rw = -width; + } else { + rx = x; + rw = width; } - - if ((magInWorld_ != null) && !hideMag_) { - g2.setPaint(Color.RED); - Point2D viwUL = new Point2D.Double(magInWorld_.getMinX(), magInWorld_.getMinY()); - Point viewUL = pointToViewport(viwUL); - Point2D viwLR = new Point2D.Double(magInWorld_.getMaxX(), magInWorld_.getMaxY()); - Point viewLR = pointToViewport(viwLR); - int vw = viewLR.x - viewUL.x; - int vh = viewLR.y - viewUL.y; - int vcx = (viewUL.x + viewLR.x) / 2; - int vcy = (viewUL.y + viewLR.y) / 2; - g2.drawRect((viewUL.x + scaledImgOrigin_.x), - (viewUL.y + scaledImgOrigin_.y), vw, vh); - g2.drawLine((int)(vcx + scaledImgOrigin_.x - BOX_XHAIR_), - (vcy + scaledImgOrigin_.y), - (int)(vcx + scaledImgOrigin_.x + BOX_XHAIR_), - (vcy + scaledImgOrigin_.y)); - g2.drawLine((vcx + scaledImgOrigin_.x), - (int)(vcy + scaledImgOrigin_.y - BOX_XHAIR_), - (vcx + scaledImgOrigin_.x), - (int)(vcy + scaledImgOrigin_.y + BOX_XHAIR_)); + if (height < 0) { + ry = endy; + rh = -height; + } else { + ry = y; + rh = height; } - return; + return (new Rectangle(rx, ry, rw, rh)); + } else { + return (null); } } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC STATIC METHODS + // + //////////////////////////////////////////////////////////////////////////// +*/ } diff --git a/src/org/systemsbiology/biofabric/ui/display/BioFabricPanel.java b/src/org/systemsbiology/biotapestry/biofabric/BioFabricPanel.java similarity index 82% rename from src/org/systemsbiology/biofabric/ui/display/BioFabricPanel.java rename to src/org/systemsbiology/biotapestry/biofabric/BioFabricPanel.java index af4bca6..c09267c 100644 --- a/src/org/systemsbiology/biofabric/ui/display/BioFabricPanel.java +++ b/src/org/systemsbiology/biotapestry/biofabric/BioFabricPanel.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.display; +package org.systemsbiology.biotapestry.biofabric; import java.awt.AlphaComposite; import java.awt.BasicStroke; @@ -47,7 +47,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; @@ -57,35 +56,21 @@ import javax.swing.JViewport; -import org.systemsbiology.biofabric.app.BioFabricApplication; -import org.systemsbiology.biofabric.app.BioFabricWindow; -import org.systemsbiology.biofabric.cmd.CommandSet; -import org.systemsbiology.biofabric.cmd.ZoomCommandSupport; -import org.systemsbiology.biofabric.cmd.ZoomTarget; -import org.systemsbiology.biofabric.db.SimpleWorkspaceSource; -import org.systemsbiology.biofabric.db.Workspace; -import org.systemsbiology.biofabric.event.EventManager; -import org.systemsbiology.biofabric.event.SelectionChangeEvent; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.model.BioFabricNetwork.LinkInfo; -import org.systemsbiology.biofabric.model.BioFabricNetwork.NodeInfo; -import org.systemsbiology.biofabric.ui.BasicZoomTargetSupport; -import org.systemsbiology.biofabric.ui.CursorManager; -import org.systemsbiology.biofabric.ui.FabricColorGenerator; -import org.systemsbiology.biofabric.ui.FabricDisplayOptions; -import org.systemsbiology.biofabric.ui.FabricDisplayOptionsManager; -import org.systemsbiology.biofabric.ui.ImageExporter; -import org.systemsbiology.biofabric.ui.PopupMenuControl; -import org.systemsbiology.biofabric.ui.ZoomPresentation; -import org.systemsbiology.biofabric.ui.render.BufBuildDrawer; -import org.systemsbiology.biofabric.ui.render.BufferBuilder; -import org.systemsbiology.biofabric.ui.render.PaintCache; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.MinMax; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.UiUtil; -import org.systemsbiology.biofabric.util.UndoSupport; +import org.systemsbiology.biotapestry.cmd.ZoomCommandSupport; +import org.systemsbiology.biotapestry.cmd.ZoomTarget; +import org.systemsbiology.biotapestry.db.Workspace; +import org.systemsbiology.biotapestry.ui.BasicZoomTargetSupport; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.UndoSupport; +import org.systemsbiology.biotapestry.db.SimpleWorkspaceSource; +import org.systemsbiology.biotapestry.event.EventManager; +import org.systemsbiology.biotapestry.event.SelectionChangeEvent; +import org.systemsbiology.biotapestry.ui.CursorManager; +import org.systemsbiology.biotapestry.ui.ImageExporter; +import org.systemsbiology.biotapestry.ui.ZoomPresentation; +import org.systemsbiology.biotapestry.util.MinMax; +import org.systemsbiology.biotapestry.util.TaggedSet; +import org.systemsbiology.biotapestry.util.UiUtil; /**************************************************************************** ** @@ -101,8 +86,7 @@ public class BioFabricPanel extends JPanel implements ZoomTarget, ZoomPresentati // //////////////////////////////////////////////////////////////////////////// - private static final int PAD_SIZE_ = 200; - + public static final int PAD_SIZE_ = 200; //////////////////////////////////////////////////////////////////////////// // @@ -132,7 +116,7 @@ public class BioFabricPanel extends JPanel implements ZoomTarget, ZoomPresentati private ZoomCommandSupport zcs_; private int zoomIndex_; - private TreeMap zoomMap_; + private TreeMap zoomMap_; private int numZoom_; private Point lastPress_; @@ -144,24 +128,22 @@ public class BioFabricPanel extends JPanel implements ZoomTarget, ZoomPresentati private Point firstZoomPoint_; private boolean isAMac_; - @SuppressWarnings("unused") private boolean lastShifted_; private boolean lastCtrl_; private BioFabricPanel myMini_; - private HashSet currLinkSelections_; - private HashSet currNodeSelections_; - private HashSet currColSelections_; - private ArrayList targetList_; - private ArrayList linkList_; + private HashSet currLinkSelections_; + private HashSet currNodeSelections_; + private HashSet currColSelections_; + private ArrayList targetList_; + private ArrayList linkList_; private BufferBuilder bufferBuilder_; - private ArrayList rects_; + private ArrayList rects_; private int currSel_; private FabricLocation myLocation_; - private MouseOverView mov_; private Rectangle worldRect_; private Dimension screenDim_; private Dimension worldDim_; @@ -175,19 +157,19 @@ public class BioFabricPanel extends JPanel implements ZoomTarget, ZoomPresentati private PaintCache painter_; private PaintCache selectionPainter_; private BioFabricApplication bfa_; + private boolean isForMain_; + private FabricColorGenerator colGen_; private FabricMagnifyingTool fmt_; private FabricNavTool fnt_; private BioFabricOverview bfo_; - private BufferedImage bim_; private boolean doBuildSelect_; private CursorManager cursorMgr_; private BioFabricWindow bfw_; - private Map nodeNameLocations_; - private Map> drainNameLocations_; + private Map nodeNameLocations_; + private Map drainNameLocations_; private PopupMenuControl popCtrl_; - private static final long serialVersionUID = 1L; //////////////////////////////////////////////////////////////////////////// // @@ -208,23 +190,24 @@ public BioFabricPanel(FabricColorGenerator colGen, BioFabricApplication bfa, fnt_ = fnt; bfo_ = bfo; bfw_ = bfw; + colGen_ = colGen; zoomSrc_ = new ZoomerSource(); zoomer_ = new BasicZoomTargetSupport(this, this, zoomSrc_); - CommandSet fc = CommandSet.getCmds((isForMain) ? "mainWindow" : "selectionWindow"); + FabricCommands fc = FabricCommands.getCmds((isForMain) ? "mainWindow" : "selectionWindow"); zcs_ = new ZoomCommandSupport(fc); isAMac_ = fc.isAMac(); painter_ = new PaintCache(colGen); selectionPainter_ = new PaintCache(colGen); fmt_.setPainters(painter_, selectionPainter_); - zoomMap_ = new TreeMap(); + zoomMap_ = new TreeMap(); numZoom_ = 0; addMouseListener(new MouseHandler()); addMouseMotionListener(new MouseMotionHandler()); - currLinkSelections_ = new HashSet(); - currNodeSelections_ = new HashSet(); - currColSelections_ = new HashSet(); - targetList_ = new ArrayList(); - linkList_ = new ArrayList(); + currLinkSelections_ = new HashSet(); + currNodeSelections_ = new HashSet(); + currColSelections_ = new HashSet(); + targetList_ = new ArrayList(); + linkList_ = new ArrayList(); collectingZoomMode_ = false; collectingTourStart_ = false; tourStartSelectionOnly_ = false; @@ -235,11 +218,12 @@ public BioFabricPanel(FabricColorGenerator colGen, BioFabricApplication bfa, worldRect_ = new Rectangle(0, 0, 100, 100); zoomSrc_.simpleSetWorkspace(new Workspace(worldRect_)); bfn_ = null; + isForMain_ = isForMain; floaterSet_ = new PaintCache.FloaterSet(null, null, null); fmt_.setCurrentFloater(floaterSet_); // Actually directly shared! - rects_ = new ArrayList(); + rects_ = new ArrayList(); currSel_ = -1; selFocus_ = null; tourFocus_ = null; @@ -366,7 +350,7 @@ public void yourOrderIsReady(int size) { return; } Double zoomVal = new Double(zoomer_.getZoomFactor()); - Integer numObj = zoomMap_.get(zoomVal); + Integer numObj = (Integer)zoomMap_.get(zoomVal); if ((numObj != null) && (size == numObj.intValue())) { repaint(); } @@ -413,18 +397,17 @@ public void zoomForBuf(int[] zooms, Dimension screenSize) { int imgWidth; if (zoomH < zoomV) { imgWidth = screenSize.width; - imgHeight = (int)(imgWidth / worldAR); + imgHeight = (int)((double)imgWidth / worldAR); zoom = zoomH; } else { imgHeight = screenSize.height; - imgWidth = (int)(imgHeight * worldAR); + imgWidth = (int)((double)imgHeight * worldAR); zoom = zoomV; } screenDim_ = new Dimension(imgWidth, imgHeight); - System.out.println("SD " + screenDim_); double lastZoom = zoom; for (int i = 0; i < zooms.length; i++) { - zoomMap_.put(new Double(lastZoom), Integer.valueOf(i)); + zoomMap_.put(new Double(lastZoom), new Integer(i)); lastZoom *= 2.0; } return; @@ -455,7 +438,7 @@ public void clearSelections() { floaterSet_.currSelRect = null; rects_.clear(); currSel_ = -1; - selectionPainter_.buildObjCache(targetList_, linkList_, false, false, new HashMap(), new HashMap>()); + selectionPainter_.buildObjCache(targetList_, linkList_, false, false, new HashMap(), new HashMap()); fnt_.haveASelection(false); handleFloaterChange(); EventManager mgr = EventManager.getManager(); @@ -463,14 +446,81 @@ public void clearSelections() { mgr.sendSelectionChangeEvent(ev); return; } + + /*************************************************************************** + ** + ** Get detail panel + */ + + public void selectFromGaggle(SelectionSupport.SelectionsForSpecies sfs) { + if (!doBuildSelect_) { + currLinkSelections_.clear(); + currNodeSelections_.clear(); + currColSelections_.clear(); + currSel_ = -1; + floaterSet_.currSelRect = null; + } + + Iterator sfsit = sfs.selections.iterator(); + while (sfsit.hasNext()) { + String selection = (String)sfsit.next(); + BioFabricNetwork.NodeInfo tni = bfn_.getNodeDefinition(selection); + if (tni != null) { + currNodeSelections_.add(selection); + } + } + + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + gaggleSelectionSupport(goose); + } + + buildSelectionGeometry(null, null); + return; + } + /*************************************************************************** ** ** Set location announcement */ - public void setFabricLocation(FabricLocation loc, MouseOverView mov) { + public void setFabricLocation(FabricLocation loc) { myLocation_ = loc; - mov_ = mov; + return; + } + + /*************************************************************************** + ** + ** Common gaggle selection operations + */ + + private void gaggleSelectionSupport(FabricGooseInterface goose) { + SelectionSupport ss = goose.getSelectionSupport(); + ss.setSelections(new ArrayList(currNodeSelections_)); + HashSet forGooseSet = new HashSet(); + // + // The link selections can include shadow links as well as real links. + // For gaggle, we wish to merge the two into a single set where either + // (or both) stand for the real link + // + Iterator cesit = currLinkSelections_.iterator(); + while (cesit.hasNext()) { + FabricLink fl = (FabricLink)cesit.next(); + if (fl.isShadow()) { + fl = (FabricLink)fl.clone(); + fl.dropShadowStatus(); + } + forGooseSet.add(fl); + } + ArrayList forGoose = new ArrayList(forGooseSet); + HashSet loneNodes = new HashSet(currNodeSelections_); + cesit = currLinkSelections_.iterator(); + while (cesit.hasNext()) { + FabricLink fl = (FabricLink)cesit.next(); + loneNodes.remove(fl.getSrc()); + loneNodes.remove(fl.getTrg()); + } + ss.setOutboundNetwork(new SelectionSupport.NetworkForSpecies(forGoose, new ArrayList(loneNodes))); return; } @@ -502,7 +552,7 @@ public boolean haveASelection() { ** Get node selections */ - public Set getNodeSelections() { + public Set getNodeSelections() { return (currNodeSelections_); } @@ -511,8 +561,9 @@ public Set getNodeSelections() { ** Get detail panel */ - public void installSearchResult(Set results, boolean doDiscard) { + public void installSearchResult(Set results, boolean doDiscard) { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); if (doDiscard) { currLinkSelections_.clear(); currNodeSelections_.clear(); @@ -521,12 +572,19 @@ public void installSearchResult(Set results, boolean doDiscard) { floaterSet_.currSelRect = null; } if (results.isEmpty()) { + if ((goose != null) && goose.isActivated()) { + gaggleSelectionSupport(goose); + } buildSelectionGeometry(null, null); return; } currNodeSelections_.addAll(results); - buildSelectionGeometry(results.iterator().next(), null); + if ((goose != null) && goose.isActivated()) { + gaggleSelectionSupport(goose); + } + + buildSelectionGeometry((String)results.iterator().next(), null); zoomToSelected(); return; } @@ -539,6 +597,10 @@ public void installSearchResult(Set results, boolean doDiscard) { public void addFirstNeighbors() { boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); bfn_.addFirstNeighbors(currNodeSelections_, currColSelections_, currLinkSelections_, showShadows); + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + gaggleSelectionSupport(goose); + } buildSelectionGeometry(null, null); return; } @@ -548,7 +610,7 @@ public void addFirstNeighbors() { ** Send selections to mini panel */ - private void transmitSelections(List targetList, List linkList) { + private void transmitSelections(List targetList, List linkList) { if (myMini_ == null) { bfa_.launchSelection(); if (myMini_ == null) { @@ -557,7 +619,7 @@ private void transmitSelections(List targetList, List linkLi } else { bfa_.raiseSelection(); } - CommandSet fc = CommandSet.getCmds("selectionWindow"); + FabricCommands fc = FabricCommands.getCmds("selectionWindow"); try { BioFabricNetwork.SelectBuildData bfnsbd = new BioFabricNetwork.SelectBuildData(bfn_, targetList, linkList); fc.newModelOperations(bfnsbd, false); @@ -672,8 +734,8 @@ public TourStatus getTourDirections(boolean selectedOnly) { if (tourFocus_ == null) { return (null); } - return (handleTourStop(tourFocus_.x, tourFocus_.y, Integer.valueOf(tourFocus_.x), - (selectedOnly) ? bfn_.getNodeIDForRow(Integer.valueOf(tourFocus_.y)) : null)); + return (handleTourStop(tourFocus_.x, tourFocus_.y, new Integer(tourFocus_.x), + (selectedOnly) ? bfn_.getNodeForRow(new Integer(tourFocus_.y)) : null)); } /*************************************************************************** @@ -683,7 +745,7 @@ public TourStatus getTourDirections(boolean selectedOnly) { private TourStatus goToDrainZone(boolean selectedOnly) { // FIX ME? Issues with this working with non-drain nodes? - NID.WithName nodeName = bfn_.getNodeIDForRow(Integer.valueOf(tourFocus_.y)); + String nodeName = bfn_.getNodeForRow(new Integer(tourFocus_.y)); if (nodeName == null) { return (null); } @@ -694,29 +756,28 @@ private TourStatus goToDrainZone(boolean selectedOnly) { int colMin; int colMax; - List dropZone = node.getDrainZones(showShadows); + MinMax dropZone = node.getDrainZone(showShadows); MinMax nmm = null; if (dropZone == null) { nmm = node.getColRange(showShadows); colMin = nmm.max; // Yes, both are max colMax = nmm.max; } else { - UiUtil.fixMePrintout("This needs review"); - colMin = dropZone.get(0).min; // QUICK FIX WILL MAKE BETTER SOLUTION LATER - colMax = dropZone.get(0).max; + colMin = dropZone.min; + colMax = dropZone.max; } int start = colMin; int end = colMax; for (int i = start; i <= end; i++) { - Integer testCol = Integer.valueOf(i); + Integer testCol = new Integer(i); if (selectedOnly) { if (!currColSelections_.contains(testCol)) { continue; } } - NID.WithName target = bfn_.getTargetIDForColumn(testCol, showShadows); - NID.WithName source = bfn_.getSourceIDForColumn(testCol, showShadows); + String target = (String)bfn_.getTargetForColumn(testCol, showShadows); + String source = (String)bfn_.getSourceForColumn(testCol, showShadows); if ((target != null) && (source != null)) { if (target.equals(nodeName) || source.equals(nodeName)) { return (handleTourStop(i, tourFocus_.y, testCol, (selectedOnly) ? nodeName : null)); @@ -733,7 +794,7 @@ private TourStatus goToDrainZone(boolean selectedOnly) { */ private TourStatus goLeftRight(int inc, boolean selectedOnly) { - NID.WithName nodeName = bfn_.getNodeIDForRow(Integer.valueOf(tourFocus_.y)); + String nodeName = bfn_.getNodeForRow(new Integer(tourFocus_.y)); if (nodeName == null) { return (null); } @@ -753,14 +814,14 @@ private TourStatus goLeftRight(int inc, boolean selectedOnly) { int start = currCol + inc; int end = (inc == 1) ? colMax : colMin; for (int i = start; (inc == 1) ? (i <= end) : (i >= end); i += inc) { - Integer testCol = Integer.valueOf(i); + Integer testCol = new Integer(i); if (selectedOnly) { if (!currColSelections_.contains(testCol)) { continue; } } - NID.WithName target = bfn_.getTargetIDForColumn(testCol, showShadows); - NID.WithName source = bfn_.getSourceIDForColumn(testCol, showShadows); + String target = (String)bfn_.getTargetForColumn(testCol, showShadows); + String source = (String)bfn_.getSourceForColumn(testCol, showShadows); if ((target != null) && (source != null)) { if (target.equals(nodeName) || source.equals(nodeName)) { return (handleTourStop(i, tourFocus_.y, testCol, (selectedOnly) ? nodeName : null)); @@ -774,10 +835,10 @@ private TourStatus goLeftRight(int inc, boolean selectedOnly) { // boolean nodeAlive = (!selectedOnly) ? true : currNodeSelections_.contains(nodeName); if ((inc == -1) && nodeAlive) { - Rectangle2D targName = nodeNameLocations_.get(nodeName); + Rectangle2D targName = (Rectangle2D)nodeNameLocations_.get(nodeName); Point targNameRC = worldToRowCol(new Point2D.Double(targName.getCenterX(), targName.getCenterY())); int useCol = targNameRC.x; - return (handleTourStop(useCol, tourFocus_.y, Integer.valueOf(useCol), nodeName)); + return (handleTourStop(useCol, tourFocus_.y, new Integer(useCol), nodeName)); } return (null); @@ -789,7 +850,7 @@ private TourStatus goLeftRight(int inc, boolean selectedOnly) { */ private TourStatus goFarLeftRight(boolean goRight, boolean selectedOnly) { - NID.WithName nodeName = bfn_.getNodeIDForRow(Integer.valueOf(tourFocus_.y)); + String nodeName = bfn_.getNodeForRow(new Integer(tourFocus_.y)); if (nodeName == null) { return (null); } @@ -804,10 +865,10 @@ private TourStatus goFarLeftRight(boolean goRight, boolean selectedOnly) { boolean nodeAlive = (!selectedOnly) ? true : currNodeSelections_.contains(nodeName); if (!goRight && nodeAlive) { - Rectangle2D targName = nodeNameLocations_.get(nodeName); + Rectangle2D targName = (Rectangle2D)nodeNameLocations_.get(nodeName); Point targNameRC = worldToRowCol(new Point2D.Double(targName.getCenterX(), targName.getCenterY())); useCol = targNameRC.x; - return (handleTourStop(useCol, tourFocus_.y, Integer.valueOf(useCol), nodeName)); + return (handleTourStop(useCol, tourFocus_.y, new Integer(useCol), nodeName)); } // @@ -819,22 +880,22 @@ private TourStatus goFarLeftRight(boolean goRight, boolean selectedOnly) { int end = tourFocus_.y; int inc = (goRight) ? -1 : 1; for (int i = useCol; (inc == 1) ? (i <= end) : (i >= end); i += inc) { - Integer testCol = Integer.valueOf(i); + Integer testCol = new Integer(i); if (!currColSelections_.contains(testCol)) { continue; } - NID.WithName target = bfn_.getTargetIDForColumn(testCol, showShadows); - NID.WithName source = bfn_.getSourceIDForColumn(testCol, showShadows); + String target = (String)bfn_.getTargetForColumn(testCol, showShadows); + String source = (String)bfn_.getSourceForColumn(testCol, showShadows); if ((target != null) && (source != null)) { - if (target.equals(node.getNodeIDWithName()) || source.equals(node.getNodeIDWithName())) { + if (target.equals(node.nodeName) || source.equals(node.nodeName)) { return (handleTourStop(useCol, tourFocus_.y, testCol, nodeName)); } } } } else { - Integer testCol = Integer.valueOf(useCol); - NID.WithName target = bfn_.getTargetIDForColumn(testCol, showShadows); - NID.WithName source = bfn_.getSourceIDForColumn(testCol, showShadows); + Integer testCol = new Integer(useCol); + String target = (String)bfn_.getTargetForColumn(testCol, showShadows); + String source = (String)bfn_.getSourceForColumn(testCol, showShadows); if ((target != null) && (source != null)) { return (handleTourStop(useCol, tourFocus_.y, testCol, null)); } @@ -847,8 +908,8 @@ private TourStatus goFarLeftRight(boolean goRight, boolean selectedOnly) { ** For finding stops that are selected */ - private SortedSet findSelectedLinkStops(NID.WithName nodeName) { - TreeSet retval = new TreeSet(); + private SortedSet findSelectedLinkStops(String nodeName) { + TreeSet retval = new TreeSet(); boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); BioFabricNetwork.NodeInfo node = bfn_.getNodeDefinition(nodeName); MinMax range = node.getColRange(showShadows); @@ -856,14 +917,14 @@ private SortedSet findSelectedLinkStops(NID.WithName nodeName) { int end = range.max; for (int i = start; i <= end; i++) { - Integer testCol = Integer.valueOf(i); + Integer testCol = new Integer(i); if (!currColSelections_.contains(testCol)) { continue; } - NID.WithName target = bfn_.getTargetIDForColumn(testCol, showShadows); - NID.WithName source = bfn_.getSourceIDForColumn(testCol, showShadows); + String target = (String)bfn_.getTargetForColumn(testCol, showShadows); + String source = (String)bfn_.getSourceForColumn(testCol, showShadows); if ((target != null) && (source != null)) { - if (target.equals(node.getNodeIDWithName()) || source.equals(node.getNodeIDWithName())) { + if (target.equals(node.nodeName) || source.equals(node.nodeName)) { retval.add(testCol); } } @@ -895,13 +956,13 @@ private boolean tourStopIsUnselected(Point focusPoint) { if (currColSelections_.isEmpty() && currNodeSelections_.isEmpty()) { return (false); } - Integer rowObj = Integer.valueOf(focusPoint.y); - Integer colObj = Integer.valueOf(focusPoint.x); + Integer rowObj = new Integer(focusPoint.y); + Integer colObj = new Integer(focusPoint.x); // // Outside of row bounds: // - NID.WithName nodeName = bfn_.getNodeIDForRow(rowObj); + String nodeName = bfn_.getNodeForRow(rowObj); if (nodeName == null) { return (false); } @@ -909,7 +970,7 @@ private boolean tourStopIsUnselected(Point focusPoint) { // // On an name, depends on node selections: // - Rectangle2D targName = nodeNameLocations_.get(nodeName); + Rectangle2D targName = (Rectangle2D)nodeNameLocations_.get(nodeName); Point targNameRC = worldToRowCol(new Point2D.Double(targName.getCenterX(), targName.getCenterY())); boolean onTargName = focusPoint.equals(targNameRC); if (onTargName) { @@ -925,7 +986,7 @@ private boolean tourStopIsUnselected(Point focusPoint) { return (false); } - SortedSet okStops = findSelectedLinkStops(nodeName); + SortedSet okStops = findSelectedLinkStops(nodeName); return (!okStops.contains(colObj)); } @@ -935,14 +996,14 @@ private boolean tourStopIsUnselected(Point focusPoint) { ** Setup and bookkeeping after tour stop is changed */ - private TourStatus handleTourStop(int x, int y, Integer col, NID.WithName selectedOnlyNodeName) { + private TourStatus handleTourStop(int x, int y, Integer col, String selectedOnlyNodeName) { tourFocus_.setLocation(x, y); floaterSet_.tourRect = buildFocusBox(tourFocus_); handleFloaterChange(); centerOnRectangle(floaterSet_.tourRect); fmt_.setCenter(rowColToWorld(tourFocus_), tourFocus_, true); - MouseLocInfo vals = buildMouseLocation(tourFocus_); - SortedSet okStops = (selectedOnlyNodeName == null) ? null : findSelectedLinkStops(selectedOnlyNodeName); + String[] vals = buildMouseLocation(tourFocus_); + SortedSet okStops = (selectedOnlyNodeName == null) ? null : findSelectedLinkStops(selectedOnlyNodeName); boolean nodeAlive = (selectedOnlyNodeName == null) ? true : currNodeSelections_.contains(selectedOnlyNodeName); boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); BioFabricNetwork.LinkInfo ld = bfn_.getLinkDefinition(col, showShadows); @@ -962,7 +1023,7 @@ private TourStatus goUpDown(boolean up, boolean selectedOnly) { return (null); } boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); - Integer useCol = Integer.valueOf(tourFocus_.x); + Integer useCol = new Integer(tourFocus_.x); BioFabricNetwork.LinkInfo link = bfn_.getLinkDefinition(useCol, showShadows); if (link == null) { return (null); @@ -986,7 +1047,7 @@ private TourStatus goUpDown(boolean up, boolean selectedOnly) { useY = link.getStartRow(); } } - return (handleTourStop(useX, useY, useCol, (selectedOnly) ? bfn_.getNodeIDForRow(Integer.valueOf(useY)) : null)); + return (handleTourStop(useX, useY, useCol, (selectedOnly) ? bfn_.getNodeForRow(new Integer(useY)) : null)); } /*************************************************************************** @@ -995,7 +1056,7 @@ private TourStatus goUpDown(boolean up, boolean selectedOnly) { */ public void setToCollectZoomRect() { - bfw_.disableControls(CommandSet.ALLOW_NAV_PUSH, false); + bfw_.disableControls(FabricCommands.ALLOW_NAV_PUSH, false); collectingZoomMode_ = true; firstZoomPoint_ = null; cursorMgr_.showModeCursor(); @@ -1008,7 +1069,7 @@ public void setToCollectZoomRect() { */ public void setToCollectTourStart(boolean selectionOnly) { - bfw_.disableControls(CommandSet.ALLOW_NAV_PUSH, false); + bfw_.disableControls(FabricCommands.ALLOW_NAV_PUSH, false); collectingTourStart_ = true; tourStartSelectionOnly_ = selectionOnly; cursorMgr_.showModeCursor(); @@ -1061,18 +1122,7 @@ public void setScroll(JScrollPane jsp) { jsp_ = jsp; return; } - - /*************************************************************************** - ** - ** - */ - - @Override - public void setBounds(int x, int y, int width, int height) { - super.setBounds(x, y, width, height); - return; - } - + /*************************************************************************** ** ** Update zoom state @@ -1103,10 +1153,8 @@ public void changePaint() { FabricDisplayOptions fdo = FabricDisplayOptionsManager.getMgr().getDisplayOptions(); boolean shadeNodes = fdo.getShadeNodes(); boolean showShadows = fdo.getDisplayShadows(); - painter_.buildObjCache(bfn_.getNodeDefList(), bfn_.getLinkDefList(showShadows), shadeNodes, - showShadows, new HashMap(), new HashMap>()); - selectionPainter_.buildObjCache(targetList_, linkList_, shadeNodes, showShadows, - new HashMap(), new HashMap>()); + painter_.buildObjCache(bfn_.getNodeDefList(), bfn_.getLinkDefList(showShadows), shadeNodes, showShadows, new HashMap(), new HashMap()); + selectionPainter_.buildObjCache(targetList_, linkList_, shadeNodes, showShadows, new HashMap(), new HashMap()); handleFloaterChange(); return; } @@ -1124,10 +1172,10 @@ public void installModel(BioFabricNetwork bfn) { worldRect_ = new Rectangle(-PAD_SIZE_, -PAD_SIZE_, (2 * PAD_SIZE_) + (bfn_.getColumnCount(showShadows) * GRID_SIZE), (2 * PAD_SIZE_) + (bfn_.getRowCount() * GRID_SIZE)); worldDim_ = new Dimension(worldRect_.width, worldRect_.height); zoomSrc_.simpleSetWorkspace(new Workspace(worldRect_)); - nodeNameLocations_ = new HashMap(); - drainNameLocations_ = new HashMap>(); + nodeNameLocations_ = new HashMap(); + drainNameLocations_ = new HashMap(); painter_.buildObjCache(bfn_.getNodeDefList(), bfn_.getLinkDefList(showShadows), shadeNodes, showShadows, nodeNameLocations_, drainNameLocations_); - selectionPainter_.buildObjCache(new ArrayList(), new ArrayList(), shadeNodes, showShadows, new HashMap(), new HashMap>()); + selectionPainter_.buildObjCache(new ArrayList(), new ArrayList(), shadeNodes, showShadows, new HashMap(), new HashMap()); fnt_.haveAModel(true); return; } @@ -1154,10 +1202,10 @@ public void installZooms() { double linkLog = (lco == 0) ? 0 : Math.log(lco) / Math.log(2.0); numZoom_ = Math.max(zoomMap_.size() + 8, (int)Math.ceil(linkLog) - 5); double[] zoomVals = new double[numZoom_]; - Iterator zmit = zoomMap_.keySet().iterator(); + Iterator zmit = zoomMap_.keySet().iterator(); int count = 0; while (zmit.hasNext()) { - Double zoom = zmit.next(); + Double zoom = (Double)zmit.next(); zoomVals[count++] = zoom.doubleValue(); } double val = zoomVals[count - 1]; @@ -1234,7 +1282,6 @@ public void selectionsToSubmodel() { ** Drawing routine */ - @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (bfn_ == null) { @@ -1243,30 +1290,23 @@ public void paintComponent(Graphics g) { Double zoomVal = new Double(zoomer_.getZoomFactor()); Rectangle2D viewInWorld = getViewInWorld(); + // // When we zoom in far enough, we start to draw it instead: // - UiUtil.fixMePrintout("first call is with lo res, shows poor scaling effects. Second call to hi res"); - - Integer numObj = zoomMap_.get(zoomVal); + Integer numObj = (Integer)zoomMap_.get(zoomVal); if ((numObj == null) || (bufferBuilder_ == null)) { Graphics2D g2 = (Graphics2D)g; drawingGuts(g2, viewInWorld); return; } - ArrayList imagesToUse = new ArrayList(); + ArrayList imagesToUse = new ArrayList(); - Iterator wfsit = bufferBuilder_.getWorldsForSize(numObj); - - // - // Image boundary problems will be reduced if we just do the world to viewport transform - // for the upper right and then just add the image tile size to that point? - // - UiUtil.fixMePrintout("implement the above??"); - - while (wfsit.hasNext()) { - Rectangle worldPiece = wfsit.next(); + Iterator wfsit = bufferBuilder_.getWorldsForSize(numObj); + int fillCount = 0; + while (wfsit.hasNext()) { + Rectangle worldPiece = (Rectangle)wfsit.next(); Rectangle2D wpit = viewInWorld.createIntersection(worldPiece); if ((wpit.getWidth() > 10.0) && (wpit.getHeight() > 10.0)) { BufferedImage img = null; @@ -1275,10 +1315,11 @@ public void paintComponent(Graphics g) { } catch (IOException ioex) { System.err.println("Bad load"); } - if (img != null) { + if (img != null) { Point wtv = pointToViewport(worldPiece.getLocation()); int stX = wtv.x; int stY = wtv.y; + fillCount++; ImageToUse itu = new ImageToUse(img, stX, stY); imagesToUse.add(itu); } @@ -1289,9 +1330,9 @@ public void paintComponent(Graphics g) { } Graphics2D g2p = (Graphics2D)g; - Iterator ituit = imagesToUse.iterator(); + Iterator ituit = imagesToUse.iterator(); while (ituit.hasNext()) { - ImageToUse it = ituit.next(); + ImageToUse it = (ImageToUse)ituit.next(); if (it.image != null) { g2p.drawImage(it.image, it.stX, it.stY, null); } @@ -1324,7 +1365,6 @@ private void drawingGuts(Graphics g, Rectangle2D viewRect) { //g2.setBackground(Color.WHITE); //g2.clearRect(clip.x, clip.y, clip.width, clip.height); - g2.setPaint(Color.WHITE); g2.drawRect(clip.x, clip.y, clip.width, clip.height); painter_.paintIt(g2, true, clip, false); @@ -1339,23 +1379,6 @@ private void drawingGuts(Graphics g, Rectangle2D viewRect) { return; } - /*************************************************************************** - ** - ** Drawing routine for printing - */ - - @Override - public void print(Graphics g) { - if (bfn_ == null) { - return; - } - Rectangle2D viewInWorld = getViewInWorld(); - Graphics2D g2 = (Graphics2D)g; - drawingGuts(g2, viewInWorld); - return; - } - - /*************************************************************************** ** ** Drawing core @@ -1396,8 +1419,8 @@ public int print(Graphics g, PageFormat pf, int pageIndex) { Rectangle worldPiece = new Rectangle(-200, -200, worldDim_.width, worldDim_.height); - double wFrac = worldPiece.width / pw; - double hFrac = worldPiece.height / ph; + double wFrac = (double)worldPiece.width / pw; + double hFrac = (double)worldPiece.height / ph; double frac = 1.0 / ((hFrac > wFrac) ? hFrac : wFrac); AffineTransform trans = new AffineTransform(); @@ -1423,12 +1446,12 @@ public int print(Graphics g, PageFormat pf, int pageIndex) { public boolean drawForBuffer(Graphics g, Rectangle clip, Dimension screenDim, Rectangle worldRec) { Graphics2D g2 = (Graphics2D)g; - double zoomH = screenDim.getWidth() / worldRec.getWidth(); - double zoomV = screenDim.getHeight() / worldRec.getHeight(); + double zoomH = (double)screenDim.getWidth() / (double)worldRec.getWidth(); + double zoomV = (double)screenDim.getHeight() / (double)worldRec.getHeight(); double zoom = Math.max(zoomH, zoomV); //Math.min(zoomH, zoomV); Point2D centerW = new Point2D.Double(worldRec.getX() + (worldRec.getWidth() / 2.0), worldRec.getY() + (worldRec.getHeight() / 2.0)); AffineTransform transform = new AffineTransform(); - transform.translate(screenDim.getWidth() / 2.0, screenDim.getHeight() / 2.0); + transform.translate((double)screenDim.getWidth() / 2.0, (double)screenDim.getHeight() / 2.0); transform.scale(zoom, zoom); transform.translate(-centerW.getX(), -centerW.getY()); @@ -1438,6 +1461,9 @@ public boolean drawForBuffer(Graphics g, Rectangle clip, Dimension screenDim, Re g2.setStroke(selectedStroke); g2.setTransform(transform); boolean retval = painter_.paintIt(g2, true, clip, false); + // Debug sizing problems + //g2.setColor(Color.red); + //g2.drawRect(clip.x, clip.y, clip.width - 1, clip.height - 1); return (retval); } @@ -1448,12 +1474,12 @@ public boolean drawForBuffer(Graphics g, Rectangle clip, Dimension screenDim, Re public boolean drawForPrint(Graphics g, Rectangle clip, Dimension screenDim, Rectangle worldRec) { Graphics2D g2 = (Graphics2D)g; - double zoomH = screenDim.getWidth() / worldRec.getWidth(); - double zoomV = screenDim.getHeight() / worldRec.getHeight(); + double zoomH = (double)screenDim.getWidth() / (double)worldRec.getWidth(); + double zoomV = (double)screenDim.getHeight() / (double)worldRec.getHeight(); double zoom = Math.max(zoomH, zoomV); //Math.min(zoomH, zoomV); Point2D centerW = new Point2D.Double(worldRec.getX() + (worldRec.getWidth() / 2.0), worldRec.getY() + (worldRec.getHeight() / 2.0)); AffineTransform transform = new AffineTransform(); - transform.translate(screenDim.getWidth() / 2.0, screenDim.getHeight() / 2.0); + transform.translate((double)screenDim.getWidth() / 2.0, (double)screenDim.getHeight() / 2.0); transform.scale(zoom, zoom); transform.translate(-centerW.getX(), -centerW.getY()); @@ -1570,7 +1596,10 @@ public ZoomCommandSupport getZoomController() { ** Return the required size of the layout */ - public Rectangle getRequiredSize(String genomeKey, String layoutKey) { + public Rectangle getRequiredSize(String genomeKey, String layoutKey, + boolean doComplete, boolean useBuffer, + boolean doModules, boolean doModuleLinks, + String ovrKey, TaggedSet modSet, Map allKeys) { return (worldRect_); } @@ -1594,9 +1623,9 @@ public Rectangle getSelectionSize(String notUsedKey, String notUsedKeyToo) { if (numRect == 0) { return (null); } - Rectangle retval = (Rectangle)(rects_.get(0).clone()); + Rectangle retval = ((Rectangle)((Rectangle)rects_.get(0)).clone()); for (int i = 1; i < numRect; i++) { - Rectangle.union(retval, rects_.get(i), retval); + Rectangle.union(retval, (Rectangle)rects_.get(i), retval); } return (retval); } @@ -1611,7 +1640,7 @@ public Rectangle getCurrentSelectionSize(String genomeKey, String layoutKey) { if (currSel_ == -1) { return (null); } - return (rects_.get(currSel_)); + return ((Rectangle)rects_.get(currSel_)); } /*************************************************************************** @@ -1668,7 +1697,7 @@ private void bumpGuts() { } else { // FIX ME: Have seen cases where currSel_ is larger than rects_ on submodel build? if (currSel_ <= (rects_.size() - 1)) { - Rectangle rect = rects_.get(currSel_); + Rectangle rect = (Rectangle)rects_.get(currSel_); floaterSet_.currSelRect = (Rectangle)rect.clone(); // world coords selFocus_ = worldToRowCol(new Point2D.Double(floaterSet_.currSelRect.getCenterX(), floaterSet_.currSelRect.getCenterY())); fmt_.setCenter(rowColToWorld(selFocus_), selFocus_, true); @@ -1730,8 +1759,8 @@ public void fixCenterPoint(boolean doComplete, UndoSupport support, boolean clos throw new UnsupportedOperationException(); } - public Dimension getBasicSize() { - return (zoomer_.getBasicSize()); + public Dimension getBasicSize(boolean doComplete, boolean doBuffer, int moduleHandling) { + return (zoomer_.getBasicSize(doComplete, doBuffer, moduleHandling)); } public Point2D viewToWorld(Point vPt) { @@ -1747,8 +1776,8 @@ public double getWorkspaceZoom(Dimension viewportDim, double percent) { return (zoomer_.getWorkspaceZoom(viewportDim, percent)); } - public Rectangle getCurrentBasicBounds() { - return (zoomer_.getCurrentBasicBounds()); + public Rectangle getCurrentBasicBounds(boolean doComplete, boolean doBuffer, int moduleHandling) { + return (zoomer_.getCurrentBasicBounds(doComplete, doBuffer, moduleHandling)); } public Rectangle getAllModelBounds() { @@ -1856,54 +1885,33 @@ public Rectangle valsToRect(int sx, int sy, int ex, int ey, boolean convert) { } } - public static class MouseLocInfo { - public String nodeDesc; - public String linkDesc; - public String zoneDesc; - public String linkSrcDesc; - public String linkTrgDesc; - - public MouseLocInfo(String nodeDesc, String linkDesc, String zoneDesc, String linkSrcDesc, String linkTrgDesc) { - this.nodeDesc = nodeDesc; - this.linkDesc = linkDesc; - this.zoneDesc = zoneDesc; - this.linkSrcDesc = linkSrcDesc; - this.linkTrgDesc = linkTrgDesc; - } - - public MouseLocInfo() { - this.nodeDesc = ""; - this.linkDesc = ""; - this.zoneDesc = ""; - this.linkSrcDesc = ""; - this.linkTrgDesc = ""; - } - } - /*************************************************************************** ** ** build mouse location */ - MouseLocInfo buildMouseLocation(Point cprc) { - MouseLocInfo retval = new MouseLocInfo(); - Integer colObj = Integer.valueOf(cprc.x); - NID.WithName target = bfn_.getNodeIDForRow(Integer.valueOf(cprc.y)); + String[] buildMouseLocation(Point cprc) { + String[] retval = new String[3]; + retval[0] = ""; + retval[1] = ""; + retval[2] = ""; + Integer colObj = new Integer(cprc.x); + String target = bfn_.getNodeForRow(new Integer(cprc.y)); boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); - NID.WithName src = bfn_.getSourceIDForColumn(colObj, showShadows); - NID.WithName trg = bfn_.getTargetIDForColumn(colObj, showShadows); - NID.WithName drain = bfn_.getDrainForColumn(colObj, showShadows); + String src = bfn_.getSourceForColumn(colObj, showShadows); + String trg = bfn_.getTargetForColumn(colObj, showShadows); + String drain = bfn_.getDrainForColumn(colObj, showShadows); int numRows = bfn_.getRowCount(); if (target != null) { BioFabricNetwork.NodeInfo ni = bfn_.getNodeDefinition(target); MinMax nimm = ni.getColRange(showShadows); if ((nimm.min <= cprc.x) && (nimm.max >= cprc.x)) { - retval.nodeDesc = target.getName(); + retval[0] = target; } else { - Rectangle2D nnl = nodeNameLocations_.get(target); + Rectangle2D nnl = (Rectangle2D)nodeNameLocations_.get(target); Point2D inWorld = rowColToWorld(cprc); if (nnl.contains(inWorld)) { - retval.nodeDesc = target.getName(); + retval[0] = target; } } } @@ -1913,52 +1921,25 @@ MouseLocInfo buildMouseLocation(Point cprc) { int minRow = li.topRow(); int maxRow = li.bottomRow(); if ((minRow <= cprc.y) && (maxRow >= cprc.y)) { - FabricLink flink = li.getLink(); - retval.linkDesc = flink.toDisplayString(); - retval.linkSrcDesc = flink.getSrcID().getName(); - retval.linkTrgDesc = flink.getTrgID().getName(); + retval[1] = li.getLink().toDisplayString(); } } } if (drain != null) { if ((0 <= cprc.x) && (numRows >= cprc.y)) { - retval.zoneDesc = drain.getName(); + retval[2] = drain; } } return (retval); } - /** - * Iterates through each Rectangle2D in recList to see if it contains Point p - */ - private Rectangle2D findPoint(List recList, Point2D p) { - - for (int i = 0; i < recList.size(); i++) { - if (recList.get(i).contains(p)) return recList.get(i); - } - -// ExceptionHandler.getHandler().displayException( -// new IllegalArgumentException("findPoint(), BioFabricPanel; Point not in recList")); - return null; - } - - /** - * THIS METHOD IS CURRENTLY WRONG. NEED MORE INFO THAT JUST THE NAME TO FIND - * THE CORRECT RECTANGLE2D - */ - private Rectangle2D findPoint(List recList, String nodeName) { - UiUtil.fixMePrintout("This method is currently wrong"); - return recList.get(0); - } - /*************************************************************************** ** ** Run the selection logic */ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt, - boolean showShadows, Set nodes, Set links, - Set cols, boolean shiftPressed) { + boolean showShadows, Set nodes, Set links, Set cols, boolean shiftPressed) { if ((nodeNameLocations_ == null) || (drainNameLocations_ == null)) { @@ -1977,14 +1958,14 @@ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt colRange.init(); nodeRange = new MinMax(); nodeRange.init(); - Iterator cit = cols.iterator(); + Iterator cit = cols.iterator(); while (cit.hasNext()) { - Integer col = cit.next(); + Integer col = (Integer)cit.next(); colRange.update(col.intValue()); } - Iterator nit = nodes.iterator(); + Iterator nit = nodes.iterator(); while (nit.hasNext()) { - NID.WithName node = nit.next(); + String node = (String)nit.next(); int row = bfn_.getNodeDefinition(node).nodeRow; nodeRange.update(row); } @@ -2008,18 +1989,16 @@ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt boolean nodeAdd = false; boolean linkAdd = false; - NID.WithName gotDrain = null; + String gotDrain = null; if (onePt) { Point2D worldPt = viewToWorld(sloc); - Iterator dnlit = drainNameLocations_.keySet().iterator(); + Iterator dnlit = drainNameLocations_.keySet().iterator(); while (dnlit.hasNext()) { - NID.WithName target = dnlit.next(); - List nameLocs = drainNameLocations_.get(target); - for (Rectangle2D zone : nameLocs) { - if (zone.contains(worldPt)) { - gotDrain = target; - break; - } + String target = (String)dnlit.next(); + Rectangle2D nameLoc = (Rectangle2D)drainNameLocations_.get(target); + if (nameLoc.contains(worldPt)) { + gotDrain = target; + break; } } } @@ -2027,9 +2006,9 @@ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt boolean gotLink = false; for (int row = startRow; row <= endRow; row++) { for (int col = startCol; col <= endCol; col++) { - Integer rowObj = Integer.valueOf(row); - Integer colObj = Integer.valueOf(col); - NID.WithName target = bfn_.getNodeIDForRow(rowObj); + Integer rowObj = new Integer(row); + Integer colObj = new Integer(col); + String target = bfn_.getNodeForRow(rowObj); if ((target != null) && (gotDrain == null)) { boolean gotIt = false; if (onePt) { // With one click, can select targets by clicking on row! @@ -2050,7 +2029,7 @@ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt } if (!gotIt) { Point2D worldPt = rowColToWorld(new Point(col, row)); - Rectangle2D nameLoc = nodeNameLocations_.get(target); + Rectangle2D nameLoc = (Rectangle2D)nodeNameLocations_.get(target); if (nameLoc.contains(worldPt)) { if (nodes.contains(target)) { nodes.remove(target); @@ -2077,8 +2056,8 @@ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt } cols.add(colObj); } - NID.WithName src = bfn_.getSourceIDForColumn(colObj, showShadows); - NID.WithName trg = bfn_.getTargetIDForColumn(colObj, showShadows); + String src = bfn_.getSourceForColumn(colObj, showShadows); + String trg = bfn_.getTargetForColumn(colObj, showShadows); if (removeIt) { links.remove(linf.getLink()); } else { @@ -2108,10 +2087,10 @@ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt if (shiftPressed) { if (linkAdd && (colRange.min != Integer.MAX_VALUE)) { for (int i = colRange.min; i < colRange.max; i++) { - Integer colObj = Integer.valueOf(i); + Integer colObj = new Integer(i); cols.add(colObj); - NID.WithName src = bfn_.getSourceIDForColumn(colObj, showShadows); - NID.WithName trg = bfn_.getTargetIDForColumn(colObj, showShadows); + String src = bfn_.getSourceForColumn(colObj, showShadows); + String trg = bfn_.getTargetForColumn(colObj, showShadows); BioFabricNetwork.LinkInfo linf = bfn_.getLinkDefinition(colObj, showShadows); links.add(linf.getLink().clone()); nodes.add(src); @@ -2120,8 +2099,8 @@ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt } if (nodeAdd && (nodeRange.min != Integer.MAX_VALUE)) { for (int i = nodeRange.min; i < nodeRange.max; i++) { - Integer rowObj = Integer.valueOf(i); - NID.WithName target = bfn_.getNodeIDForRow(rowObj); + Integer rowObj = new Integer(i); + String target = bfn_.getNodeForRow(rowObj); nodes.add(target); } } @@ -2134,49 +2113,49 @@ public void selectionLogic(Point rcbp, Point sloc, Rectangle rect, boolean onePt ** Build needed selection geometry */ - public void buildSelectionGeometry(NID.WithName newStartName, Rectangle newStartRect) { + public void buildSelectionGeometry(String newStartName, Rectangle newStartRect) { Point focus = new Point(); boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); // // Create target focus boxes, sorted by row: // targetList_.clear(); - TreeMap sortTargs = new TreeMap(); - Iterator tgit = currNodeSelections_.iterator(); + TreeMap sortTargs = new TreeMap(); + Iterator tgit = currNodeSelections_.iterator(); while (tgit.hasNext()) { - NID.WithName target = tgit.next(); + String target = (String)tgit.next(); BioFabricNetwork.NodeInfo targetInf = bfn_.getNodeDefinition(target); targetList_.add(targetInf); - Rectangle2D targName = nodeNameLocations_.get(target); + Rectangle2D targName = (Rectangle2D)nodeNameLocations_.get(target); Point targNameRC = worldToRowCol(new Point2D.Double(targName.getCenterX(), targName.getCenterY())); focus.setLocation(targNameRC.x, targetInf.nodeRow); - sortTargs.put(Integer.valueOf(targetInf.nodeRow), buildFocusBox(focus)); + sortTargs.put(new Integer(targetInf.nodeRow), buildFocusBox(focus)); } // // Create link focus boxes: // - HashMap> linksByRow = new HashMap>(); + HashMap linksByRow = new HashMap(); linkList_.clear(); - Iterator cit = currColSelections_.iterator(); + Iterator cit = currColSelections_.iterator(); while (cit.hasNext()) { - Integer colObj = cit.next(); + Integer colObj = (Integer)cit.next(); BioFabricNetwork.LinkInfo linf = bfn_.getLinkDefinition(colObj, showShadows); linkList_.add(linf); - Integer strtObj = Integer.valueOf(linf.getStartRow()); - SortedMap lbr = linksByRow.get(strtObj); + Integer strtObj = new Integer(linf.getStartRow()); + TreeMap lbr = (TreeMap)linksByRow.get(strtObj); if (lbr == null) { - lbr = new TreeMap(); + lbr = new TreeMap(); linksByRow.put(strtObj, lbr); } focus.setLocation(linf.getUseColumn(showShadows), linf.getStartRow()); lbr.put(colObj, buildFocusBox(focus)); - Integer endObj = Integer.valueOf(linf.getEndRow()); - lbr = linksByRow.get(endObj); + Integer endObj = new Integer(linf.getEndRow()); + lbr = (TreeMap)linksByRow.get(endObj); if (lbr == null) { - lbr = new TreeMap(); + lbr = new TreeMap(); linksByRow.put(endObj, lbr); } focus.setLocation(linf.getUseColumn(showShadows), linf.getEndRow()); @@ -2187,17 +2166,17 @@ public void buildSelectionGeometry(NID.WithName newStartName, Rectangle newStart Rectangle currRect = ((currSel_ == -1) || (currSel_ >= rects_.size())) ? null : (Rectangle)rects_.get(currSel_); rects_.clear(); - Iterator stit = sortTargs.keySet().iterator(); + Iterator stit = sortTargs.keySet().iterator(); while (stit.hasNext()) { - Integer row = stit.next(); - Rectangle trgRect = sortTargs.get(row); + Integer row = (Integer)stit.next(); + Rectangle trgRect = (Rectangle)sortTargs.get(row); if (trgRect.equals(currRect)) { currSel_ = rects_.size(); - } else if ((newStartName != null) && newStartName.equals(bfn_.getNodeIDForRow(row))) { + } else if ((newStartName != null) && newStartName.equals(bfn_.getNodeForRow(row))) { currSel_ = rects_.size(); } rects_.add(trgRect); - SortedMap ufr = linksByRow.get(row); + TreeMap ufr = (TreeMap)linksByRow.get(row); if (ufr == null) { continue; } @@ -2220,9 +2199,7 @@ public void buildSelectionGeometry(NID.WithName newStartName, Rectangle newStart } bumpGuts(); handleFloaterChange(); - selectionPainter_.buildObjCache(targetList_, linkList_, false, showShadows, - new HashMap(), - new HashMap>()); + selectionPainter_.buildObjCache(targetList_, linkList_, false, showShadows, new HashMap(), new HashMap()); EventManager mgr = EventManager.getManager(); SelectionChangeEvent ev = new SelectionChangeEvent(null, null, SelectionChangeEvent.SELECTED_ELEMENT); mgr.sendSelectionChangeEvent(ev); @@ -2237,7 +2214,7 @@ public void buildSelectionGeometry(NID.WithName newStartName, Rectangle newStart private void resetCurrentSelection(Rectangle newStart) { int numRect = rects_.size(); for (int i = 0 ; i < numRect; i++) { - Rectangle trgRect = rects_.get(i); + Rectangle trgRect = (Rectangle)rects_.get(i); if (trgRect.equals(newStart)) { currSel_ = i; } @@ -2245,6 +2222,8 @@ private void resetCurrentSelection(Rectangle newStart) { return; } + + /*************************************************************************** ** ** Support image export @@ -2278,8 +2257,8 @@ private void exportGuts(Object outObj, String format, ImageExporter.ResolutionSe Rectangle worldPiece = new Rectangle(-200, -200, worldDim_.width, worldDim_.height); if (size == null) { - width = (int)(worldPiece.width * zoom); - height = (int)(worldPiece.height * zoom); + width = (int)((double)worldPiece.width * zoom); + height = (int)((double)worldPiece.height * zoom); } else { width = size.width; height = size.height; @@ -2308,16 +2287,16 @@ public TourStatus startTourFromSelection(boolean selectionOnly) { tourFocus_ = worldToRowCol(new Point2D.Double(floaterSet_.tourRect.getCenterX(), floaterSet_.tourRect.getCenterY())); centerOnRectangle(floaterSet_.tourRect); fmt_.setCenter(rowColToWorld(tourFocus_), tourFocus_, true); - MouseLocInfo vals = buildMouseLocation(tourFocus_); + String[] vals = buildMouseLocation(tourFocus_); handleFloaterChange(); // else tour rect does not redraw boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); - Integer tfx = Integer.valueOf(tourFocus_.x); + Integer tfx = new Integer(tourFocus_.x); BioFabricNetwork.LinkInfo ld = bfn_.getLinkDefinition(tfx, showShadows); if ((ld != null) && !ld.inLinkRowRange(tourFocus_.y)) { ld = null; } - NID.WithName nodeForRow = bfn_.getNodeIDForRow(Integer.valueOf(tourFocus_.y)); - SortedSet okStops = (selectionOnly) ? null : findSelectedLinkStops(nodeForRow); + String nodeForRow = bfn_.getNodeForRow(new Integer(tourFocus_.y)); + SortedSet okStops = (selectionOnly) ? null : findSelectedLinkStops(nodeForRow); boolean nodeAlive = (!selectionOnly) ? true : currNodeSelections_.contains(nodeForRow); return (new TourStatus(vals, bfn_, ld, tourFocus_, okStops, nodeAlive, false)); } @@ -2339,7 +2318,7 @@ private Point findClosestTourStart(Point prtc, int limit) { double minDist = Double.POSITIVE_INFINITY; Point closestRC = new Point(); for (int i = start; i <= end; i++) { - Integer testCol = Integer.valueOf(i); + Integer testCol = new Integer(i); BioFabricNetwork.LinkInfo linf = bfn_.getLinkDefinition(testCol, showShadows); if (linf != null) { if ((linf.getStartRow() >= minY) && (linf.getStartRow() <= maxY)) { @@ -2368,10 +2347,10 @@ private Point findClosestTourStart(Point prtc, int limit) { Point2D inWorldL = rowColToWorld(new Point(prtc.x - limit, prtc.y)); Point2D inWorldR = rowColToWorld(new Point(prtc.x + limit, prtc.y)); for (int i = minY; i <= maxY; i++) { - Integer testRow = Integer.valueOf(i); - NID.WithName nodeName = bfn_.getNodeIDForRow(testRow); + Integer testRow = new Integer(i); + String nodeName = bfn_.getNodeForRow(testRow); if (nodeName != null) { - Rectangle2D nnl = nodeNameLocations_.get(nodeName); + Rectangle2D nnl = (Rectangle2D)nodeNameLocations_.get(nodeName); Point2D nameCenter = new Point2D.Double(nnl.getCenterX(), nnl.getCenterY()); if ((nameCenter.getX() >= inWorldL.getX()) && (nameCenter.getX() <= inWorldR.getX())) { Point2D ncRC = worldToRowCol(nameCenter); @@ -2439,10 +2418,10 @@ public static class TourStatus implements Cloneable { boolean farRightEnabled; boolean currStopUnselected; - TourStatus(MouseLocInfo vals, BioFabricNetwork bfn, BioFabricNetwork.LinkInfo link, - Point navFocus, SortedSet selectedOnly, boolean nodeAlive, boolean stopUnselected) { - nodeName = vals.nodeDesc; - linkName = vals.linkDesc; + TourStatus(String[] vals, BioFabricNetwork bfn, BioFabricNetwork.LinkInfo link, + Point navFocus, SortedSet selectedOnly, boolean nodeAlive, boolean stopUnselected) { + nodeName = vals[0]; + linkName = vals[1]; boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); currStopUnselected = stopUnselected; // Null link means we are sitting on a node label @@ -2465,7 +2444,7 @@ public static class TourStatus implements Cloneable { } else { // int minCol = (selectedOnly == null) ? useNode.minCol : ((Integer)selectedOnly.first()).intValue(); MinMax range = useNode.getColRange(showShadows); - int maxCol = (selectedOnly == null) ? range.max : selectedOnly.last().intValue(); + int maxCol = (selectedOnly == null) ? range.max : ((Integer)selectedOnly.last()).intValue(); upEnabled = (navFocus.y != link.topRow()); downEnabled = (navFocus.y != link.bottomRow()); leftEnabled = (navFocus.x >= range.min) && nodeAlive; @@ -2476,9 +2455,9 @@ public static class TourStatus implements Cloneable { } } - public TourStatus clone() { + public Object clone() { try { - return ((TourStatus)super.clone()); + return (super.clone()); } catch (CloneNotSupportedException cnse) { throw new IllegalStateException(); } @@ -2493,8 +2472,7 @@ public TourStatus clone() { public class MouseHandler extends MouseAdapter { private final static int CLICK_SLOP_ = 2; - - @Override + public void mouseClicked(MouseEvent me) { if (me.isPopupTrigger()) { Point pscreenLoc = me.getComponent().getLocationOnScreen(); @@ -2532,13 +2510,13 @@ private void handleSelection(Point rcbp, Rectangle rect, Point sloc, boolean one } tourFocus_ = newFocus; floaterSet_.tourRect = buildFocusBox(tourFocus_); - MouseLocInfo loc = buildMouseLocation(tourFocus_); - BioFabricNetwork.LinkInfo linf = bfn_.getLinkDefinition(Integer.valueOf(tourFocus_.x), showShadows); + String[] loc = buildMouseLocation(tourFocus_); + BioFabricNetwork.LinkInfo linf = bfn_.getLinkDefinition(new Integer(tourFocus_.x), showShadows); if ((linf != null) && !linf.inLinkRowRange(tourFocus_.y)) { linf = null; } - NID.WithName nodeForRow = bfn_.getNodeIDForRow(Integer.valueOf(tourFocus_.y)); - SortedSet okStops = (forSelOnly) ? findSelectedLinkStops(nodeForRow) : null; + String nodeForRow = bfn_.getNodeForRow(new Integer(tourFocus_.y)); + SortedSet okStops = (forSelOnly) ? findSelectedLinkStops(nodeForRow) : null; boolean nodeAlive = (!forSelOnly) ? true : currNodeSelections_.contains(nodeForRow); fnt_.installNames(new TourStatus(loc, bfn_, linf, tourFocus_, okStops, nodeAlive, tstatUS)); } @@ -2588,6 +2566,11 @@ private void handleSelection(Point rcbp, Rectangle rect, Point sloc, boolean one Rectangle newStart = (onePt) ? buildFocusBox(rcbp) : null; selectionLogic(rcbp, sloc, rect, onePt, showShadows, currNodeSelections_, currLinkSelections_, currColSelections_, shiftPressed); + + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + gaggleSelectionSupport(goose); + } buildSelectionGeometry(null, newStart); return; } @@ -2615,7 +2598,6 @@ private void dragResult(int sx, int sy, int ex, int ey, boolean isCtrl) { } } - @Override public void mousePressed(MouseEvent me) { try { if (me.isPopupTrigger()) { @@ -2636,7 +2618,6 @@ public void mousePressed(MouseEvent me) { return; } - @Override public void mouseEntered(MouseEvent me) { try { bfo_.setMouseIn(true, fmt_.isIgnoring()); @@ -2647,20 +2628,18 @@ public void mouseEntered(MouseEvent me) { return; } - @Override public void mouseExited(MouseEvent me) { try { bfo_.setMouseIn(false, fmt_.isIgnoring()); fmt_.setMouseIn(false); - myLocation_.setNodeAndLink(new MouseLocInfo()); - mov_.showForNode(new MouseLocInfo()); + myLocation_.setNodeAndLink("", "", ""); } catch (Exception ex) { ExceptionHandler.getHandler().displayException(ex); } return; } - @Override + public void mouseReleased(MouseEvent me) { try { // Do this stuff NO MATTER WHAT! @@ -2713,16 +2692,16 @@ private void triggerPopup(int x, int y, Point screenAbs) { try { Point loc = new Point(x, y); Point rcp = transToRowCol(loc); - HashSet nodes = new HashSet(); - HashSet links = new HashSet(); - HashSet cols = new HashSet(); + HashSet nodes = new HashSet(); + HashSet links = new HashSet(); + HashSet cols = new HashSet(); boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); selectionLogic(rcp, loc, null, true, showShadows, nodes, links, cols, false); if (!links.isEmpty()) { - FabricLink fabLink = links.iterator().next(); + FabricLink fabLink = (FabricLink)links.iterator().next(); popCtrl_.showLinkPopup(fabLink, loc); } else if (!nodes.isEmpty()) { - NID.WithName nodeName = nodes.iterator().next(); + String nodeName = (String)nodes.iterator().next(); popCtrl_.showNodePopup(nodeName, loc); } } catch (Exception ex) { @@ -2738,8 +2717,6 @@ private void triggerPopup(int x, int y, Point screenAbs) { */ public class MouseMotionHandler extends MouseMotionAdapter { - - @Override public void mouseDragged(MouseEvent me) { try { if (lastPress_ == null) { @@ -2765,7 +2742,7 @@ public void mouseDragged(MouseEvent me) { if (newY < vMin) newY = vMin; jsp_.getViewport().setViewPosition(new Point(newX, newY)); - jsp_.getViewport().invalidate(); + jsp_.getViewport().invalidate(); jsp_.revalidate(); return; } else if (collectingZoomMode_) { @@ -2781,8 +2758,7 @@ public void mouseDragged(MouseEvent me) { ExceptionHandler.getHandler().displayException(ex); } } - - @Override + public void mouseMoved(MouseEvent me) { try { Point currPt = me.getPoint(); @@ -2793,9 +2769,8 @@ public void mouseMoved(MouseEvent me) { if (bfn_ == null) { return; } - MouseLocInfo vals = buildMouseLocation(cprc); - myLocation_.setNodeAndLink(vals); - mov_.showForNode(vals); + String[] vals = buildMouseLocation(cprc); + myLocation_.setNodeAndLink(vals[0], vals[1], vals[2]); if (collectingZoomMode_) { if (firstZoomPoint_ != null) { Point2D lpw = viewToWorld(firstZoomPoint_); diff --git a/src/org/systemsbiology/biotapestry/biofabric/BioFabricWindow.java b/src/org/systemsbiology/biotapestry/biofabric/BioFabricWindow.java new file mode 100644 index 0000000..0e6d45b --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/BioFabricWindow.java @@ -0,0 +1,552 @@ +/* +** Copyright (C) 2003-2012 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSeparator; +import javax.swing.JToolBar; +import javax.swing.KeyStroke; + +import org.systemsbiology.biotapestry.util.BackgroundWorkerControlManager; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.FixedJComboBox; +import org.systemsbiology.biotapestry.util.ResourceManager; + + +/**************************************************************************** +** +** This is the BioFabric Window! +*/ + +public class BioFabricWindow extends JFrame implements BackgroundWorkerControlManager { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + private BioFabricPanel cp_; + private BioFabricApplication bfa_; + private FabricMagnifyingTool fmt_; + private HashMap actionMap_; + private BioFabricNavAndControl nac_; + private boolean doGaggle_; + private boolean isMain_; + private JButton gaggleInstallButton_; + private JButton gaggleUpdateGooseButton_; + private FixedJComboBox gaggleGooseCombo_; + private JPanel hidingPanel_; + private CardLayout myCard_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE MEMBERS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Constructor + */ + + public BioFabricWindow(Map args, BioFabricApplication bfa, boolean isMain) { + super((isMain) ? "BioFabric" : "BioFabric: Selected Submodel View"); + Boolean doGag = (Boolean)args.get("doGaggle"); + doGaggle_ = (doGag != null) && doGag.booleanValue(); + bfa_ = bfa; + isMain_ = isMain; + actionMap_ = new HashMap(); + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /**************************************************************************** + ** + ** disable + */ + + public void disableControls() { + disableControls(FabricCommands.GENERAL_PUSH, true); + return; + } + + /*************************************************************************** + ** + ** Disable the main controls + */ + + public void disableControls(int pushFlags, boolean displayToo) { + FabricCommands fc = FabricCommands.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); + if (displayToo) { + myCard_.show(hidingPanel_, "Hiding"); + fmt_.enableControls(false); + } + nac_.getNavTool().enableControls(false); + if (gaggleGooseCombo_ != null) { + gaggleGooseCombo_.setEnabled(false); + } + getContentPane().validate(); + fc.pushDisabled(pushFlags); + } + + /**************************************************************************** + ** + ** enable + */ + + public void reenableControls() { + FabricCommands fc = FabricCommands.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); + fc.popDisabled(); + myCard_.show(hidingPanel_, "SUPanel"); + fmt_.enableControls(true); + nac_.getNavTool().enableControls(true); + + if (gaggleGooseCombo_ != null) { + gaggleGooseCombo_.setEnabled(true); + } + + getContentPane().validate(); + + // + // Following background thread operations, sometimes we need to + // get keyboard focus back to the network panel: + // + // We make this conditional to keep it from being called in normal operation as + // the genome is changed, which causes the time slider to lose focus EVERY + // TIME IT IS MOVED!!!!!!! + + // if (withFocus) { + // sup_.requestFocus(); + // } + + return; + } + + /**************************************************************************** + ** + ** also redraw.... + */ + + public void redraw() { + cp_.repaint(); + return; + } + + /*************************************************************************** + ** + ** Get it up and running + */ + + public void initWindow() { + JPanel cpane = (JPanel)getContentPane(); + ((JComponent)cpane).getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ESCAPE"), "BioTapCancel"); + ((JComponent)cpane).getActionMap().put("BioTapCancel", new AbstractAction() { + public void actionPerformed(ActionEvent e) { + try { + AbstractAction aa = (AbstractAction)actionMap_.get(new Integer(FabricCommands.CANCEL)); + aa.actionPerformed(null); + return; + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + FabricCommands fc = FabricCommands.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); + JToolBar toolBar = null; + JMenu gaggleGooseChooseMenu = (doGaggle_) ? new JMenu(ResourceManager.getManager().getString("command.gooseChoose")) : null; + gaggleGooseCombo_ = (doGaggle_) ? new FixedJComboBox(250) : null; + fc.setGaggleElements(gaggleGooseChooseMenu, gaggleGooseCombo_); + + menuInstall(fc, isMain_, gaggleGooseChooseMenu); + toolBar = new JToolBar(); + stockActionMap(fc, isMain_); + stockToolBar(toolBar, isMain_, fc); + nac_ = new BioFabricNavAndControl(isMain_, this); + fmt_ = nac_.getFMT(); + cp_ = new BioFabricPanel(fc.getColorGenerator(), bfa_, fmt_, nac_.getOverview(), nac_.getNavTool(), isMain_, this); + fc.setFabricPanel(cp_); + nac_.setFabricPanel(cp_); + cp_.setFabricLocation(nac_.getFabricLocation()); + cp_.setBackground(Color.white); + + JScrollPane jsp = new JScrollPane(cp_); + cp_.setScroll(jsp); + // GOTTA USE THIS ON MY LINUX BOX, BUT NOWHERE ELSE!!!! + //jsp.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); + cp_.getZoomController().registerScrollPaneAndZoomTarget(jsp, cp_); + + cpane.setLayout(new BorderLayout()); + + if (toolBar != null) { + cpane.add(toolBar, BorderLayout.NORTH); + } + + hidingPanel_ = new JPanel(); + myCard_ = new CardLayout(); + hidingPanel_.setLayout(myCard_); + hidingPanel_.add(jsp, "SUPanel"); + JPanel blankPanel = new JPanel(); + blankPanel.setBackground(Color.white); + hidingPanel_.add(blankPanel, "Hiding"); + + cpane.add(hidingPanel_, BorderLayout.CENTER); + cpane.add(nac_, BorderLayout.SOUTH); + + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/BioFab16White.gif"); + setIconImage(new ImageIcon(ugif).getImage()); + setResizable(true); + fc.checkForChanges(); + return; + } + + /*************************************************************************** + ** + ** Call to let us know new gaggle commands are available + */ + + public void haveInboundGaggleCommands() { + FabricCommands fc = FabricCommands.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); + fc.triggerGaggleState(FabricCommands.GAGGLE_PROCESS_INBOUND, true); + return; + } + + /*************************************************************************** + ** + ** Call to let us know gaggle geese have changed + */ + + public void haveGaggleGooseChange() { + FabricCommands fc = FabricCommands.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); + fc.triggerGaggleState(FabricCommands.GAGGLE_GOOSE_UPDATE, true); + return; + } + + /*************************************************************************** + ** + ** Call to let us know gaggle geese have changed + */ + + public void connectedToGaggle(boolean connected) { + FabricCommands fc = FabricCommands.getCmds((isMain_) ? "mainWindow" : "selectionWindow"); + fc.getAction(FabricCommands.GAGGLE_CONNECT, true, null).setEnabled(!connected); + fc.getAction(FabricCommands.GAGGLE_DISCONNECT, true, null).setEnabled(connected); + fc.getAction(FabricCommands.GAGGLE_CONNECT, false, null).setEnabled(!connected); + fc.getAction(FabricCommands.GAGGLE_DISCONNECT, false, null).setEnabled(connected); + return; + } + + /*************************************************************************** + ** + ** Drawing core + */ + + public void stopBufferBuilding() { + cp_.shutdown(); + return; + } + + /*************************************************************************** + ** + ** Drawing core + */ + + public BioFabricApplication getApplication() { + return (bfa_); + } + + /*************************************************************************** + ** + ** Drawing core + */ + + public BioFabricPanel getFabricPanel() { + return (cp_); + } + + /*************************************************************************** + ** + ** Drawing core + */ + + public BioFabricOverview getOverview() { + return (nac_.getOverview()); + } + + /*************************************************************************** + ** + ** Menu install + */ + + private void menuInstall(FabricCommands fc, boolean isMain, JMenu gaggleGooseChooseMenu) { + ResourceManager rMan = ResourceManager.getManager(); + JMenuBar menuBar = new JMenuBar(); + + if (isMain) { + JMenu fMenu = new JMenu(rMan.getString("command.File")); + fMenu.setMnemonic(rMan.getChar("command.FileMnem")); + menuBar.add(fMenu); + fMenu.add(fc.getAction(FabricCommands.LOAD_XML, false, null)); + fMenu.add(fc.getAction(FabricCommands.SAVE, false, null)); + fMenu.add(fc.getAction(FabricCommands.SAVE_AS, false, null)); + fMenu.add(new JSeparator()); + JMenu importMenu = new JMenu(rMan.getString("command.importMenu")); + importMenu.setMnemonic(rMan.getChar("command.importMenuMnem")); + fMenu.add(importMenu); + importMenu.add(fc.getAction(FabricCommands.LOAD, false, null)); + importMenu.add(fc.getAction(FabricCommands.LOAD_WITH_NODE_ATTRIBUTES, false, null)); + JMenu exportMenu = new JMenu(rMan.getString("command.exportMenu")); + exportMenu.setMnemonic(rMan.getChar("command.exportMenuMnem")); + fMenu.add(exportMenu); + exportMenu.add(fc.getAction(FabricCommands.EXPORT_IMAGE, false, null)); + exportMenu.add(fc.getAction(FabricCommands.EXPORT_IMAGE_PUBLISH, false, null)); + exportMenu.add(new JSeparator()); + exportMenu.add(fc.getAction(FabricCommands.EXPORT_NODE_ORDER, false, null)); + exportMenu.add(fc.getAction(FabricCommands.EXPORT_LINK_ORDER, false, null)); + exportMenu.add(new JSeparator()); + exportMenu.add(fc.getAction(FabricCommands.EXPORT_SELECTED_NODES, false, null)); + fMenu.add(new JSeparator()); + fMenu.add(fc.getAction(FabricCommands.EMPTY_NETWORK, false, null)); + fMenu.add(new JSeparator()); + fMenu.add(fc.getAction(FabricCommands.PRINT, false, null)); + fMenu.add(new JSeparator()); + fMenu.add(fc.getAction(FabricCommands.CLOSE, false, null)); + } else { + JMenu fMenu = new JMenu(rMan.getString("command.File")); + fMenu.setMnemonic(rMan.getChar("command.FileMnem")); + menuBar.add(fMenu); + JMenu exportMenu = new JMenu(rMan.getString("command.exportMenu")); + exportMenu.setMnemonic(rMan.getChar("command.exportMenuMnem")); + fMenu.add(exportMenu); + exportMenu.add(fc.getAction(FabricCommands.EXPORT_IMAGE, false, null)); + exportMenu.add(fc.getAction(FabricCommands.EXPORT_IMAGE_PUBLISH, false, null)); + exportMenu.add(new JSeparator()); + exportMenu.add(fc.getAction(FabricCommands.EXPORT_SELECTED_NODES, false, null)); + } + + JMenu eMenu = new JMenu(rMan.getString("command.Edit")); + eMenu.setMnemonic(rMan.getChar("command.EditMnem")); + menuBar.add(eMenu); + eMenu.add(fc.getAction(FabricCommands.CLEAR_SELECTIONS, false, null)); + eMenu.add(fc.getAction(FabricCommands.ADD_FIRST_NEIGHBORS, false, null)); + if (isMain) { + eMenu.add(fc.getAction(FabricCommands.PROPAGATE_DOWN, false, null)); + } + Action bsa = fc.getAction(FabricCommands.BUILD_SELECT, false, null); + JCheckBoxMenuItem jcb = new JCheckBoxMenuItem(bsa); + jcb.setSelected(true); + eMenu.add(jcb); + eMenu.add(new JSeparator()); + eMenu.add(fc.getAction(FabricCommands.SET_DISPLAY_OPTIONS, false, null)); + + JMenu vMenu = new JMenu(rMan.getString("command.View")); + vMenu.setMnemonic(rMan.getChar("command.ViewMnem")); + menuBar.add(vMenu); + vMenu.add(fc.getAction(FabricCommands.ZOOM_OUT, false, null)); + vMenu.add(fc.getAction(FabricCommands.ZOOM_IN, false, null)); + vMenu.add(fc.getAction(FabricCommands.ZOOM_TO_MODEL, false, null)); + vMenu.add(fc.getAction(FabricCommands.ZOOM_TO_RECT, false, null)); + vMenu.add(fc.getAction(FabricCommands.ZOOM_TO_CURRENT_MOUSE, false, null)); + vMenu.add(fc.getAction(FabricCommands.ZOOM_TO_CURRENT_MAGNIFY, false, null)); + vMenu.add(fc.getAction(FabricCommands.ZOOM_TO_SELECTIONS, false, null)); + vMenu.add(new JSeparator()); + vMenu.add(fc.getAction(FabricCommands.CENTER_ON_PREVIOUS_SELECTION, false, null)); + vMenu.add(fc.getAction(FabricCommands.ZOOM_TO_CURRENT_SELECTION, false, null)); + vMenu.add(fc.getAction(FabricCommands.CENTER_ON_NEXT_SELECTION, false, null)); + + // + // Tools Menu + // + + JMenu sMenu = new JMenu(rMan.getString("command.Tools")); + sMenu.setMnemonic(rMan.getChar("command.ToolsMnem")); + menuBar.add(sMenu); + sMenu.add(fc.getAction(FabricCommands.SEARCH, false, null)); + sMenu.add(fc.getAction(FabricCommands.COMPARE_NODES, false, null)); + + // + // Layout Menu + // + + JMenu lMenu = new JMenu(rMan.getString("command.Layout")); + lMenu.setMnemonic(rMan.getChar("command.LayoutMnem")); + menuBar.add(lMenu); + lMenu.add(fc.getAction(FabricCommands.DEFAULT_LAYOUT, false, null)); + lMenu.add(fc.getAction(FabricCommands.RELAYOUT_USING_CONNECTIVITY, false, null)); + lMenu.add(fc.getAction(FabricCommands.RELAYOUT_USING_SHAPE_MATCH, false, null)); + lMenu.add(fc.getAction(FabricCommands.LAYOUT_NODES_VIA_ATTRIBUTES, false, null)); + lMenu.add(fc.getAction(FabricCommands.LAYOUT_LINKS_VIA_ATTRIBUTES, false, null)); + lMenu.add(fc.getAction(FabricCommands.SET_LINK_GROUPS, false, null)); + + // + // Gaggle Menu + // + + if (doGaggle_) { + JMenu gMenu = new JMenu(rMan.getString("command.Gaggle")); + gMenu.setMnemonic(rMan.getChar("command.GaggleMnem")); + menuBar.add(gMenu); + gMenu.add(gaggleGooseChooseMenu); + gMenu.add(fc.getAction(FabricCommands.GAGGLE_GOOSE_UPDATE, false, null)); + gMenu.add(fc.getAction(FabricCommands.GAGGLE_RAISE_GOOSE, false, null)); + gMenu.add(fc.getAction(FabricCommands.GAGGLE_LOWER_GOOSE, false, null)); + gMenu.add(fc.getAction(FabricCommands.GAGGLE_SEND_NETWORK, false, null)); + gMenu.add(fc.getAction(FabricCommands.GAGGLE_SEND_NAMELIST, false, null)); + gMenu.add(fc.getAction(FabricCommands.GAGGLE_PROCESS_INBOUND, false, null)); + gMenu.add(fc.getAction(FabricCommands.GAGGLE_CONNECT, false, null)); + gMenu.add(fc.getAction(FabricCommands.GAGGLE_DISCONNECT, false, null)); + } + + JMenu hMenu = new JMenu(rMan.getString("command.Help")); + hMenu.setMnemonic(rMan.getChar("command.HelpMnem")); + menuBar.add(hMenu); + hMenu.add(fc.getAction(FabricCommands.ABOUT, false, null)); + + setJMenuBar(menuBar); + return; + } + + /*************************************************************************** + ** + ** Stock the action map + */ + + private void stockActionMap(FabricCommands fc, boolean isMain) { + actionMap_.put(new Integer(FabricCommands.SEARCH), fc.getAction(FabricCommands.SEARCH, true, null)); + actionMap_.put(new Integer(FabricCommands.ZOOM_OUT), fc.getAction(FabricCommands.ZOOM_OUT, true, null)); + actionMap_.put(new Integer(FabricCommands.ZOOM_IN), fc.getAction(FabricCommands.ZOOM_IN, true, null)); + actionMap_.put(new Integer(FabricCommands.ADD_FIRST_NEIGHBORS), fc.getAction(FabricCommands.ADD_FIRST_NEIGHBORS, true, null)); + actionMap_.put(new Integer(FabricCommands.CLEAR_SELECTIONS), fc.getAction(FabricCommands.CLEAR_SELECTIONS, true, null)); + actionMap_.put(new Integer(FabricCommands.ZOOM_TO_MODEL), fc.getAction(FabricCommands.ZOOM_TO_MODEL, true, null)); + actionMap_.put(new Integer(FabricCommands.ZOOM_TO_SELECTIONS), fc.getAction(FabricCommands.ZOOM_TO_SELECTIONS, true, null)); + actionMap_.put(new Integer(FabricCommands.ZOOM_TO_RECT), fc.getAction(FabricCommands.ZOOM_TO_RECT, true, null)); + actionMap_.put(new Integer(FabricCommands.CANCEL), fc.getAction(FabricCommands.CANCEL, true, null)); + actionMap_.put(new Integer(FabricCommands.ZOOM_TO_CURRENT_SELECTION), fc.getAction(FabricCommands.ZOOM_TO_CURRENT_SELECTION, true, null)); + actionMap_.put(new Integer(FabricCommands.CENTER_ON_NEXT_SELECTION), fc.getAction(FabricCommands.CENTER_ON_NEXT_SELECTION, true, null)); + actionMap_.put(new Integer(FabricCommands.CENTER_ON_PREVIOUS_SELECTION), fc.getAction(FabricCommands.CENTER_ON_PREVIOUS_SELECTION, true, null)); + + if (isMain) { + actionMap_.put(new Integer(FabricCommands.PROPAGATE_DOWN), fc.getAction(FabricCommands.PROPAGATE_DOWN, true, null)); + } + if (doGaggle_) { + actionMap_.put(new Integer(FabricCommands.GAGGLE_GOOSE_UPDATE), fc.getAction(FabricCommands.GAGGLE_GOOSE_UPDATE, true, null)); + actionMap_.put(new Integer(FabricCommands.GAGGLE_RAISE_GOOSE), fc.getAction(FabricCommands.GAGGLE_RAISE_GOOSE, true, null)); + actionMap_.put(new Integer(FabricCommands.GAGGLE_LOWER_GOOSE), fc.getAction(FabricCommands.GAGGLE_LOWER_GOOSE, true, null)); + actionMap_.put(new Integer(FabricCommands.GAGGLE_SEND_NETWORK), fc.getAction(FabricCommands.GAGGLE_SEND_NETWORK, true, null)); + actionMap_.put(new Integer(FabricCommands.GAGGLE_SEND_NAMELIST), fc.getAction(FabricCommands.GAGGLE_SEND_NAMELIST, true, null)); + actionMap_.put(new Integer(FabricCommands.GAGGLE_PROCESS_INBOUND), fc.getAction(FabricCommands.GAGGLE_PROCESS_INBOUND, true, null)); + actionMap_.put(new Integer(FabricCommands.GAGGLE_CONNECT), fc.getAction(FabricCommands.GAGGLE_CONNECT, true, null)); + actionMap_.put(new Integer(FabricCommands.GAGGLE_DISCONNECT), fc.getAction(FabricCommands.GAGGLE_DISCONNECT, true, null)); + } + return; + } + + /*************************************************************************** + ** + ** Stock the tool bar + */ + + private void stockToolBar(JToolBar toolBar, boolean isMain, FabricCommands fc) { + toolBar.removeAll(); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.ZOOM_OUT))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.ZOOM_IN))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.ZOOM_TO_MODEL))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.ZOOM_TO_RECT))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.ZOOM_TO_SELECTIONS))); + toolBar.addSeparator(); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.CENTER_ON_PREVIOUS_SELECTION))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.ZOOM_TO_CURRENT_SELECTION))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.CENTER_ON_NEXT_SELECTION))); + toolBar.addSeparator(); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.ADD_FIRST_NEIGHBORS))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.CLEAR_SELECTIONS))); + toolBar.addSeparator(); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.CANCEL))); + toolBar.addSeparator(); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.SEARCH))); + if (isMain) { + toolBar.addSeparator(); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.PROPAGATE_DOWN))); + } + + if (doGaggle_) { + boolean updateMcmd = false; + toolBar.addSeparator(); + if (gaggleUpdateGooseButton_ == null) { + AbstractAction gaggleUpdate = (AbstractAction)actionMap_.get(new Integer(FabricCommands.GAGGLE_GOOSE_UPDATE)); + gaggleUpdateGooseButton_ = toolBar.add(gaggleUpdate); + updateMcmd = true; + } else { + toolBar.add(gaggleUpdateGooseButton_); + } + toolBar.add(gaggleGooseCombo_); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.GAGGLE_RAISE_GOOSE))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.GAGGLE_LOWER_GOOSE))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.GAGGLE_SEND_NETWORK))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.GAGGLE_SEND_NAMELIST))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.GAGGLE_CONNECT))); + toolBar.add((AbstractAction)actionMap_.get(new Integer(FabricCommands.GAGGLE_DISCONNECT))); + if (gaggleInstallButton_ == null) { + AbstractAction gaggleInstall = (AbstractAction)actionMap_.get(new Integer(FabricCommands.GAGGLE_PROCESS_INBOUND)); + gaggleInstallButton_ = toolBar.add(gaggleInstall); + updateMcmd = true; + } else { + toolBar.add(gaggleInstallButton_); + } + if (updateMcmd) { + fc.setGaggleButtons(gaggleInstallButton_, gaggleUpdateGooseButton_, gaggleInstallButton_.getBackground()); + } + } + return; + } +} \ No newline at end of file diff --git a/src/org/systemsbiology/biofabric/ui/BrowserLauncher.java b/src/org/systemsbiology/biotapestry/biofabric/BrowserLauncher.java similarity index 84% rename from src/org/systemsbiology/biofabric/ui/BrowserLauncher.java rename to src/org/systemsbiology/biotapestry/biofabric/BrowserLauncher.java index 1033cb8..365f11d 100644 --- a/src/org/systemsbiology/biofabric/ui/BrowserLauncher.java +++ b/src/org/systemsbiology/biotapestry/biofabric/BrowserLauncher.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -20,7 +20,7 @@ ** comments below! */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.biofabric; import java.lang.reflect.Method; import java.net.URI; @@ -73,11 +73,11 @@ public void openBBURL(String url) { URI myUri = new URI(url); Object[] uriArr = new Object[] {myUri}; - Class d = Class.forName("java.awt.Desktop"); + Class d = Class.forName("java.awt.Desktop"); Method gdm = d.getDeclaredMethod("getDesktop", (Class[])null); Object deskObj = gdm.invoke(null, (Object[])null); - Class[] uric = new Class[] {java.net.URI.class}; + Class[] uric = new Class[] {java.net.URI.class}; Method meth = d.getDeclaredMethod("browse", uric); meth.invoke(deskObj, uriArr); @@ -85,8 +85,8 @@ public void openBBURL(String url) { String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { - Class fm = Class.forName("com.apple.eio.FileManager"); - Class[] sar = new Class[] {String.class}; + Class fm = Class.forName("com.apple.eio.FileManager"); + Class[] sar = new Class[] {String.class}; Method orl = fm.getDeclaredMethod("openURL", sar); orl.invoke(null, new Object[] {url}); } else if (osName.startsWith("Windows")) { @@ -114,4 +114,16 @@ public void openBBURL(String url) { } return; } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC STATIC METHODS + // + //////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// + } diff --git a/src/org/systemsbiology/biofabric/ui/render/BufBuildDrawer.java b/src/org/systemsbiology/biotapestry/biofabric/BufBuildDrawer.java similarity index 96% rename from src/org/systemsbiology/biofabric/ui/render/BufBuildDrawer.java rename to src/org/systemsbiology/biotapestry/biofabric/BufBuildDrawer.java index 0733fdd..2b6cb5e 100644 --- a/src/org/systemsbiology/biofabric/ui/render/BufBuildDrawer.java +++ b/src/org/systemsbiology/biotapestry/biofabric/BufBuildDrawer.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.render; +package org.systemsbiology.biotapestry.biofabric; import java.awt.Dimension; import java.awt.Graphics; diff --git a/src/org/systemsbiology/biofabric/ui/render/BufferBuilder.java b/src/org/systemsbiology/biotapestry/biofabric/BufferBuilder.java similarity index 62% rename from src/org/systemsbiology/biofabric/ui/render/BufferBuilder.java rename to src/org/systemsbiology/biotapestry/biofabric/BufferBuilder.java index f45e3fd..7f9f57d 100644 --- a/src/org/systemsbiology/biofabric/ui/render/BufferBuilder.java +++ b/src/org/systemsbiology/biotapestry/biofabric/BufferBuilder.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,15 +17,13 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.render; +package org.systemsbiology.biotapestry.biofabric; -import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.PixelGrabber; @@ -39,9 +37,7 @@ import java.util.Map; import javax.swing.SwingUtilities; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.ui.FabricDisplayOptionsManager; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.UiUtil; /**************************************************************************** ** @@ -57,18 +53,12 @@ public class BufferBuilder { //////////////////////////////////////////////////////////////////////////// // - // Tweak the slice height up by one, else rounding/trunc errors introduce white + // Tweak the slice height up by one, else rounding/truc errors introduce white // gridding on the image mosaic! // private static final int SLICE_HEIGHT_HACK_ = 1; - // - // Don't build slices smaller than this dimension: - // - - private static final int MIN_DIM_ = 100; - //////////////////////////////////////////////////////////////////////////// // // PUBLIC CONSTANTS @@ -86,7 +76,7 @@ public class BufferBuilder { // private ImageCache cache_; - private HashMap> worldToImageName_; + private HashMap worldToImageName_; private BufBuildDrawer drawer_; private int[] bbZooms_; private Dimension screenDim_; @@ -109,7 +99,7 @@ public class BufferBuilder { public BufferBuilder(String cachePref, int maxMeg, BufBuildDrawer drawer) { cache_ = new ImageCache(cachePref, maxMeg); - worldToImageName_ = new HashMap>(); + worldToImageName_ = new HashMap(); drawer_ = drawer; bbc_ = null; timeToExit_ = false; @@ -122,7 +112,7 @@ public BufferBuilder(String cachePref, int maxMeg, BufBuildDrawer drawer) { public BufferBuilder(BufBuildDrawer drawer) { drawer_ = drawer; - worldToImageName_ = new HashMap>(); + worldToImageName_ = new HashMap(); bbc_ = null; timeToExit_ = false; } @@ -158,12 +148,12 @@ public BufferedImage buildOneBuf(int[] zooms) { screenDim_ = new Dimension(); worldDim_ = new Dimension(); drawer_.dimsForBuf(screenDim_, worldDim_); - HashMap worldForSize = new HashMap(); - Integer key = Integer.valueOf(0); + HashMap worldForSize = new HashMap(); + Integer key = new Integer(0); worldToImageName_.put(key, worldForSize); - buildPieceMap(zooms[0], screenDim_, worldDim_, true, worldForSize); - Map worldForSizex = worldToImageName_.get(key); - Rectangle worldPiece = worldForSizex.keySet().iterator().next(); + buildPieceMap(zooms[0], worldDim_, worldForSize); + HashMap worldForSizex = (HashMap)worldToImageName_.get(key); + Rectangle worldPiece = (Rectangle)worldForSizex.keySet().iterator().next(); BufferedImage bi = new BufferedImage(screenDim_.width, screenDim_.height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.setColor(Color.WHITE); @@ -185,48 +175,28 @@ public BufferedImage buildBufs(int[] zooms, BufferBuilderClient bbc, int maxSize screenDim_ = new Dimension(); worldDim_ = new Dimension(); drawer_.dimsForBuf(screenDim_, worldDim_); - HashMap limitOffering = null; - for (int i = 0; i < zooms.length; i++) { - // - // We do not allow the tesselation size to drop below a minimum image dimension. If we actually hit that - // limit for BOTH dimensions just use the last minimum: - // - if (limitOffering != null) { - Integer key = Integer.valueOf(i); - HashMap worldForSize = new HashMap(); - Iterator wpoKit = limitOffering.keySet().iterator(); - while (wpoKit.hasNext()) { - Rectangle rkey = wpoKit.next(); - WorldPieceOffering wpo = limitOffering.get(rkey); - worldForSize.put((Rectangle)rkey.clone(), wpo.clone()); - } - worldToImageName_.put(key, worldForSize); - } else { - HashMap worldForSize = new HashMap(); - Integer key = Integer.valueOf(i); - worldToImageName_.put(key, worldForSize); - boolean gottaStop = buildPieceMap(zooms[i], screenDim_, worldDim_, false, worldForSize); - if (gottaStop) { - limitOffering = worldForSize; - } - } + for (int i = 0; i < zooms.length; i++) { + HashMap worldForSize = new HashMap(); + Integer key = new Integer(i); + worldToImageName_.put(key, worldForSize); + buildPieceMap(zooms[i], worldDim_, worldForSize); } // // Build the first two zoom levels before we even get started: // - List requestQueuePre = buildQueue(0, 1, 10); + List requestQueuePre = buildQueue(0, 1, 10); while (!requestQueuePre.isEmpty()) { - QueueRequest qr = requestQueuePre.remove(0); - buildBuffer(new Dimension(qr.imageDim.width, qr.imageDim.height), qr); + QueueRequest qr = (QueueRequest)requestQueuePre.remove(0); + buildBuffer(screenDim_, qr); } // // Now build up the requests for the background thread: // - List requestQueue = (zooms.length > 2) ? buildQueue(2, zooms.length - 1, maxSize) : new ArrayList(); + List requestQueue = (zooms.length > 2) ? buildQueue(2, zooms.length - 1, maxSize) : new ArrayList(); bbc_ = bbc; @@ -242,26 +212,26 @@ public BufferedImage buildBufs(int[] zooms, BufferBuilderClient bbc, int maxSize /*************************************************************************** ** - ** Get all worlds for given size + ** Drawing routine */ - public Iterator getWorldsForSize(Integer size) { - Map worldForSize = worldToImageName_.get(size); - HashSet setOfKeys = new HashSet(worldForSize.keySet()); + public Iterator getWorldsForSize(Integer size) { + Map worldForSize = (Map)worldToImageName_.get(size); + HashSet setOfKeys = new HashSet(worldForSize.keySet()); return (setOfKeys.iterator()); } /*************************************************************************** ** - ** Get the top buffered image + ** Drawing routine */ public BufferedImage getTopImage() throws IOException { - Map worldForSize = worldToImageName_.get(Integer.valueOf(0)); - WorldPieceOffering wpo = worldForSize.values().iterator().next(); + Map worldForSize = (Map)worldToImageName_.get(new Integer(0)); + WorldPieceOffering wpo = (WorldPieceOffering)worldForSize.values().iterator().next(); BufferedImage retval = null; synchronized (this) { - retval = cache_.getAnImage(wpo.cacheHandle); + retval = (BufferedImage)cache_.getAnImage(wpo.cacheHandle); } return (retval); } @@ -272,20 +242,20 @@ public BufferedImage getTopImage() throws IOException { */ public BufferedImage getImageForSizeAndPiece(Integer size, Rectangle worldPiece) throws IOException { - Map worldForSize = worldToImageName_.get(size); - WorldPieceOffering wpo = worldForSize.get(worldPiece); - // FIX METhis is assuming that write to handle is atomic??? + Map worldForSize = (Map)worldToImageName_.get(size); + WorldPieceOffering wpo = (WorldPieceOffering)worldForSize.get(worldPiece); + // This is assuming that write to handle is atomic??? if (wpo.cacheHandle == null) { buildLoResSlice(bbZooms_[size.intValue()], screenDim_, worldDim_, worldPiece, worldForSize); if (biw_ != null) { - biw_.bumpRequest(new QueueRequest(size, new Rectangle(wpo.imgWidth, wpo.imgHeight), worldPiece)); + biw_.bumpRequest(new QueueRequest(size, worldPiece)); } } BufferedImage retval = null; // This stalls a lot on big images, perhaps while files are being written out? synchronized (this) { if ((wpo.cacheHandle != null) && !wpo.cacheHandle.equals("")) { - retval = cache_.getAnImage(wpo.cacheHandle); + retval = (BufferedImage)cache_.getAnImage(wpo.cacheHandle); } } return (retval); @@ -296,42 +266,16 @@ public BufferedImage getImageForSizeAndPiece(Integer size, Rectangle worldPiece) ** generate piece map */ - private boolean buildPieceMap(int zoomNum, Dimension baseImageDim, Dimension worldDim, boolean force, Map worldForSize) { - // - // On very large, very high aspect ratio networks, we can get cases where the height of the piece is zero - // pixels. Don't let this happen. Also seeing on tiny networks. - // - boolean wIsMin = false; - boolean hIsMin = false; - - int useWidth = baseImageDim.width; - int useHeight = baseImageDim.height; - - int effectiveZoomNumX = zoomNum; - int worldWInc = worldDim.width / zoomNum; - if ((worldWInc < MIN_DIM_) && !force) { - useWidth = (int)Math.ceil(baseImageDim.width * ((double)MIN_DIM_ / worldWInc)); - worldWInc = MIN_DIM_; - effectiveZoomNumX = (int)Math.ceil((double)worldDim.width / worldWInc); - wIsMin = true; - } - - int effectiveZoomNumY = zoomNum; - int worldHInc = worldDim.height / zoomNum; - if ((worldHInc < MIN_DIM_) && !force) { - useHeight = (int)Math.ceil(baseImageDim.height * ((double)MIN_DIM_ / worldHInc)); - worldHInc = MIN_DIM_; - effectiveZoomNumY = (int)Math.ceil((double)worldDim.height / worldHInc); - hIsMin = true; - } - - for (int x = 0; x < effectiveZoomNumX; x++) { - for (int y = 0; y < effectiveZoomNumY; y++) { + private void buildPieceMap(int zoomNum, Dimension worldDim, Map worldForSize) { + for (int x = 0; x < zoomNum; x++) { + for (int y = 0; y < zoomNum; y++) { + int worldHInc = worldDim.height / zoomNum; + int worldWInc = worldDim.width / zoomNum; Rectangle worldPiece = new Rectangle(-200 + (x * worldWInc), -200 + (y * worldHInc), worldWInc, worldHInc); - worldForSize.put(worldPiece, new WorldPieceOffering(null, useWidth, useHeight, false)); + worldForSize.put(worldPiece, new WorldPieceOffering(null, zoomNum, false)); } } - return (wIsMin && hIsMin); + return; } /*************************************************************************** @@ -339,17 +283,16 @@ private boolean buildPieceMap(int zoomNum, Dimension baseImageDim, Dimension wor ** Build the request queue */ - private List buildQueue(int startIndex, int endIndex, int maxCount) { - ArrayList retval = new ArrayList(); + private List buildQueue(int startIndex, int endIndex, int maxCount) { + ArrayList retval = new ArrayList(); for (int i = startIndex; i <= endIndex; i++) { - Integer key = Integer.valueOf(i); - Map worldForSize = worldToImageName_.get(key); + Integer key = new Integer(i); + HashMap worldForSize = (HashMap)worldToImageName_.get(key); if (worldForSize != null) { - Iterator w4sit = worldForSize.keySet().iterator(); + Iterator w4sit = worldForSize.keySet().iterator(); while (w4sit.hasNext()) { - Rectangle worldPiece = w4sit.next(); - WorldPieceOffering wpo = worldForSize.get(worldPiece); - retval.add(new QueueRequest(key, new Rectangle(wpo.imgWidth, wpo.imgHeight), worldPiece)); + Rectangle worldPiece = (Rectangle)w4sit.next(); + retval.add(new QueueRequest(key, worldPiece)); if (retval.size() >= maxCount) { return (retval); } @@ -364,7 +307,7 @@ private List buildQueue(int startIndex, int endIndex, int maxCount ** Build the buffers */ - private boolean buildBuffer(Dimension imageDim, QueueRequest qr) throws IOException { + private boolean buildBuffer(Dimension screenDim, QueueRequest qr) throws IOException { // // To chunk the image, we parcel out pieces of world to pieces of screen: // @@ -373,18 +316,17 @@ private boolean buildBuffer(Dimension imageDim, QueueRequest qr) throws IOExcept return (false); } } - buildHiResSlice(imageDim, qr.key, qr.worldPiece); + buildHiResSlice(screenDim, qr.key, qr.worldPiece); return (true); } /*************************************************************************** ** - ** If we lack an image slice, we first create a lo-res version from existing images. - ** + ** Drawing routine */ private String buildLoResSlice(int num, Dimension screenDim, Dimension worldDim, - Rectangle worldPiece, Map worldForSize) throws IOException { + Rectangle worldPiece, Map worldForSize) throws IOException { int worldHInc = worldDim.height / num; int worldWInc = worldDim.width / num; @@ -398,14 +340,14 @@ private String buildLoResSlice(int num, Dimension screenDim, Dimension worldDim, Rectangle usePiece = null; // NOTE THE USE INDEX OF 1 FOR THE IMAGE BASE!!!! NO!!!! FIX ME!!!! - Map worldForUse = worldToImageName_.get(Integer.valueOf(useIndex)); - Iterator wf1Kit = worldForUse.keySet().iterator(); + Map worldForUse = (Map)worldToImageName_.get(new Integer(useIndex)); + Iterator wf1Kit = worldForUse.keySet().iterator(); while (wf1Kit.hasNext()) { - usePiece = wf1Kit.next(); + usePiece = (Rectangle)wf1Kit.next(); Rectangle2D wpit = usePiece.createIntersection(worldPiece); if ((wpit.getWidth() > 10.0) && (wpit.getHeight() > 10.0)) { synchronized (this) { - WorldPieceOffering wpou = worldForUse.get(usePiece); + WorldPieceOffering wpou = (WorldPieceOffering)worldForUse.get(usePiece); if ((wpou.cacheHandle != null) && !wpou.cacheHandle.equals("")) { bi1 = cache_.getAnImage(wpou.cacheHandle); } @@ -429,12 +371,12 @@ private String buildLoResSlice(int num, Dimension screenDim, Dimension worldDim, // REALLY thin slices (1.25 million links) have round/trunc errors taking height to 0! double screenHIncd = (double)screenDim.height / (double)scale; double yIncd = (double)((worldPiece.y - usePiece.y) + 10) / (double)worldHInc; - double topHeightd = bi1.getHeight() - (yIncd * screenHInc); + double topHeightd = (double)bi1.getHeight() - (yIncd * (double)screenHInc); double useHeightd = (topHeightd < screenHIncd) ? topHeightd : screenHIncd; double screenWIncd = (double)screenDim.width / (double)scale; double xIncd = (double)((worldPiece.x - usePiece.x) + 10) / (double)worldWInc; - double topWidthd = bi1.getWidth() - (xIncd * screenWInc); + double topWidthd = (double)bi1.getWidth() - (xIncd * (double)screenWInc); double useWidthd = (topWidthd < screenWIncd) ? topWidthd : screenWIncd; if ((useHeight <= 0) && (useHeightd > 0.0)) { @@ -448,7 +390,6 @@ private String buildLoResSlice(int num, Dimension screenDim, Dimension worldDim, } } - UiUtil.fixMePrintout("Crappy lo-res segmentation occurs here!"); BufferedImage chunk = bi1.getSubimage((xInc * screenWInc), (yInc * screenHInc), useWidth, useHeight); BufferedImage scaled = new BufferedImage(screenDim.width, screenDim.height + SLICE_HEIGHT_HACK_, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = scaled.createGraphics(); @@ -457,7 +398,7 @@ private String buildLoResSlice(int num, Dimension screenDim, Dimension worldDim, g2.dispose(); String handle = null; synchronized (this) { - WorldPieceOffering wpo = worldForSize.get(worldPiece); + WorldPieceOffering wpo = (WorldPieceOffering)worldForSize.get(worldPiece); if (!wpo.isDrawn) { if (!isBlankImage(scaled)) { wpo.cacheHandle = cache_.cacheAnImage(scaled); @@ -471,17 +412,17 @@ private String buildLoResSlice(int num, Dimension screenDim, Dimension worldDim, /*************************************************************************** ** - ** While the lo-res slice is being displayed, we go out and render to a high-res - ** slice that is cached: + ** Drawing routine */ - private void buildHiResSlice(Dimension imageDim, Integer key, Rectangle worldPiece) throws IOException { - BufferedImage bi = new BufferedImage(imageDim.width, imageDim.height + SLICE_HEIGHT_HACK_, BufferedImage.TYPE_INT_RGB); + private void buildHiResSlice(Dimension screenDim, Integer key, Rectangle worldPiece) throws IOException { + + BufferedImage bi = new BufferedImage(screenDim.width, screenDim.height + SLICE_HEIGHT_HACK_, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.setColor(Color.WHITE); - //g2.setColor(new Color(255, 220, 220)); //Debug sizing problems - g2.fillRect(0, 0, imageDim.width, imageDim.height + SLICE_HEIGHT_HACK_); - boolean didDraw = drawer_.drawForBuffer(g2, worldPiece, imageDim, worldPiece); + //g2.setColor(Color.RED); Debug sizing problems + g2.fillRect(0, 0, screenDim.width, screenDim.height + SLICE_HEIGHT_HACK_); + boolean didDraw = drawer_.drawForBuffer(g2, worldPiece, screenDim, worldPiece); // Debug sizing problems: //AffineTransform transform = new AffineTransform(); @@ -489,15 +430,15 @@ private void buildHiResSlice(Dimension imageDim, Integer key, Rectangle worldPie //BasicStroke selectedStroke = new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER); //g2.setStroke(selectedStroke); //g2.setColor(Color.GREEN); - //g2.drawRect(0, 0, imageDim.width - 1, imageDim.height + SLICE_HEIGHT_HACK_ - 1); + //g2.drawRect(0, 0, screenDim.width - 1, screenDim.height + SLICE_HEIGHT_HACK_ - 1); g2.dispose(); BufferBuilderClient tellHim = null; synchronized (this) { - Map worldForSize = worldToImageName_.get(key); - WorldPieceOffering wpo = worldForSize.get(worldPiece); + HashMap worldForSize = (HashMap)worldToImageName_.get(key); + WorldPieceOffering wpo = (WorldPieceOffering)worldForSize.get(worldPiece); if (didDraw) { if ((wpo.cacheHandle == null) || wpo.cacheHandle.equals("")) { wpo.cacheHandle = cache_.cacheAnImage(bi); @@ -563,36 +504,6 @@ private boolean parsePixel(int x, int y, int pixel) { return ((red == 255) && (green == 255) && (blue == 255)); } - /*************************************************************************** - ** - ** We only do image-based zooms if we need to, and switch over to actual drawing - ** when the link count in the frame gets small enough. Note that right now, that - ** cross-over is set to 10,000 links: - */ - - public static int[] calcImageZooms(BioFabricNetwork bfn) { - - boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); - int lco = (bfn == null) ? 0 : bfn.getLinkCount(showShadows); - int[] preZooms; - if (lco != 0) { - int linkLog = (int)Math.ceil(Math.log(lco) / Math.log(2.0)); - int firstDrawLog = (int)Math.ceil(Math.log(1.0E4) / Math.log(2.0)); - // For tiny networks (1 link), previous 4 levels of zoom is too much. - int numPre = Math.max(linkLog - firstDrawLog, 2); - preZooms = new int[numPre]; - preZooms[0] = 1; - for (int i = 1; i < numPre; i++) { - preZooms[i] = 2 * preZooms[i - 1]; - } - } else { - preZooms = new int[1]; - preZooms[0] = 1; - } - return (preZooms); - } - - /*************************************************************************** ** ** Build images in the background: @@ -600,14 +511,13 @@ public static int[] calcImageZooms(BioFabricNetwork bfn) { public class BuildImageWorker implements Runnable { - private Dimension screenDim_; - @SuppressWarnings("unused") + private Dimension screenDim_; private String errString_; - private ArrayList requests_; + private ArrayList requests_; - public BuildImageWorker(Dimension screenDim, List requests) { + public BuildImageWorker(Dimension screenDim, List requests) { screenDim_ = (Dimension)screenDim.clone(); - requests_ = new ArrayList(requests); + requests_ = new ArrayList(requests); } public void run() { @@ -617,7 +527,7 @@ public void run() { if (qr == null) { break; } - if (!buildBuffer(new Dimension(qr.imageDim.width, qr.imageDim.height), qr)) { + if (!buildBuffer(screenDim_, qr)) { return; } } @@ -645,7 +555,7 @@ private QueueRequest getNextRequest() { return (null); } } - return (requests_.remove(0)); + return ((QueueRequest)requests_.remove(0)); } } @@ -669,27 +579,16 @@ void bumpRequest(QueueRequest qr) { ** World Piece Offering */ - private static class WorldPieceOffering implements Cloneable { + private static class WorldPieceOffering { String cacheHandle; boolean isDrawn; - int imgWidth; - int imgHeight; + int zoomNum; - WorldPieceOffering(String cacheHandle, int imgWidth, int imgHeight, boolean isDrawn) { + WorldPieceOffering(String cacheHandle, int zoomNum, boolean isDrawn) { this.cacheHandle = cacheHandle; - this.imgWidth = imgWidth; - this.imgHeight = imgHeight; + this.zoomNum = zoomNum; this.isDrawn = isDrawn; } - - @Override - public WorldPieceOffering clone() { - try { - return ((WorldPieceOffering)super.clone()); - } catch (CloneNotSupportedException cnse) { - throw new IllegalStateException(); - } - } } /*************************************************************************** @@ -699,17 +598,15 @@ public WorldPieceOffering clone() { private static class QueueRequest { Integer key; - Rectangle imageDim; Rectangle worldPiece; - QueueRequest(Integer key, Rectangle imageDim, Rectangle worldPiece) { + QueueRequest(Integer key, Rectangle worldPiece) { this.key = key; this.worldPiece = worldPiece; - this.imageDim = imageDim; } public int hashCode() { - return (key.hashCode() + worldPiece.hashCode() + imageDim.hashCode()); + return (key.hashCode() + worldPiece.hashCode()); } public boolean equals(Object other) { @@ -727,9 +624,6 @@ public boolean equals(Object other) { if (!this.key.equals(otherReq.key)) { return (false); } - if (!this.imageDim.equals(otherReq.imageDim)) { - return (false); - } return (this.worldPiece.equals(otherReq.worldPiece)); } diff --git a/src/org/systemsbiology/biofabric/layouts/NodeSimilarityLayout.java b/src/org/systemsbiology/biotapestry/biofabric/ClusteredLayout.java similarity index 50% rename from src/org/systemsbiology/biofabric/layouts/NodeSimilarityLayout.java rename to src/org/systemsbiology/biotapestry/biofabric/ClusteredLayout.java index 3f43016..5e99859 100644 --- a/src/org/systemsbiology/biofabric/layouts/NodeSimilarityLayout.java +++ b/src/org/systemsbiology/biotapestry/biofabric/ClusteredLayout.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,10 +17,9 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.layouts; +package org.systemsbiology.biotapestry.biofabric; import java.util.ArrayList; -import java.util.Collections; import java.util.TreeSet; import java.util.HashMap; import java.util.HashSet; @@ -33,26 +32,22 @@ import java.util.TreeMap; import java.util.Vector; - -import org.systemsbiology.biofabric.analysis.Link; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.AsynchExitRequestException; -import org.systemsbiology.biofabric.util.BTProgressMonitor; -import org.systemsbiology.biofabric.util.ChoiceContent; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.DoubMinMax; -import org.systemsbiology.biofabric.util.MinMax; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.analysis.Link; +import org.systemsbiology.biotapestry.util.AffineCombination; +import org.systemsbiology.biotapestry.util.AsynchExitRequestException; +import org.systemsbiology.biotapestry.util.BTProgressMonitor; +import org.systemsbiology.biotapestry.util.ChoiceContent; +import org.systemsbiology.biotapestry.util.DataUtil; +import org.systemsbiology.biotapestry.util.DoubMinMax; +import org.systemsbiology.biotapestry.util.MinMax; +import org.systemsbiology.biotapestry.util.ResourceManager; /**************************************************************************** ** -** This does the node similarity layout +** This is the Network model */ -public class NodeSimilarityLayout { +public class ClusteredLayout { //////////////////////////////////////////////////////////////////////////// // @@ -83,7 +78,8 @@ public class NodeSimilarityLayout { ** Constructor */ - public NodeSimilarityLayout() { + public ClusteredLayout() { + } //////////////////////////////////////////////////////////////////////////// @@ -94,161 +90,39 @@ public NodeSimilarityLayout() { /*************************************************************************** ** - ** Move nodes to match shapes - */ - - public void doReorderLayout(BioFabricNetwork.RelayoutBuildData rbd, - NodeSimilarityLayout.CRParams params, - BTProgressMonitor monitor, - double startFrac, - double endFrac) throws AsynchExitRequestException { - - BioFabricNetwork bfn = rbd.bfn; - HashMap targToRow = new HashMap(); - SortedMap> connVecs = getConnectionVectors(rbd, targToRow); - - NodeSimilarityLayout.ResortParams rp = (NodeSimilarityLayout.ResortParams)params; - - List ordered = new ArrayList(); - int numRows = bfn.getRowCount(); - for (int i = 0; i < numRows; i++) { - ordered.add(Integer.valueOf(i)); - } - - double currStart = startFrac; - double inc = (endFrac - startFrac) / rp.passCount; - double currEnd = currStart + inc; - - TreeMap rankings = new TreeMap(); - NodeSimilarityLayout.ClusterPrep cprep = setupForResort(bfn, connVecs, ordered, rankings); - Double lastRank = rankings.get(rankings.lastKey()); - - for (int i = 0; i < rp.passCount; i++) { - monitor.updateRankings(rankings); - List nextOrdered = resort(cprep, monitor, currStart, currEnd); - currStart = currEnd; - currEnd = currStart + inc; - cprep = setupForResort(bfn, connVecs, nextOrdered, rankings); - Integer lastKey = rankings.lastKey(); - Double nowRank = rankings.get(lastKey); - if (rp.terminateAtIncrease) { - if (lastRank.doubleValue() < nowRank.doubleValue()) { - rankings.remove(lastKey); - break; - } - } - ordered = nextOrdered; - lastRank = nowRank; - } - - monitor.updateRankings(rankings); - Map orderedNames = convertOrderToMap(bfn, ordered); - rbd.setNodeOrder(orderedNames); - - return; - } - - /*************************************************************************** - ** - ** Clustered Layout guts - */ - - public void doClusteredLayout(BioFabricNetwork.RelayoutBuildData rbd, - NodeSimilarityLayout.CRParams params, - BTProgressMonitor monitor, - double startFrac, double endFrac) throws AsynchExitRequestException { - - List ordered = doClusteredLayoutOrder(rbd, params, monitor, startFrac, endFrac); - Map orderedNames = convertOrderToMap(rbd.bfn, ordered); - rbd.setNodeOrder(orderedNames); - return; - } - - /*************************************************************************** - ** - ** Clustered Layout Ordering only - */ - - public List doClusteredLayoutOrder(BioFabricNetwork.RelayoutBuildData rbd, - NodeSimilarityLayout.CRParams params, - BTProgressMonitor monitor, - double startFrac, double endFrac) throws AsynchExitRequestException { - - //BioFabricNetwork bfn = rbd.bfn; - NodeSimilarityLayout.ClusterParams cp = (NodeSimilarityLayout.ClusterParams)params; - HashMap targToRow = new HashMap(); - SortedMap> connVecs = getConnectionVectors(rbd, targToRow); - - TreeMap> dists = new TreeMap>(Collections.reverseOrder()); - HashMap degMag = new HashMap(); - - Integer highestDegree = (cp.distanceMethod == NodeSimilarityLayout.ClusterParams.COSINES) ? - getCosines(connVecs, dists, degMag, rbd, targToRow) : - getJaccard(connVecs, dists, degMag, rbd, targToRow); - - ArrayList linkTrace = new ArrayList(); - ArrayList jumpLog = new ArrayList(); - - - HashMap rowToTarg = new HashMap(); - for (NID.WithName targ : targToRow.keySet()) { - rowToTarg.put(targToRow.get(targ), targ); - } - List ordered = orderByDistanceChained(rowToTarg, highestDegree, dists, - degMag, linkTrace, cp.chainLength, - cp.tolerance, jumpLog, monitor, startFrac, endFrac); - - - - - - return (ordered); - } - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Get connection vectors + ** Get connectivity vectors */ - private SortedMap> getConnectionVectors(BioFabricNetwork.RelayoutBuildData rbd, - Map targToRow) { + public SortedMap getConnectivityVectors(BioFabricNetwork bfn) { - Iterator rtit = rbd.existingIDOrder.iterator(); - int count = 0; + HashMap targToRow = new HashMap(); + Iterator rtit = bfn.getRows(); while (rtit.hasNext()) { - NID.WithName node = rtit.next(); - targToRow.put(node, Integer.valueOf(count++)); + Integer row = (Integer)rtit.next(); + String node = bfn.getNodeForRow(row); + targToRow.put(node,row); } - TreeMap> retval = new TreeMap>(); - Iterator ldit = rbd.allLinks.iterator(); + TreeMap retval = new TreeMap(); + Iterator ldit = bfn.getOrderedLinkInfo(false); while (ldit.hasNext()) { - FabricLink fl = ldit.next(); //Integer col = ldit.next(); - if (fl.isShadow()) { - continue; - } - // BioFabricNetwork.LinkInfo linf = bfn.getLinkDefinition(col, false); - NID.WithName srcName = fl.getSrcID(); //linf.getSource(); - Integer srcRow = targToRow.get(srcName); - NID.WithName trgName = fl.getTrgID(); //.getTarget(); - Integer trgRow = targToRow.get(trgName); + Integer col = (Integer)ldit.next(); + BioFabricNetwork.LinkInfo linf = bfn.getLinkDefinition(col, false); + String srcName = linf.getSource(); + Integer srcRow = (Integer)targToRow.get(srcName); + String trgName = linf.getTarget(); + Integer trgRow = (Integer)targToRow.get(trgName); - SortedSet forRetval = retval.get(srcRow); + TreeSet forRetval = (TreeSet)retval.get(srcRow); if (forRetval == null) { - forRetval = new TreeSet(); + forRetval = new TreeSet(); retval.put(srcRow, forRetval); } forRetval.add(trgRow); - forRetval = retval.get(trgRow); + forRetval = (TreeSet)retval.get(trgRow); if (forRetval == null) { - forRetval = new TreeSet(); + forRetval = new TreeSet(); retval.put(trgRow, forRetval); } forRetval.add(srcRow); @@ -261,51 +135,54 @@ private SortedMap> getConnectionVectors(BioFabricNet ** Get cosines. */ - private Integer getCosines(SortedMap> connVec, - SortedMap> retval, - Map connMag, - BioFabricNetwork.RelayoutBuildData rbd, Map targToRow) { - int rowCount = rbd.allNodeIDs.size(); + public Integer getConnectivityCosines(SortedMap connVec, SortedMap retval, Map connMag, BioFabricNetwork bfn) { + int rowCount = bfn.getRowCount(); Integer[] icache = new Integer[rowCount]; String[] scache = new String[rowCount]; for (int i = 0; i < rowCount; i++) { - icache[i] = Integer.valueOf(i); + icache[i] = new Integer(i); scache[i] = icache[i].toString(); } - + HashMap targToRow = new HashMap(); + Iterator rtit = bfn.getRows(); + while (rtit.hasNext()) { + Integer row = (Integer)rtit.next(); + String node = bfn.getNodeForRow(row); + targToRow.put(node,row); + } + int count = 0; + int fullCount = (rowCount * rowCount) / 2; - Integer highestDegree = null; + Integer mostConnected = null; int biggestMag = Integer.MIN_VALUE; - HashSet intersect = new HashSet(); + HashSet intersect = new HashSet(); - Iterator ldit = rbd.allLinks.iterator(); + Iterator ldit = bfn.getOrderedLinkInfo(false); while (ldit.hasNext()) { - FabricLink fl = ldit.next(); - if (fl.isShadow()) { - continue; - } - NID.WithName srcName = fl.getSrcID(); - Integer srcRow = targToRow.get(srcName); - NID.WithName trgName = fl.getTrgID(); - Integer trgRow = targToRow.get(trgName); - SortedSet srcVec = connVec.get(srcRow); + Integer col = (Integer)ldit.next(); + BioFabricNetwork.LinkInfo linf = bfn.getLinkDefinition(col, false); + String srcName = linf.getSource(); + Integer srcRow = (Integer)targToRow.get(srcName); + String trgName = linf.getTarget(); + Integer trgRow = (Integer)targToRow.get(trgName); + TreeSet srcVec = (TreeSet)connVec.get(srcRow); int srcSize = srcVec.size(); if (srcSize > biggestMag) { biggestMag = srcSize; - highestDegree = srcRow; + mostConnected = srcRow; } - SortedSet trgVec = connVec.get(trgRow); + TreeSet trgVec = (TreeSet)connVec.get(trgRow); int trgSize = trgVec.size(); if (trgSize > biggestMag) { biggestMag = trgSize; - highestDegree = trgRow; + mostConnected = trgRow; } - connMag.put(icache[srcRow.intValue()], icache[srcSize]); - connMag.put(icache[trgRow.intValue()], icache[trgSize]); + connMag.put(scache[srcRow.intValue()], icache[srcSize]); + connMag.put(scache[trgRow.intValue()], icache[trgSize]); - double sqrs = Math.sqrt(srcSize); - double sqrt = Math.sqrt(trgSize); + double sqrs = Math.sqrt((double)(srcSize)); + double sqrt = Math.sqrt((double)(trgSize)); intersect.clear(); intersect.addAll(srcVec); intersect.retainAll(trgVec); @@ -315,17 +192,17 @@ private Integer getCosines(SortedMap> connVec, // an entry for the node itself, so two nodes only connected to each other end up with // zero intersection. - double val = intersect.size() / (sqrs * sqrt); + double val = (double)(intersect.size()) / (sqrs * sqrt); Double dot = new Double(val); - SortedSet forDot = retval.get(dot); + ArrayList forDot = (ArrayList)retval.get(dot); if (forDot == null) { - forDot = new TreeSet(); + forDot = new ArrayList(); retval.put(dot, forDot); } forDot.add(new Link(scache[srcRow.intValue()], scache[trgRow.intValue()])); count++; } - return (highestDegree); + return (mostConnected); } /*************************************************************************** @@ -348,50 +225,52 @@ private Integer getCosines(SortedMap> connVec, * This distance is a proper metric */ - private Integer getJaccard(SortedMap> connVec, - SortedMap> retval, - Map connMag, - BioFabricNetwork.RelayoutBuildData rbd, Map targToRow) { + public Integer getConnectivityJaccard(SortedMap connVec, SortedMap retval, Map connMag, BioFabricNetwork bfn) { - int rowCount = rbd.allNodeIDs.size(); + int rowCount = bfn.getRowCount(); Integer[] icache = new Integer[rowCount]; String[] scache = new String[rowCount]; for (int i = 0; i < rowCount; i++) { - icache[i] = Integer.valueOf(i); + icache[i] = new Integer(i); scache[i] = icache[i].toString(); } - + HashMap targToRow = new HashMap(); + Iterator rtit = bfn.getRows(); + while (rtit.hasNext()) { + Integer row = (Integer)rtit.next(); + String node = bfn.getNodeForRow(row); + targToRow.put(node,row); + } + int count = 0; - Integer highestDegree = null; + Integer mostConnected = null; int biggestMag = Integer.MIN_VALUE; - HashSet union = new HashSet(); - HashSet intersect = new HashSet(); - - Iterator ldit = rbd.allLinks.iterator(); + HashSet union = new HashSet(); + HashSet intersect = new HashSet(); + + Iterator ldit = bfn.getOrderedLinkInfo(false); while (ldit.hasNext()) { - FabricLink fl = ldit.next(); - if (fl.isShadow()) { - continue; - } - NID.WithName srcName = fl.getSrcID(); - Integer srcRow = targToRow.get(srcName); - NID.WithName trgName = fl.getTrgID(); - Integer trgRow = targToRow.get(trgName); - SortedSet srcVec = connVec.get(srcRow); + Integer col = (Integer)ldit.next(); + BioFabricNetwork.LinkInfo linf = bfn.getLinkDefinition(col, false); + String srcName = linf.getSource(); + Integer srcRow = (Integer)targToRow.get(srcName); + String trgName = linf.getTarget(); + Integer trgRow = (Integer)targToRow.get(trgName); + TreeSet srcVec = (TreeSet)connVec.get(srcRow); int srcSize = srcVec.size(); if (srcSize > biggestMag) { biggestMag = srcSize; - highestDegree = srcRow; + mostConnected = srcRow; } - SortedSet trgVec = connVec.get(trgRow); + TreeSet trgVec = (TreeSet)connVec.get(trgRow); int trgSize = trgVec.size(); if (trgSize > biggestMag) { biggestMag = trgSize; - highestDegree = trgRow; + mostConnected = trgRow; } - connMag.put(icache[srcRow.intValue()], icache[srcSize]); - connMag.put(icache[trgRow.intValue()], icache[trgSize]); + connMag.put(scache[srcRow.intValue()], icache[srcSize]); + connMag.put(scache[trgRow.intValue()], icache[trgSize]); union.clear(); DataUtil.union(srcVec, trgVec, union); @@ -403,15 +282,15 @@ private Integer getJaccard(SortedMap> connVec, double jaccard = (double)(iSize) / (double)uSize; Double jaccardObj = new Double(jaccard); - SortedSet forDot = retval.get(jaccardObj); + ArrayList forDot = (ArrayList)retval.get(jaccardObj); if (forDot == null) { - forDot = new TreeSet(); + forDot = new ArrayList(); retval.put(jaccardObj, forDot); } forDot.add(new Link(scache[srcRow.intValue()], scache[trgRow.intValue()])); count++; } - return (highestDegree); + return (mostConnected); } /*************************************************************************** @@ -420,17 +299,17 @@ private Integer getJaccard(SortedMap> connVec, ** set of nodes. */ - private List orderByDistanceChained(Map rowToTarg, - Integer start, SortedMap> cosines, - Map connMag, List linkTrace, - int limit, double tol, List jumpLog, - BTProgressMonitor monitor, double startFrac, double endFrac) - throws AsynchExitRequestException { - int rowCount = rowToTarg.size(); - ArrayList retval = new ArrayList(); - HashSet seen = new HashSet(); - retval.add(start); - seen.add(start); + public List orderByDistanceChained(BioFabricNetwork bfn, Integer start, SortedMap cosines, + Map connMag, List linkTrace, + int limit, double tol, List jumpLog, + BTProgressMonitor monitor, double startFrac, double endFrac) + throws AsynchExitRequestException { + int rowCount = bfn.getRowCount(); + ArrayList retval = new ArrayList(); + HashSet seen = new HashSet(); + String startNode = Integer.toString(start.intValue()); + retval.add(startNode); + seen.add(startNode); // // Tried running multiple chains, with the idea of being able to @@ -441,8 +320,8 @@ private List orderByDistanceChained(Map rowToTar // we went to reclaim another chain to start over. Seems to // be little benefit, and big speed hit. - ArrayList currentChain = new ArrayList(); - currentChain.add(start); + ArrayList currentChain = new ArrayList(); + currentChain.add(startNode); int switchCount = 0; int stayCount = 0; @@ -450,26 +329,25 @@ private List orderByDistanceChained(Map rowToTar // Keep adding until all nodes are accounted for: // while (retval.size() < rowCount) { - // Find best unconstrained hop: - DoubleRanked bestHop = findBestUnseenHop(rowToTarg, cosines, connMag, seen, null, retval); + // Find best uncontrained hop: + DoubleRanked bestHop = findBestUnseenHop(bfn, cosines, connMag, seen, null); // Find best hop off the current search net: - DoubleRanked currentHop = findBestUnseenHop(rowToTarg, cosines, connMag, seen, currentChain, retval); + DoubleRanked currentHop = findBestUnseenHop(bfn, cosines, connMag, seen, currentChain); if (bestHop == null) { // Not found, need to find the highest non-seen guy. if (currentHop != null) { throw new IllegalStateException(); } - handleFallbacks(rowToTarg, connMag, linkTrace, seen, retval); + handleFallbacks(bfn, connMag, linkTrace, seen, retval); continue; } // // If the CURRENT chained hop stuff sucks, we toss the chain and start over: - // - + // if ((currentHop == null) || (currentHop.rank <= (bestHop.rank * tol))) { seen.add(bestHop.id); linkTrace.add(bestHop.byLink); - jumpLog.add(Integer.valueOf(retval.size())); + jumpLog.add(new Integer(retval.size())); retval.add(bestHop.id); currentChain.clear(); maintainChain(currentChain, bestHop, limit); @@ -483,7 +361,6 @@ private List orderByDistanceChained(Map rowToTar maintainChain(currentChain, currentHop, limit); stayCount++; } - if (monitor != null) { double currProg = startFrac + ((endFrac - startFrac) * ((double)retval.size() / (double)rowCount)); if (!monitor.updateProgress((int)(currProg * 100.0))) { @@ -494,22 +371,27 @@ private List orderByDistanceChained(Map rowToTar return (retval); } - + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE METHODS + // + //////////////////////////////////////////////////////////////////////////// + /*************************************************************************** ** ** Maintain the recent used chain */ - private void maintainChain(List chain, DoubleRanked bestChainedHop, int limit) { + private void maintainChain(List chain, DoubleRanked bestChainedHop, int limit) { // // The guy who established the link goes first. The newly added guy goes second. // If we hit the limit, the last guys are tossed // - Integer bySrc = Integer.valueOf(bestChainedHop.byLink.getSrc()); - Integer byTrg = Integer.valueOf(bestChainedHop.byLink.getTrg()); + String bySrc = bestChainedHop.byLink.getSrc(); + String byTrg = bestChainedHop.byLink.getTrg(); - Integer bridge = (bySrc.equals(bestChainedHop.id)) ? byTrg : bySrc; + String bridge = (bySrc.equals(bestChainedHop.id)) ? byTrg : bySrc; chain.remove(bridge); chain.add(0, bestChainedHop.id); chain.add(0, bridge); @@ -523,99 +405,64 @@ private void maintainChain(List chain, DoubleRanked bestChainedHop, int /*************************************************************************** ** - ** Start with highest degree node. Find the highest cosine for it and + ** Start with most connected node. Find the highest cosine for it and ** another node. That node then becomes the next to search on. */ - private DoubleRanked findBestUnseenHop(Map nodeForRow, SortedMap> cosines, - Map degMag, HashSet seen, - List launchNodes, List currentOrder) { + private DoubleRanked findBestUnseenHop(BioFabricNetwork bfn, SortedMap cosines, Map connMag, HashSet seen, List launchNodes) { if ((launchNodes != null) && launchNodes.isEmpty()) { return (null); } - Iterator dotIt = cosines.keySet().iterator(); + Iterator dotIt = cosines.keySet().iterator(); // // Look in order of cosine magnitude, high to low: // - String maxDegNodeName = null; - Integer maxDegNode = null; - Integer maxDegDeg = null; - Integer maxDegMinOther = null; - Integer maxDegOtherNode = null; - ArrayList candConnects = new ArrayList(); + String maxConnNode = null; + Integer maxConnConn = null; while (dotIt.hasNext()) { - Double dot = dotIt.next(); - SortedSet forDot = cosines.get(dot); - maxDegNode = null; - maxDegDeg = null; + Double dot = (Double)dotIt.next(); + ArrayList forDot = (ArrayList)cosines.get(dot); + int numForDot = forDot.size(); + maxConnNode = null; + maxConnConn = null; + Link viaLink = null; // Each cosine magnitude has a list of links. Find ones that span from the // set of placed nodes to the set of unplaced nodes: - for (Link nextLink : forDot) { - Integer src = Integer.valueOf(nextLink.getSrc()); - Integer trg = Integer.valueOf(nextLink.getTrg()); - Integer cand = null; - Integer other = null; + for (int i = 0; i < numForDot; i++) { + Link nextLink = (Link)forDot.get(i); + String src = nextLink.getSrc(); + String trg = nextLink.getTrg(); + String cand = null; if (seen.contains(src) && !seen.contains(trg)) { if ((launchNodes == null) || launchNodes.contains(src)) { cand = trg; - other = src; } } else if (seen.contains(trg) && !seen.contains(src)) { if ((launchNodes == null) || launchNodes.contains(trg)) { cand = src; - other = trg; } } // - // Having found one, record who has the highest degree: + // Having found one, record who has the highest connectivity: // if (cand != null) { - Integer degVal = degMag.get(cand); - UiUtil.fixMePrintout("current degmag counts src->trg and trg->src directed links as only degree 1"); - String n4r = nodeForRow.get(cand).getName(); - Integer r4o = Integer.valueOf(currentOrder.indexOf(other)); - boolean gtCon = (maxDegDeg == null) || (maxDegDeg.intValue() < degVal.intValue()); - boolean eqCon = (maxDegDeg != null) && (maxDegDeg.intValue() == degVal.intValue()); - boolean ltORow = (maxDegMinOther == null) || (maxDegMinOther.compareTo(r4o) > 0); - boolean eqORow = (maxDegMinOther != null) && (maxDegMinOther.compareTo(r4o) == 0); - boolean ltName = (maxDegNodeName == null) || (maxDegNodeName.compareToIgnoreCase(n4r) > 0); - boolean eqName = (maxDegNodeName != null) && (maxDegNodeName.compareToIgnoreCase(n4r) == 0); - if (gtCon || (eqCon && (ltORow || eqORow && (ltName || eqName)))) { - maxDegNode = cand; - maxDegNodeName = n4r; - maxDegDeg = degVal; - maxDegMinOther = r4o; - maxDegOtherNode = other; - if (!eqName) { - candConnects.clear(); - } - candConnects.add(nextLink); + Integer connVal = (Integer)connMag.get(cand); + if ((maxConnConn == null) || (maxConnConn.intValue() < connVal.intValue())) { + maxConnNode = cand; + maxConnConn = connVal; + viaLink = nextLink; } } } // - // Having found the one with the highest cosine, tie-breaking with highest degree, tie breaking - // with connection to higher node, tie-breaking by alphabetical order, add it to the list, - // find the "best link" we used to get there: - // - - if (maxDegNode != null) { - Link viaLink = null; - for (Link aConnect : candConnects) { - String other = (aConnect.getSrc().equals(maxDegNode)) ? aConnect.getTrg() : aConnect.getSrc(); - if (other.equals(maxDegOtherNode)) { - viaLink = aConnect; - break; - } - } - if (viaLink == null) { - throw new IllegalStateException(); - } - - return (new DoubleRanked(dot.doubleValue(), maxDegNode, viaLink)); + // Having found the one with the highest cosine, tie-breaking with highest connectivity, + // add it to the list: + // + if (maxConnNode != null) { + return (new DoubleRanked(dot.doubleValue(), maxConnNode, viaLink)); } } @@ -627,27 +474,26 @@ private DoubleRanked findBestUnseenHop(Map nodeForRow, So ** Handle the fallback case. */ - private void handleFallbacks(Map rowToNode, Map degMag, List linkTrace, - HashSet seen, List retval) { - Integer nextBest = getHighestDegreeRemaining(rowToNode, seen, degMag); + private void handleFallbacks(BioFabricNetwork bfn, Map connMag, List linkTrace, HashSet seen, List retval) { + String nextBest = getMostConnectedRemaining(seen, connMag); if (nextBest != null) { retval.add(nextBest); seen.add(nextBest); - linkTrace.add(new Link(nextBest.toString(), nextBest.toString())); + linkTrace.add(new Link(nextBest, nextBest)); } else { // Nodes not connected need to be flushed - TreeSet remainingTargs = new TreeSet(); - Iterator rtkit = rowToNode.keySet().iterator(); + TreeSet remainingTargs = new TreeSet(); + Iterator rtkit = bfn.getRows(); while (rtkit.hasNext()) { - Integer row = rtkit.next(); - remainingTargs.add(row); + Integer row = (Integer)rtkit.next(); + remainingTargs.add(row.toString()); } remainingTargs.removeAll(retval); - Iterator rtit = remainingTargs.iterator(); + Iterator rtit = remainingTargs.iterator(); while (rtit.hasNext()) { - Integer rTrg = rtit.next(); + String rTrg = (String)rtit.next(); retval.add(rTrg); - linkTrace.add(new Link(rTrg.toString(), rTrg.toString())); + linkTrace.add(new Link(rTrg, rTrg)); } } return; @@ -658,29 +504,22 @@ private void handleFallbacks(Map rowToNode, Map rowToNode, Set seen, Map degMag) { - Integer maxDegNode = null; - String maxDegNodeName = null; - Integer maxDegDeg = null; - Iterator degIt = degMag.keySet().iterator(); - while (degIt.hasNext()) { - Integer cand = degIt.next(); + private String getMostConnectedRemaining(Set seen, Map connMag) { + String maxConnNode = null; + Integer maxConnConn = null; + Iterator connIt = connMag.keySet().iterator(); + while (connIt.hasNext()) { + String cand = (String)connIt.next(); if (seen.contains(cand)) { continue; } - Integer degVal = degMag.get(cand); - String n4r = rowToNode.get(cand).getName(); - boolean gtCon = (maxDegDeg == null) || (maxDegDeg.intValue() < degVal.intValue()); - boolean eqCon = (maxDegDeg != null) && (maxDegDeg.intValue() == degVal.intValue()); - boolean ltName = (maxDegNodeName == null) || (maxDegNodeName.compareToIgnoreCase(n4r) > 0); - boolean eqName = (maxDegNodeName != null) && (maxDegNodeName.compareToIgnoreCase(n4r) == 0); - if (gtCon || (eqCon && (ltName || eqName))) { - maxDegNode = cand; - maxDegNodeName = n4r; - maxDegDeg = degVal; + Integer connVal = (Integer)connMag.get(cand); + if ((maxConnConn == null) || (maxConnConn.intValue() < connVal.intValue())) { + maxConnNode = cand; + maxConnConn = connVal; } } - return (maxDegNode); + return (maxConnNode); } /*************************************************************************** @@ -688,14 +527,14 @@ private Integer getHighestDegreeRemaining(Map rowToNode, ** Utility conversion */ - public List convertOrder(BioFabricNetwork bfn, List orderedStringRows) { - ArrayList retval = new ArrayList(); + public List convertOrder(BioFabricNetwork bfn, List orderedStringRows) { + ArrayList retval = new ArrayList(); int numOsr = orderedStringRows.size(); for (int i = 0; i < numOsr; i++) { - String sval = orderedStringRows.get(i); + String sval = (String)orderedStringRows.get(i); try { Integer intval = Integer.valueOf(sval); - retval.add(bfn.getNodeIDForRow(intval)); + retval.add(bfn.getNodeForRow(intval)); } catch (NumberFormatException nfex) { throw new IllegalStateException(); } @@ -708,12 +547,17 @@ public List convertOrder(BioFabricNetwork bfn, List ordere ** Utility conversion */ - public Map convertOrderToMap(BioFabricNetwork bfn, List orderedStringRows) { - HashMap retval = new HashMap(); + public Map convertOrderToMap(BioFabricNetwork bfn, List orderedStringRows) { + HashMap retval = new HashMap(); int numOsr = orderedStringRows.size(); for (int i = 0; i < numOsr; i++) { - Integer intval = orderedStringRows.get(i); - retval.put(bfn.getNodeIDForRow(intval), Integer.valueOf(i)); + String sval = (String)orderedStringRows.get(i); + try { + Integer intval = Integer.valueOf(sval); + retval.put(bfn.getNodeForRow(intval).toUpperCase(), Integer.toString(i)); + } catch (NumberFormatException nfex) { + throw new IllegalStateException(); + } } return (retval); } @@ -723,13 +567,13 @@ public Map convertOrderToMap(BioFabricNetwork bfn, List orderedStringRows, Map forward, Map backward) { + public void orderToMaps(List orderedStringRows, Map forward, Map backward) { int numOsr = orderedStringRows.size(); for (int i = 0; i < numOsr; i++) { - Integer sval = orderedStringRows.get(i); + String sval = (String)orderedStringRows.get(i); try { - Integer newPos = sval; - Integer oldPos = Integer.valueOf(i); + Integer newPos = Integer.valueOf(sval); + Integer oldPos = new Integer(i); forward.put(oldPos, newPos); backward.put(newPos, oldPos); } catch (NumberFormatException nfex) { @@ -744,13 +588,12 @@ public void orderToMaps(List orderedStringRows, Map f ** Debug output: */ - @SuppressWarnings("unused") - private void curveDebug(SortedMap curve) { - Iterator cit = curve.keySet().iterator(); + private void curveDebug(SortedMap curve) { + Iterator cit = curve.keySet().iterator(); int count = 0; while (cit.hasNext()) { - Integer key = cit.next(); - Double val = curve.get(key); + Integer key = (Integer)cit.next(); + Double val = (Double)curve.get(key); System.out.print("(" + key + "," + val + ")"); if (count++ == 5) { break; @@ -764,30 +607,27 @@ private void curveDebug(SortedMap curve) { ** Build curves and caches */ - private void buildCurvesAndCaches(TreeMap oldToNew, TreeMap newToOld, - SortedMap> connVec, Integer[] icache, Double[] dcache, - HashMap> curves, - HashMap>> connectMap, int numRows) { + private void buildCurvesAndCaches(TreeMap oldToNew, TreeMap newToOld, SortedMap connVec, Integer[] icache, Double[] dcache, HashMap curves, HashMap connectMap, int numRows) { for (int i = 0; i < numRows; i++) { - Integer newRow = Integer.valueOf(i); + Integer newRow = new Integer(i); icache[i] = newRow; - dcache[i] = new Double(i); - Integer oldRow = newToOld.get(newRow); - SortedSet baseNodeVec = connVec.get(oldRow); - SortedMap curve = calcShapeCurve(baseNodeVec, oldToNew); + dcache[i] = new Double((double)i); + Integer oldRow = (Integer)newToOld.get(newRow); + TreeSet baseNodeVec = (TreeSet)connVec.get(oldRow); + SortedMap curve = calcShapeCurve(baseNodeVec, oldToNew); curves.put(newRow, curve); double connLog = Math.log(baseNodeVec.size()) / Math.log(2.0); Double connLogKey = new Double(connLog); int logBin = (connLog < 4.0) ? 0 : (int)Math.floor(connLog); - Integer logBinKey = Integer.valueOf(logBin); - Map> fineGrain = connectMap.get(logBinKey); + Integer logBinKey = new Integer(logBin); + HashMap fineGrain = (HashMap)connectMap.get(logBinKey); if (fineGrain == null) { - fineGrain = new HashMap>(); + fineGrain = new HashMap(); connectMap.put(logBinKey, fineGrain); } - Set perFine = fineGrain.get(connLogKey); + HashSet perFine = (HashSet)fineGrain.get(connLogKey); if (perFine == null) { - perFine = new HashSet(); + perFine = new HashSet(); fineGrain.put(connLogKey, perFine); } perFine.add(newRow); @@ -800,9 +640,7 @@ private void buildCurvesAndCaches(TreeMap oldToNew, TreeMap baseCurve, TreeSet connBuf, - SortedSet logKeys, - HashMap>> connectMap) { + private void buildCheckSet(SortedMap baseCurve, TreeSet connBuf, SortedSet logKeys, HashMap connectMap) { // // Chose who to check against based on having about the same number of neighbors: // @@ -811,27 +649,27 @@ private void buildCheckSet(SortedMap baseCurve, TreeSet lit = logKeys.iterator(); + Iterator lit = logKeys.iterator(); while (lit.hasNext()) { - Integer logBinKey = lit.next(); + Integer logBinKey = (Integer)lit.next(); int logBinVal = logBinKey.intValue(); - Map> fineGrain = connectMap.get(logBinKey); + HashMap fineGrain = (HashMap)connectMap.get(logBinKey); if (fineGrain == null) { continue; } - Iterator pfg = fineGrain.keySet().iterator(); + Iterator pfg = fineGrain.keySet().iterator(); while (pfg.hasNext()) { - Double fineKey = pfg.next(); + Double fineKey = (Double)pfg.next(); double fineKeyVal = fineKey.doubleValue(); if ((logBinVal == 0) || ((baseConnLogLo <= fineKeyVal) && (baseConnLogHi >= fineKeyVal))) { - Set fineGrains = fineGrain.get(fineKey); + HashSet fineGrains = (HashSet)fineGrain.get(fineKey); connBuf.addAll(fineGrains); } } @@ -844,8 +682,7 @@ private void buildCheckSet(SortedMap baseCurve, TreeSet> connVec, - List orderedStringRows, SortedMap rankings) { + public ClusterPrep setupForResort(BioFabricNetwork bfn, SortedMap connVec, List orderedStringRows, SortedMap rankings) { ClusterPrep retval = new ClusterPrep(orderedStringRows.size()); @@ -867,22 +704,22 @@ public ClusterPrep setupForResort(BioFabricNetwork bfn, SortedMap unionBuf = new TreeSet(); - TreeSet keyBuf = new TreeSet(); + TreeSet unionBuf = new TreeSet(); + TreeSet keyBuf = new TreeSet(); double deltaSum = 0.0; - Iterator n2oit = (new TreeSet(retval.newToOld.keySet())).iterator(); + Iterator n2oit = (new TreeSet(retval.newToOld.keySet())).iterator(); while (n2oit.hasNext()) { - Integer newRow = n2oit.next(); + Integer newRow = (Integer)n2oit.next(); int currRow = newRow.intValue(); if (currRow == (retval.numRows - 1)) { break; } - SortedMap baseCurve = retval.curves.get(newRow); - SortedMap nextCurve = retval.curves.get(retval.icache[currRow + 1]); + SortedMap baseCurve = (SortedMap)retval.curves.get(newRow); + SortedMap nextCurve = (SortedMap)retval.curves.get(retval.icache[currRow + 1]); double delt = calcShapeDeltaUsingCurveMaps(baseCurve, nextCurve, unionBuf, keyBuf); deltaSum += delt; } - Integer useKey = (rankings.isEmpty()) ? Integer.valueOf(0) : Integer.valueOf(rankings.lastKey().intValue() + 1); + Integer useKey = (rankings.isEmpty()) ? new Integer(0) : new Integer(((Integer)rankings.lastKey()).intValue() + 1); rankings.put(useKey, new Double(deltaSum)); return (retval); } @@ -892,8 +729,8 @@ public ClusterPrep setupForResort(BioFabricNetwork bfn, SortedMap resort(ClusterPrep prep, BTProgressMonitor monitor, double startFrac, double endFrac) - throws AsynchExitRequestException { + public List resort(ClusterPrep prep, BTProgressMonitor monitor, double startFrac, double endFrac) + throws AsynchExitRequestException { /* int numRows = orderedStringRows.size(); @@ -935,7 +772,7 @@ public List resort(ClusterPrep prep, BTProgressMonitor monitor, double double delt = calcShapeDeltaUsingCurveMaps(baseCurve, nextCurve, unionBuf, keyBuf); deltaSum += delt; } - Integer useKey = (rankings.isEmpty()) ? Integer.valueOf(0) : Integer.valueOf(((Integer)rankings.lastKey()).intValue() + 1); + Integer useKey = (rankings.isEmpty()) ? new Integer(0) : new Integer(((Integer)rankings.lastKey()).intValue() + 1); rankings.put(useKey, new Double(deltaSum)); */ @@ -943,26 +780,26 @@ public List resort(ClusterPrep prep, BTProgressMonitor monitor, double - TreeSet unionBuf = new TreeSet(); - TreeSet keyBuf = new TreeSet(); + TreeSet unionBuf = new TreeSet(); + TreeSet keyBuf = new TreeSet(); - TreeSet stillAvail = new TreeSet(prep.newToOld.keySet()); - TreeMap results = new TreeMap(); + TreeSet stillAvail = new TreeSet(prep.newToOld.keySet()); + TreeMap results = new TreeMap(); - TreeSet connBuf = new TreeSet(); - SortedSet logKeys = new TreeSet(); - SortedMap baseCurve = null; + TreeSet connBuf = new TreeSet(); + SortedSet logKeys = new TreeSet(); + SortedMap baseCurve = null; int currRow = 0; int startCheck = 1; int fillSlot = 0; results.put(prep.icache[0], prep.icache[fillSlot++]); stillAvail.remove(prep.icache[0]); - baseCurve = prep.curves.get(prep.icache[0]); + baseCurve = (SortedMap)prep.curves.get(prep.icache[0]); while (!stillAvail.isEmpty()) { - Integer newRow = stillAvail.first(); + Integer newRow = (Integer)stillAvail.first(); startCheck = newRow.intValue(); buildCheckSet(baseCurve, connBuf, logKeys, prep.connectMap); @@ -972,26 +809,26 @@ public List resort(ClusterPrep prep, BTProgressMonitor monitor, double DoubMinMax dmm = new DoubMinMax(); dmm.inverseInit(); - //double baseDelt = 0.0; + double baseDelt = 0.0; double minMatch = Double.POSITIVE_INFINITY; int minI = currRow; int numCheck = 0; - Iterator cit = connBuf.iterator(); + Iterator cit = connBuf.iterator(); while (cit.hasNext()) { - Integer swapCheck = cit.next(); + Integer swapCheck = (Integer)cit.next(); int swapCheckVal = swapCheck.intValue(); numCheck++; - SortedMap shiftCandCurve = prep.curves.get(swapCheck); + SortedMap shiftCandCurve = (SortedMap)prep.curves.get(swapCheck); double delt = calcShapeDeltaUsingCurveMaps(baseCurve, shiftCandCurve, unionBuf, keyBuf); - //if (swapCheckVal == startCheck) { - // baseDelt = delt; - //} + if (swapCheckVal == startCheck) { + baseDelt = delt; + } dmm.update(delt); if (delt < minMatch) { // Need to see if there is a global improvement! - // Integer preRemIndx = (Integer)newToOld.get(Integer.valueOf(i - 1)); + // Integer preRemIndx = (Integer)newToOld.get(new Integer(i - 1)); // TreeSet preRemoveVec = (TreeSet)connVec.get(preRemIndx); - // Integer postRemIndx = (Integer)newToOld.get(Integer.valueOf(i + 1)); + // Integer postRemIndx = (Integer)newToOld.get(new Integer(i + 1)); // TreeSet postRemoveVec = (TreeSet)connVec.get(oldForSwap); // double deltRight = calcShapeDeltaViaCurve(preRemoveVec, postRemoveVec, oldToNew); minI = swapCheckVal; @@ -1000,11 +837,11 @@ public List resort(ClusterPrep prep, BTProgressMonitor monitor, double } if (minI > startCheck) { - baseCurve = prep.curves.get(prep.icache[minI]); + baseCurve = (SortedMap)prep.curves.get(prep.icache[minI]); stillAvail.remove(prep.icache[minI]); results.put(prep.icache[minI], prep.icache[fillSlot++]); } else { - baseCurve = prep.curves.get(prep.icache[startCheck]); + baseCurve = (SortedMap)prep.curves.get(prep.icache[startCheck]); stillAvail.remove(prep.icache[startCheck]); results.put(prep.icache[startCheck], prep.icache[fillSlot++]); } @@ -1021,12 +858,12 @@ public List resort(ClusterPrep prep, BTProgressMonitor monitor, double // Convert and leave: // - ArrayList retval = new ArrayList(); - Iterator o2nit = prep.oldToNew.values().iterator(); + ArrayList retval = new ArrayList(); + Iterator o2nit = prep.oldToNew.values().iterator(); while (o2nit.hasNext()) { - Integer newRow = o2nit.next(); - Integer mappedRow = results.get(newRow); - retval.add(mappedRow); + Integer newRow = (Integer)o2nit.next(); + Integer mappedRow = (Integer)results.get(newRow); + retval.add(mappedRow.toString()); } return (retval); } @@ -1036,20 +873,20 @@ public List resort(ClusterPrep prep, BTProgressMonitor monitor, double ** Calculate the shape per node: */ - private SortedMap calcShapeCurve(SortedSet vec1, Map newOrder) { + private SortedMap calcShapeCurve(SortedSet vec1, Map newOrder) { - TreeSet reordered1 = new TreeSet(); - Iterator ub1it = vec1.iterator(); + TreeSet reordered1 = new TreeSet(); + Iterator ub1it = vec1.iterator(); while (ub1it.hasNext()) { - Integer linkEnd = ub1it.next(); - Integer mappedEnd = newOrder.get(linkEnd); + Integer linkEnd = (Integer)ub1it.next(); + Integer mappedEnd = (Integer)newOrder.get(linkEnd); reordered1.add(mappedEnd); } - ArrayList vec1Order = new ArrayList(reordered1); + ArrayList vec1Order = new ArrayList(reordered1); int numPts = vec1Order.size(); - TreeMap vec1Points = new TreeMap(); + TreeMap vec1Points = new TreeMap(); for (int i = 0; i < numPts; i++) { - Integer linkEnd = vec1Order.get(i); + Integer linkEnd = (Integer)vec1Order.get(i); calcCurveMap(reordered1, vec1Order, linkEnd, vec1Points); } @@ -1061,14 +898,14 @@ private SortedMap calcShapeCurve(SortedSet vec1, Map curve) { + private double curveAverage(SortedMap curve) { double retval = 0.0; Double firstVal = null; double lastX = 0.0; - Iterator cit = curve.keySet().iterator(); + Iterator cit = curve.keySet().iterator(); while (cit.hasNext()) { - Integer key = cit.next(); - Double val = curve.get(key); + Integer key = (Integer)cit.next(); + Double val = (Double)curve.get(key); double thisKey = key.doubleValue(); double thisVal = val.doubleValue(); if (firstVal == null) { @@ -1092,8 +929,7 @@ private double curveAverage(SortedMap curve) { ** Calculate the shape distance: */ - private double calcShapeDeltaUsingCurveMaps(SortedMap vec1Points, SortedMap vec2Points, - SortedSet unionBuf, SortedSet keyBuf) { + private double calcShapeDeltaUsingCurveMaps(SortedMap vec1Points, SortedMap vec2Points, SortedSet unionBuf, SortedSet keyBuf) { // // We want to find out how close the "link shapes" of two nodes are, given the current @@ -1111,9 +947,9 @@ private double calcShapeDeltaUsingCurveMaps(SortedMap vec1Point unionBuf.clear(); DataUtil.union(vec1Points.keySet(), vec2Points.keySet(), unionBuf); - Iterator ubit = unionBuf.iterator(); + Iterator ubit = unionBuf.iterator(); while (ubit.hasNext()) { - Integer point = ubit.next(); + Integer point = (Integer)ubit.next(); double v1Val = interpCurve(vec1Points, point, keyBuf) - ca1; double v2Val = interpCurve(vec2Points, point, keyBuf) - ca2; double yDelt = v1Val - v2Val; @@ -1134,11 +970,11 @@ private double calcShapeDeltaUsingCurveMaps(SortedMap vec1Point ** Calculate a curve. Now only used for exact hits; interpolation code is obsolete! */ - private void calcCurveMap(SortedSet vec, List vecOrder, Integer linkEnd, Map curvePoints) { + private void calcCurveMap(SortedSet vec, List vecOrder, Integer linkEnd, Map curvePoints) { int numVec = vecOrder.size(); int vec1Pos = vecOrder.indexOf(linkEnd); if (vec1Pos != -1) { - curvePoints.put(linkEnd, new Double(numVec - vec1Pos)); + curvePoints.put(linkEnd, new Double((double)(numVec - vec1Pos))); } else { throw new IllegalArgumentException(); } @@ -1150,9 +986,9 @@ private void calcCurveMap(SortedSet vec, List vecOrder, Intege ** Calculate a curve point: */ - private double interpCurve(SortedMap curve, Integer xVal, SortedSet xBuf) { + private double interpCurve(SortedMap curve, Integer xVal, SortedSet xBuf) { - Double exact = curve.get(xVal); + Double exact = (Double)curve.get(xVal); if (exact != null) { return (exact.doubleValue()); } else { @@ -1160,15 +996,15 @@ private double interpCurve(SortedMap curve, Integer xVal, Sorte xBuf.clear(); xBuf.addAll(curve.keySet()); MinMax bounds = DataUtil.boundingInts(xBuf, xVal.intValue()); - boolean areDiff = getWeights(bounds.min, bounds.max, xVal.doubleValue(), weights); + boolean areDiff = AffineCombination.getWeights((double)bounds.min, (double)bounds.max, xVal.doubleValue(), weights); if (areDiff) { - Integer mappedEndLo = Integer.valueOf(bounds.min); - Integer mappedEndHi = Integer.valueOf(bounds.max); + Integer mappedEndLo = new Integer(bounds.min); + Integer mappedEndHi = new Integer(bounds.max); // double vec1XVal = Math.round(weights[0] * (double)bounds.min + weights[1] * (double)bounds.max); - double vec1YVal = weights[0] * curve.get(mappedEndLo).doubleValue() + weights[1] * curve.get(mappedEndHi).doubleValue(); + double vec1YVal = weights[0] * ((Double)curve.get(mappedEndLo)).doubleValue() + weights[1] * ((Double)curve.get(mappedEndHi)).doubleValue(); return (vec1YVal); - } else if (bounds.min > xBuf.first().intValue()) { - return (curve.get(curve.firstKey()).doubleValue()); + } else if (bounds.min > ((Integer)xBuf.first()).intValue()) { + return (((Double)curve.get(curve.firstKey())).doubleValue()); } else { return (0.0); } @@ -1182,10 +1018,10 @@ private double interpCurve(SortedMap curve, Integer xVal, Sorte static class DoubleRanked { double rank; - Integer id; + String id; Link byLink; - DoubleRanked(double rank, Integer id, Link byLink) { + DoubleRanked(double rank, String id, Link byLink) { this.rank = rank; this.id = id; this.byLink = byLink; @@ -1200,21 +1036,21 @@ static class DoubleRanked { public static class ClusterPrep { int numRows; - TreeMap oldToNew; - TreeMap newToOld; + TreeMap oldToNew; + TreeMap newToOld; Integer[] icache; Double[] dcache; - HashMap> curves; - HashMap>> connectMap; + HashMap curves; + HashMap connectMap; ClusterPrep(int numRows) { this.numRows = numRows; - oldToNew = new TreeMap(); - newToOld = new TreeMap(); + oldToNew = new TreeMap(); + newToOld = new TreeMap(); icache = new Integer[numRows]; dcache = new Double[numRows]; - curves = new HashMap>(); - connectMap = new HashMap>>(); + curves = new HashMap(); + connectMap = new HashMap(); } } @@ -1255,21 +1091,21 @@ public static class ClusterParams implements CRParams { public int chainLength; public int distanceMethod; - public ClusterParams(double tolerance, int chainLength, int distanceMethod) { + ClusterParams(double tolerance, int chainLength, int distanceMethod) { this.tolerance = tolerance; this.chainLength = chainLength; this.distanceMethod = distanceMethod; } - public ClusterParams() { + ClusterParams() { tolerance = 0.80; chainLength = 15; distanceMethod = JACCARD; } - public static Vector getDistanceChoices() { + public static Vector getDistanceChoices() { ResourceManager rMan = ResourceManager.getManager(); - Vector retval = new Vector(); + Vector retval = new Vector(); retval.add(new ChoiceContent(rMan.getString("clusterParams.jaccard"), JACCARD)); retval.add(new ChoiceContent(rMan.getString("clusterParams.cosines"), COSINES)); return (retval); @@ -1285,30 +1121,13 @@ public static class ResortParams implements CRParams { public int passCount; public boolean terminateAtIncrease; - public ResortParams(double tolerance, int passCount, boolean terminateAtIncrease) { + ResortParams(double tolerance, int passCount, boolean terminateAtIncrease) { this.passCount = passCount; this.terminateAtIncrease = terminateAtIncrease; } - public ResortParams() { + ResortParams() { passCount = 10; terminateAtIncrease = false; } - } - - /*************************************************************************** - ** - ** Affine coords in a single dimension - */ - - private boolean getWeights(double val1, double val2, double calcForVal, double[] toFill) { - if (val1 == val2) { - return (false); - } - toFill[0] = (calcForVal - val2) / (val1 - val2); - toFill[1] = 1.0 - toFill[0]; - return (true); - } - - - + } } diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/NodeSimilarityLayoutSetupDialog.java b/src/org/systemsbiology/biotapestry/biofabric/ClusteredLayoutParamsDialog.java similarity index 86% rename from src/org/systemsbiology/biofabric/ui/dialogs/NodeSimilarityLayoutSetupDialog.java rename to src/org/systemsbiology/biotapestry/biofabric/ClusteredLayoutParamsDialog.java index 1be1b3c..0b5e81e 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/NodeSimilarityLayoutSetupDialog.java +++ b/src/org/systemsbiology/biotapestry/biofabric/ClusteredLayoutParamsDialog.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.ui.dialogs; +package org.systemsbiology.biotapestry.biofabric; import java.awt.Dimension; import java.awt.event.ActionListener; @@ -29,19 +29,18 @@ import javax.swing.JComboBox; import javax.swing.JOptionPane; -import org.systemsbiology.biofabric.layouts.NodeSimilarityLayout; -import org.systemsbiology.biofabric.ui.dialogs.utils.BTStashResultsDialog; -import org.systemsbiology.biofabric.util.ChoiceContent; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; +import org.systemsbiology.biotapestry.ui.dialogs.utils.BTStashResultsDialog; +import org.systemsbiology.biotapestry.util.ChoiceContent; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ExceptionHandler; /**************************************************************************** ** ** Dialog box for setting layout params */ -public class NodeSimilarityLayoutSetupDialog extends BTStashResultsDialog { +public class ClusteredLayoutParamsDialog extends BTStashResultsDialog { //////////////////////////////////////////////////////////////////////////// // @@ -49,8 +48,6 @@ public class NodeSimilarityLayoutSetupDialog extends BTStashResultsDialog { // //////////////////////////////////////////////////////////////////////////// - private static final long serialVersionUID = 1L; - //////////////////////////////////////////////////////////////////////////// // // PRIVATE INSTANCE MEMBERS @@ -60,7 +57,7 @@ public class NodeSimilarityLayoutSetupDialog extends BTStashResultsDialog { private JTextField chainSizeField_; private JTextField jumpToleranceField_; private JComboBox distanceTypeCombo_; - private NodeSimilarityLayout.ClusterParams results_; + private ClusteredLayout.ClusterParams results_; //////////////////////////////////////////////////////////////////////////// // @@ -73,11 +70,11 @@ public class NodeSimilarityLayoutSetupDialog extends BTStashResultsDialog { ** Constructor */ - public NodeSimilarityLayoutSetupDialog(JFrame parent, NodeSimilarityLayout.ClusterParams params) { + public ClusteredLayoutParamsDialog(JFrame parent, ClusteredLayout.ClusterParams params) { super(parent, "clusteredLayout.title", new Dimension(600, 350), 2); results_ = null; - distanceTypeCombo_ = new JComboBox(NodeSimilarityLayout.ClusterParams.getDistanceChoices()); + distanceTypeCombo_ = new JComboBox(ClusteredLayout.ClusterParams.getDistanceChoices()); int numSrc = distanceTypeCombo_.getItemCount(); for (int i = 0; i < numSrc; i++) { ChoiceContent cc = (ChoiceContent)distanceTypeCombo_.getItemAt(i); @@ -128,7 +125,7 @@ public void actionPerformed(ActionEvent ev) { ** Get results */ - public NodeSimilarityLayout.ClusterParams getParams() { + public ClusteredLayout.ClusterParams getParams() { return (results_); } @@ -146,7 +143,7 @@ public NodeSimilarityLayout.ClusterParams getParams() { protected boolean stashForOK() { - results_ = new NodeSimilarityLayout.ClusterParams(); + results_ = new ClusteredLayout.ClusterParams(); ChoiceContent cc = (ChoiceContent)distanceTypeCombo_.getSelectedItem(); results_.distanceMethod = cc.val; @@ -236,7 +233,7 @@ private Integer parseInteger(String intVal, String badMsg) { JOptionPane.ERROR_MESSAGE); return (null); } - return (Integer.valueOf(retVal)); + return (new Integer(retVal)); } /*************************************************************************** @@ -246,7 +243,7 @@ private Integer parseInteger(String intVal, String badMsg) { */ private void resetDefaults() { - NodeSimilarityLayout.ClusterParams defaults = new NodeSimilarityLayout.ClusterParams(); + ClusteredLayout.ClusterParams defaults = new ClusteredLayout.ClusterParams(); int numSrc = distanceTypeCombo_.getItemCount(); for (int i = 0; i < numSrc; i++) { diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/CompareNodesSetupDialog.java b/src/org/systemsbiology/biotapestry/biofabric/CompareNodesSetupDialog.java similarity index 58% rename from src/org/systemsbiology/biofabric/ui/dialogs/CompareNodesSetupDialog.java rename to src/org/systemsbiology/biotapestry/biofabric/CompareNodesSetupDialog.java index 4f0d2aa..08d152c 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/CompareNodesSetupDialog.java +++ b/src/org/systemsbiology/biotapestry/biofabric/CompareNodesSetupDialog.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2016 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,8 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.dialogs; + +package org.systemsbiology.biotapestry.biofabric; import java.awt.Dimension; import java.awt.event.ActionEvent; @@ -27,22 +28,18 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Set; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JOptionPane; -import org.systemsbiology.biofabric.cmd.CommandSet; -import org.systemsbiology.biofabric.ui.dialogs.utils.BTStashResultsDialog; -import org.systemsbiology.biofabric.ui.dialogs.utils.EditableTable; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; -import org.systemsbiology.biotapestry.biofabric.FabricCommands; +import org.systemsbiology.biotapestry.ui.dialogs.utils.BTStashResultsDialog; +import org.systemsbiology.biotapestry.ui.dialogs.utils.EditableTable; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.DataUtil; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.UiUtil; /**************************************************************************** ** @@ -57,11 +54,9 @@ public class CompareNodesSetupDialog extends BTStashResultsDialog { // //////////////////////////////////////////////////////////////////////////// - private static final long serialVersionUID = 1L; - private Set result_; - private EditableTable est_; - private Set allNodeIDs_; - private Map> normNameToID_; + private Set result_; + private EditableTable est_; + private Set allNodes_; //////////////////////////////////////////////////////////////////////////// // @@ -74,11 +69,10 @@ public class CompareNodesSetupDialog extends BTStashResultsDialog { ** Constructor */ - public CompareNodesSetupDialog(JFrame parent, Set allNodeIDs, Map> normNameToID) { + public CompareNodesSetupDialog(JFrame parent, Set allNodes) { super(parent, "compareNodesSetup.title", new Dimension(600, 500), 2); result_ = null; - allNodeIDs_ = allNodeIDs; - normNameToID_ = normNameToID; + allNodes_ = allNodes; // // Build extra button: @@ -95,7 +89,7 @@ public void actionPerformed(ActionEvent ev) { } }); - est_ = new EditableTable(new NodeListTableModel(), parent_); + est_ = new EditableTable(new NodeListTableModel(), parent_); EditableTable.TableParams etp = new EditableTable.TableParams(); etp.addAlwaysAtEnd = false; etp.buttons = EditableTable.ALL_BUT_EDIT_BUTTONS; @@ -113,7 +107,7 @@ public void actionPerformed(ActionEvent ev) { ** */ - public Set getResults() { + public Set getResults() { return (result_); } @@ -134,52 +128,36 @@ public Set getResults() { ** The table */ - class NodeListTableModel extends EditableTable.TableModel { + class NodeListTableModel extends EditableTable.TableModel { - private static final long serialVersionUID = 1L; private final static int NODE_NAME_ = 0; - private final static int NUM_COL_ = 1; - - private final static int NID_ = 0; - private final static int NUM_HIDDEN_ = 1; + private final static int NUM_COL_ = 1; NodeListTableModel() { super(NUM_COL_); colNames_ = new String[] {"compareNodesSetup.nodeName"}; colClasses_ = new Class[] {String.class}; - addHiddenColumns(NUM_HIDDEN_); } - public class TableRow implements EditableTable.ATableRow { - public String nodeName; - public String nid; - - public TableRow() { - } - - TableRow(int i) { - nodeName = (String)columns_.get(NODE_NAME_).get(i); - nid = (String)hiddenColumns_.get(NID_).get(i); - } - - public void toCols() { - columns_.get(NODE_NAME_).add(nodeName); - hiddenColumns_.get(NID_).add(nid); - return; + public List getValuesFromTable() { + ArrayList retval = new ArrayList(); + for (int i = 0; i < this.rowCount_; i++) { + retval.add((String)columns_[NODE_NAME_].get(i)); } + return (retval); } - - protected TableRow constructARow(int i) { - return (new TableRow(i)); + + public void extractValues(List prsList) { + super.extractValues(prsList); + Iterator rit = prsList.iterator(); + while (rit.hasNext()) { + columns_[NODE_NAME_].add(rit.next()); + } + return; } - public TableRow constructARow() { - return (new TableRow()); - } - - - List applyValues() { - List vals = getValuesFromTable(); + List applyValues() { + List vals = getValuesFromTable(); // // Make sure the groups are OK. Names must be unique, non-blank, present as suffixes in the @@ -187,15 +165,14 @@ List applyValues() { // ResourceManager rMan = ResourceManager.getManager(); - ArrayList seenTags = new ArrayList(); + ArrayList seenTags = new ArrayList(); int size = vals.size(); if (size == 0) { return (seenTags); } for (int i = 0; i < size; i++) { - TableRow row = vals.get(i); - String tag = row.nodeName; + String tag = (String)vals.get(i); if ((tag == null) || (tag.trim().equals(""))) { JOptionPane.showMessageDialog(parent_, rMan.getString("compareNodesSetup.badName"), rMan.getString("compareNodesSetup.badNameTitle"), @@ -212,28 +189,15 @@ List applyValues() { return (null); } - - String normTag = DataUtil.normKey(tag); - Set haveIDs = normNameToID_.get(normTag); - boolean gotIt = (haveIDs != null); - if (gotIt) { - gotIt = false; - for (NID.WithName haveID : haveIDs) { - if (allNodeIDs_.contains(haveID)) { - gotIt = true; - break; - } - } - } - if (!gotIt) { + if (!DataUtil.containsKey(allNodes_, tag)) { JOptionPane.showMessageDialog(parent_, rMan.getString("compareNodesSetup.notANode"), rMan.getString("compareNodesSetup.notANodeTitle"), JOptionPane.ERROR_MESSAGE); return (null); } - seenTags.add(new NID.WithName(new NID(row.nid), tag)); + seenTags.add(tag); } return (seenTags); @@ -253,13 +217,12 @@ List applyValues() { */ protected boolean stashForOK() { - List av = ((NodeListTableModel)est_.getModel()).applyValues(); + List av = ((NodeListTableModel)est_.getModel()).applyValues(); if (av == null) { result_ = null; return (false); } - - result_ = new HashSet(av); + result_ = new HashSet(av); return (true); } @@ -270,43 +233,18 @@ protected boolean stashForOK() { */ void loadFromFile() { - CommandSet cmd = CommandSet.getCmds("mainWindow"); + FabricCommands cmd = FabricCommands.getCmds("mainWindow"); File fileEda = cmd.getTheFile(".txt", null, "AttribDirectory", "filterName.txt"); if (fileEda == null) { return; } - List nodes = UiUtil.simpleFileRead(fileEda); + List nodes = UiUtil.simpleFileRead(fileEda); if (nodes == null) { return; } - List initRows = initTableRows(nodes); - est_.updateTable(true, initRows); - FabricCommands.setPreference("AttribDirectory", fileEda.getAbsoluteFile().getParent()); + ((NodeListTableModel)est_.getModel()).extractValues(nodes); + est_.updateTable(true, nodes); + cmd.setPreference("AttribDirectory", fileEda.getAbsoluteFile().getParent()); return; } - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Get the list of table rows - ** - */ - - private List initTableRows(List inTags) { - ArrayList retval = new ArrayList(); - EditableTable.TableModel ecdtm = est_.getModel(); - Iterator ceit = inTags.iterator(); - while (ceit.hasNext()) { - String tag = ceit.next(); - NodeListTableModel.TableRow tr = ecdtm.constructARow(); - tr.nodeName = tag; - retval.add(tr); - } - return (retval); - } } diff --git a/src/org/systemsbiology/biotapestry/biofabric/DeadFabricGoose.java b/src/org/systemsbiology/biotapestry/biofabric/DeadFabricGoose.java new file mode 100644 index 0000000..8b2b061 --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/DeadFabricGoose.java @@ -0,0 +1,194 @@ +/* +** Copyright (C) 2003-2008 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + + +/**************************************************************************** +** +** Used as a stub for applications not using the gaggle +*/ + +public class DeadFabricGoose implements FabricGooseInterface { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Constructor + */ + + public DeadFabricGoose() { + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Activate the goose - called on AWT thread + */ + + public void activate() { + return; + } + + /*************************************************************************** + ** + ** Set goose parameters - called on AWT thread + */ + + public void setParameters(BioFabricWindow topWindow, String species) { + return; + } + + /*************************************************************************** + ** + ** A function to find out if goose is active - called on AWT thread + */ + + public boolean isActivated() { + return (false); + } + + /*************************************************************************** + ** + ** A function to find out if goose is connected - called on AWT thread + */ + + public boolean isConnected() { + return (false); + } + + /*************************************************************************** + ** + ** A function to connect to gaggle - called on AWT thread + */ + + public void connect() { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** Disconnect from gaggle - called on AWT thread + */ + + public void disconnect() { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** A function to get selection support - called on AWT thread + */ + + public SelectionSupport getSelectionSupport() { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** A function to set the current gaggle target - called on AWT thread + */ + + public void setCurrentGaggleTarget(String gooseName) { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** A function to transmit selections to the gaggle boss. - called on AWT thread + */ + + public void transmitSelections() { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** A function to transmit a network - called on AWT thread + */ + + public void transmitNetwork(SelectionSupport.NetworkForSpecies net) { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** A function to show the current target - called on AWT thread + */ + + public void raiseCurrentTarget() { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** A function to hide the current target - called on AWT thread + */ + + public void hideCurrentTarget() { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** A function to shut down the gaggle infrastructure - called on AWT thread + */ + + public void closeDown() { + throw new IllegalStateException(); + } + + /*************************************************************************** + ** + ** Connect to the boss (Goose req'd - called on AWT thread) + */ + + public void connectToGaggle() { + throw new IllegalStateException(); + } +} + \ No newline at end of file diff --git a/src/org/systemsbiology/biofabric/ui/FabricColorGenerator.java b/src/org/systemsbiology/biotapestry/biofabric/FabricColorGenerator.java similarity index 85% rename from src/org/systemsbiology/biofabric/ui/FabricColorGenerator.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricColorGenerator.java index af06e1a..4d752c1 100644 --- a/src/org/systemsbiology/biofabric/ui/FabricColorGenerator.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricColorGenerator.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2017 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.biofabric; import java.awt.Color; import java.io.IOException; @@ -28,12 +28,12 @@ import org.xml.sax.Attributes; -import org.systemsbiology.biofabric.db.ColorGenerator; -import org.systemsbiology.biofabric.io.FabricFactory; -import org.systemsbiology.biofabric.parser.AbstractFactoryClient; -import org.systemsbiology.biofabric.parser.GlueStick; -import org.systemsbiology.biofabric.util.AttributeExtractor; -import org.systemsbiology.biofabric.util.Indenter; +import org.systemsbiology.biotapestry.db.ColorGenerator; +import org.systemsbiology.biotapestry.parser.AbstractFactoryClient; +import org.systemsbiology.biotapestry.parser.GlueStick; +import org.systemsbiology.biotapestry.ui.NamedColor; +import org.systemsbiology.biotapestry.util.AttributeExtractor; +import org.systemsbiology.biotapestry.util.Indenter; /**************************************************************************** ** @@ -59,8 +59,8 @@ public class FabricColorGenerator { //////////////////////////////////////////////////////////////////////////// private ColorGenerator myColGen_; - private HashMap brighter_; - private HashMap darker_; + private HashMap brighter_; + private HashMap darker_; //////////////////////////////////////////////////////////////////////////// // @@ -75,8 +75,8 @@ public class FabricColorGenerator { public FabricColorGenerator() { myColGen_ = new ColorGenerator(); - brighter_ = new HashMap(); - darker_ = new HashMap(); + brighter_ = new HashMap(); + darker_ = new HashMap(); } //////////////////////////////////////////////////////////////////////////// @@ -111,18 +111,13 @@ public void newColorModel() { float db = Math.min(1.0F, hsbvals[2] * (float)dark); darker_.put(gckey, Color.getHSBColor(hsbvals[0], hsbvals[1], db)); } else { - // These three standard colors get TOO light if we apply the operation. So keep them as is: - if ((nc.name.indexOf("Gold") == -1) && (nc.name.indexOf("Dark Wheat") == -1) && (nc.name.indexOf("Pale Goldenrod") == -1)) { - int rb = Math.min(255, (int)Math.round(baseR * light)); - int gb = Math.min(255, (int)Math.round(baseG * light)); - int bb = Math.min(255, (int)Math.round(baseB * light)); - brighter_.put(gckey, new Color(rb, gb, bb)); - } else { - brighter_.put(gckey, nc.color); - } - int rd = Math.min(255, (int)Math.round(baseR * dark)); - int gd = Math.min(255, (int)Math.round(baseG * dark)); - int bd = Math.min(255, (int)Math.round(baseB * dark)); + int rb = Math.min(255, (int)Math.round((double)baseR * light)); + int gb = Math.min(255, (int)Math.round((double)baseG * light)); + int bb = Math.min(255, (int)Math.round((double)baseB * light)); + brighter_.put(gckey, new Color(rb, gb, bb)); + int rd = Math.min(255, (int)Math.round((double)baseR * dark)); + int gd = Math.min(255, (int)Math.round((double)baseG * dark)); + int bd = Math.min(255, (int)Math.round((double)baseB * dark)); darker_.put(gckey, new Color(rd, gd, bd)); } } @@ -173,10 +168,10 @@ public Color getModifiedColor(String colorKey, int which) { paintCol = ((nc == null) || (nc.color == null)) ? null : nc.color; break; case DARKER: - paintCol = darker_.get(colorKey); + paintCol = (Color)darker_.get(colorKey); break; case BRIGHTER: - paintCol = brighter_.get(colorKey); + paintCol = (Color)brighter_.get(colorKey); break; default: throw new IllegalArgumentException(); @@ -234,16 +229,16 @@ public void writeXML(PrintWriter out, Indenter ind) { ** */ - private void writeColorsForType(PrintWriter out, Indenter ind, String type, Map colMap) { + private void writeColorsForType(PrintWriter out, Indenter ind, String type, Map colMap) { ind.indent(); out.print(""); ind.up(); - Iterator colors = colMap.keySet().iterator(); + Iterator colors = colMap.keySet().iterator(); while (colors.hasNext()) { - String key = colors.next(); - Color c = colMap.get(key); + String key = (String)colors.next(); + Color c = (Color)colMap.get(key); ind.indent(); out.print(" 500000) { + sss = new FabricSIFLoader.SIFStats(); + BackgroundFileReader br = new BackgroundFileReader(); + br.doBackgroundSIFRead(file, links, loneNodes, nameMap, sss); + return (true); + } else { + try { + sss = (new FabricSIFLoader()).readSIF(file, links, loneNodes, nameMap); + return (finishLoadFromSIFSource(file, sss, links, loneNodes)); + } catch (IOException ioe) { + displayFileInputError(ioe); + return (false); + } catch (OutOfMemoryError oom) { + ExceptionHandler.getHandler().displayOutOfMemory(oom); + return (false); + } + } + } + + /*************************************************************************** + ** + ** Common load operations. + */ + + private boolean finishLoadFromSIFSource(File file, FabricSIFLoader.SIFStats sss, List links, Set loneNodes) { + ResourceManager rMan = ResourceManager.getManager(); + try { + if (!sss.badLines.isEmpty()) { + String badLineFormat = rMan.getString("fabricRead.badLineFormat"); + String badLineMsg = MessageFormat.format(badLineFormat, new Object[] {new Integer(sss.badLines.size())}); + JOptionPane.showMessageDialog(topWindow_, badLineMsg, + rMan.getString("fabricRead.badLineTitle"), + JOptionPane.WARNING_MESSAGE); + } + SortedMap relaMap = BioFabricNetwork.extractRelations(links); + RelationDirectionDialog rdd = new RelationDirectionDialog(topWindow_, relaMap); + rdd.show(); + if (!rdd.haveResult()) { + return (false); + } + if (rdd.getFromFile()) { + File fileEda = getTheFile(".rda", ".txt", "AttribDirectory", "filterName.rda"); + if (fileEda == null) { + return (true); + } + Map relAttributes = loadTheFile(fileEda, true); // Use the simple a = b format of node attributes + if (relAttributes == null) { + return (true); + } + + HashSet needed = new HashSet(relaMap.keySet()); + + boolean tooMany = false; + Iterator rit = relAttributes.keySet().iterator(); + while (rit.hasNext()) { + String key = (String)rit.next(); + String val = (String)relAttributes.get(key); + Boolean dirVal = Boolean.valueOf(val); + FabricLink.AugRelation forNorm = new FabricLink.AugRelation(key, false); + FabricLink.AugRelation forShad = new FabricLink.AugRelation(key, true); + boolean matched = false; + if (needed.contains(forNorm)) { + matched = true; + relaMap.put(forNorm, dirVal); + needed.remove(forNorm); + } + if (needed.contains(forShad)) { + matched = true; + relaMap.put(forShad, dirVal); + needed.remove(forShad); + } + if (!matched) { + tooMany = true; + break; + } + } + if (!needed.isEmpty() || tooMany) { + JOptionPane.showMessageDialog(topWindow_, rMan.getString("fabricRead.directionMapLoadFailure"), + rMan.getString("fabricRead.directionMapLoadFailureTitle"), + JOptionPane.ERROR_MESSAGE); + return (false); + } + } else { + relaMap = rdd.getRelationMap(); + } + + BioFabricNetwork.assignDirections(links, relaMap); + HashSet reducedLinks = new HashSet(); + HashSet culledLinks = new HashSet(); + BioFabricNetwork.preprocessLinks(links, reducedLinks, culledLinks); + if (!culledLinks.isEmpty()) { + String dupLinkFormat = rMan.getString("fabricRead.dupLinkFormat"); + // Ignore shadow link culls: / 2 + String dupLinkMsg = MessageFormat.format(dupLinkFormat, new Object[] {new Integer(culledLinks.size() / 2)}); + JOptionPane.showMessageDialog(topWindow_, dupLinkMsg, + rMan.getString("fabricRead.dupLinkTitle"), + JOptionPane.WARNING_MESSAGE); + } + + BioFabricNetwork.OrigBuildData bfn = new BioFabricNetwork.OrigBuildData(reducedLinks, loneNodes, colGen_, BioFabricNetwork.BUILD_FROM_SIF); + NetworkBuilder nb = new NetworkBuilder(); + nb.doNetworkBuild(bfn, true); + } catch (OutOfMemoryError oom) { + ExceptionHandler.getHandler().displayOutOfMemory(oom); + return (false); + } + currentFile_ = null; + setPreference("LoadDirectory", file.getAbsoluteFile().getParent()); + manageWindowTitle(file.getName()); + return (true); + } + + /*************************************************************************** + ** + ** Common load operations. + */ + + private boolean loadXMLFromSource(File file) { + ArrayList alist = new ArrayList(); + FabricFactory ff = new FabricFactory(); + alist.add(ff); + SUParser sup = new SUParser(alist); + if (file.length() > 1000000) { + BackgroundFileReader br = new BackgroundFileReader(); + br.doBackgroundRead(ff, sup, file); + return (true); + } else { + try { + sup.parse(file); + } catch (IOException ioe) { + displayFileInputError(ioe); + return (false); + } catch (OutOfMemoryError oom) { + ExceptionHandler.getHandler().displayOutOfMemory(oom); + return (false); + } + } + setCurrentXMLFile(file); + postXMLLoad(ff, file.getName()); + return (true); + } + + /*************************************************************************** + ** + ** Common load operations. + */ + + boolean postXMLLoad(FabricFactory ff, String fileName) { + BioFabricNetwork bfn = ff.getFabricNetwork(); + BioFabricNetwork.PreBuiltBuildData pbd = new BioFabricNetwork.PreBuiltBuildData(bfn, BioFabricNetwork.BUILD_FROM_XML); + NetworkBuilder nb = new NetworkBuilder(); + nb.doNetworkBuild(pbd, true); + manageWindowTitle(fileName); + return (true); + } + + /*************************************************************************** + ** + ** Load network from gaggle + */ + + public boolean loadFromGaggle(List links, List singles) { + HashSet reducedLinks = new HashSet(); + HashSet culledLinks = new HashSet(); + BioFabricNetwork.preprocessLinks(links, reducedLinks, culledLinks); + if (!culledLinks.isEmpty()) { + ResourceManager rMan = ResourceManager.getManager(); + String dupLinkFormat = rMan.getString("fabricRead.dupLinkFormat"); + // Ignore shadow link culls: / 2 + String dupLinkMsg = MessageFormat.format(dupLinkFormat, new Object[] {new Integer(culledLinks.size() / 2)}); + JOptionPane.showMessageDialog(topWindow_, dupLinkMsg, + rMan.getString("fabricRead.dupLinkTitle"), + JOptionPane.WARNING_MESSAGE); + } + BioFabricNetwork.OrigBuildData bfnbd = new BioFabricNetwork.OrigBuildData(reducedLinks, new HashSet(singles), colGen_, BioFabricNetwork.BUILD_FROM_GAGGLE); + NetworkBuilder nb = new NetworkBuilder(); + nb.doNetworkBuild(bfnbd, true); + manageWindowTitle("Gaggle"); + return (true); + } + + /*************************************************************************** + ** + ** Do standard file checks and warnings + */ + + public boolean standardFileChecks(File target, boolean mustExist, boolean canCreate, + boolean checkOverwrite, boolean mustBeDirectory, + boolean canWrite, boolean canRead) { + ResourceManager rMan = ResourceManager.getManager(); + boolean doesExist = target.exists(); + + if (mustExist) { + if (!doesExist) { + String noFileFormat = rMan.getString("fileChecks.noFileFormat"); + String noFileMsg = MessageFormat.format(noFileFormat, new Object[] {target.getName()}); + JOptionPane.showMessageDialog(topWindow_, noFileMsg, + rMan.getString("fileChecks.noFileTitle"), + JOptionPane.ERROR_MESSAGE); + return (false); + } + } + if (mustBeDirectory) { + if (doesExist && !target.isDirectory()) { + String notADirectoryFormat = rMan.getString("fileChecks.notADirectoryFormat"); + String notADirectoryMsg = MessageFormat.format(notADirectoryFormat, new Object[] {target.getName()}); + JOptionPane.showMessageDialog(topWindow_, notADirectoryMsg, + rMan.getString("fileChecks.notADirectoryTitle"), + JOptionPane.ERROR_MESSAGE); + return (false); + } + } else { // gotta be a file + if (doesExist && !target.isFile()) { + String notAFileFormat = rMan.getString("fileChecks.notAFileFormat"); + String notAFileMsg = MessageFormat.format(notAFileFormat, new Object[] {target.getName()}); + JOptionPane.showMessageDialog(topWindow_, notAFileMsg, + rMan.getString("fileChecks.notAFileTitle"), + JOptionPane.ERROR_MESSAGE); + return (false); + } + } + + if (!doesExist && canCreate) { + if (mustBeDirectory) { + throw new IllegalArgumentException(); + } + boolean couldNotCreate = false; + try { + if (!target.createNewFile()) { + couldNotCreate = true; + } + } catch (IOException ioex) { + couldNotCreate = true; + } + if (couldNotCreate) { + String noCreateFormat = rMan.getString("fileChecks.noCreateFormat"); + String noCreateMsg = MessageFormat.format(noCreateFormat, new Object[] {target.getName()}); + JOptionPane.showMessageDialog(topWindow_, noCreateMsg, + rMan.getString("fileChecks.noCreateTitle"), + JOptionPane.ERROR_MESSAGE); + return (false); + } + } + + boolean didExist = doesExist; + doesExist = target.exists(); + + if (canWrite) { + if (doesExist && !target.canWrite()) { + String noWriteFormat = rMan.getString("fileChecks.noWriteFormat"); + String noWriteMsg = MessageFormat.format(noWriteFormat, new Object[] {target.getName()}); + JOptionPane.showMessageDialog(topWindow_, noWriteMsg, + rMan.getString("fileChecks.noWriteTitle"), + JOptionPane.ERROR_MESSAGE); + return (false); + } + } + if (canRead) { + if (doesExist && !target.canRead()) { + String noReadFormat = rMan.getString("fileChecks.noReadFormat"); + String noReadMsg = MessageFormat.format(noReadFormat, new Object[] {target.getName()}); + JOptionPane.showMessageDialog(topWindow_, noReadMsg, + rMan.getString("fileChecks.noReadTitle"), + JOptionPane.ERROR_MESSAGE); + return (false); + } + } + + if (didExist && checkOverwrite) { // note we care about DID exist (before creation) + String overFormat = rMan.getString("fileChecks.doOverwriteFormat"); + String overMsg = MessageFormat.format(overFormat, new Object[] {target.getName()}); + int overwrite = + JOptionPane.showConfirmDialog(topWindow_, overMsg, + rMan.getString("fileChecks.doOverwriteTitle"), + JOptionPane.YES_NO_OPTION); + if (overwrite != JOptionPane.YES_OPTION) { + return (false); + } + } + return (true); + } + + /*************************************************************************** + ** + ** Get readable attribute file + */ + + public File getTheFile(String ext1, String ext2, String prefTag, String desc) { + File file = null; + String filename = getPreference(prefTag); + while (file == null) { + JFileChooser chooser = new JFileChooser(); + FileFilter filter; + if (ext2 == null) { + filter = new FileExtensionFilters.SimpleFilter(ext1, desc); + } else { + filter = new FileExtensionFilters.DoubleExtensionFilter(ext1, ext2, desc); + } + chooser.addChoosableFileFilter(filter); + if (filename != null) { + File startDir = new File(filename); + if (startDir.exists()) { + chooser.setCurrentDirectory(startDir); + } + } + + int option = chooser.showOpenDialog(topWindow_); + if (option != JFileChooser.APPROVE_OPTION) { + return (null); + } + file = chooser.getSelectedFile(); + if (file == null) { + return (null); + } + if (!standardFileChecks(file, FILE_MUST_EXIST, FILE_CAN_CREATE_DONT_CARE, + FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE_DONT_CARE, FILE_CAN_READ)) { + file = null; + continue; + } + } + return (file); + } + + /*************************************************************************** + ** + ** Do standard file checks and warnings + */ + + public Map loadTheFile(File file, boolean forNodes) { + HashMap attributes = new HashMap(); + try { + AttributeLoader.ReadStats stats = new AttributeLoader.ReadStats(); + AttributeLoader alod = new AttributeLoader(); + alod.readAttributes(file, forNodes, attributes, stats); + if (!stats.badLines.isEmpty()) { + ResourceManager rMan = ResourceManager.getManager(); + String badLineFormat = rMan.getString("attribRead.badLineFormat"); + String badLineMsg = MessageFormat.format(badLineFormat, new Object[] {new Integer(stats.badLines.size())}); + JOptionPane.showMessageDialog(topWindow_, badLineMsg, + rMan.getString("attribRead.badLineTitle"), + JOptionPane.WARNING_MESSAGE); + } + if (!stats.dupLines.isEmpty()) { + ResourceManager rMan = ResourceManager.getManager(); + String dupLineFormat = rMan.getString("attribRead.dupLineFormat"); + String dupLineMsg = MessageFormat.format(dupLineFormat, new Object[] {new Integer(stats.dupLines.size())}); + JOptionPane.showMessageDialog(topWindow_, dupLineMsg, + rMan.getString("attribRead.dupLineTitle"), + JOptionPane.WARNING_MESSAGE); + } + if (!forNodes && !stats.shadowsPresent) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, rMan.getString("attribRead.noShadowError"), + rMan.getString("attribRead.noShadowTitle"), + JOptionPane.ERROR_MESSAGE); + return (null); + } + + } catch (IOException ioe) { + displayFileInputError(ioe); + return (null); + } + setPreference("AttribDirectory", file.getAbsoluteFile().getParent()); + return (attributes); + } + + /*************************************************************************** + ** + ** Do new model operations + */ + + public void preLoadOperations() { + bfp_.reset(); + return; + } + + /*************************************************************************** + ** + ** Do new model operations + */ + + public BufferedImage expensiveModelOperations(BioFabricNetwork.BuildData bfnbd, boolean forMain) throws IOException { + Dimension screenSize = (forMain) ? Toolkit.getDefaultToolkit().getScreenSize() : new Dimension(600, 800); + screenSize.setSize((int)(screenSize.getWidth() * 0.8), (int)(screenSize.getHeight() * 0.4)); + // Possibly expensive network analysis preparation: + BioFabricNetwork bfn = new BioFabricNetwork(bfnbd); + // Possibly expensive display object creation: + bfp_.installModel(bfn); + // Very expensive display buffer creation: + boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); + int lco = bfn.getLinkCount(showShadows); + int[] preZooms; + if (lco != 0) { + int linkLog = (int)Math.ceil(Math.log(lco) / Math.log(2.0)); + int firstDrawLog = (int)Math.ceil(Math.log(1.0E4) / Math.log(2.0)); + int numPre = Math.max(linkLog - firstDrawLog, 4); + preZooms = new int[numPre]; + preZooms[0] = 1; + for (int i = 1; i < numPre; i++) { + preZooms[i] = 2 * preZooms[i - 1]; + } + } else { + preZooms = new int[1]; + preZooms[0] = 1; + } + + bfp_.zoomForBuf(preZooms, screenSize); + BufferedImage topImage = null; + if (forMain) { + BufferBuilder bb = new BufferBuilder(null, 1/*30*/, bfp_); + topImage = bb.buildBufs(preZooms, bfp_, 24); + bfp_.setBufBuilder(bb); + } else { + BufferBuilder bb = new BufferBuilder(bfp_); + topImage = bb.buildOneBuf(preZooms); + bfp_.setBufBuilder(null); + } + return (topImage); + } + + /*************************************************************************** + ** + ** Do new model operations + */ + + public BufferedImage expensiveRecolorOperations(boolean forMain) throws IOException { + Dimension screenSize = (forMain) ? Toolkit.getDefaultToolkit().getScreenSize() : new Dimension(800, 400); + screenSize.setSize((int)(screenSize.getWidth() * 0.8), (int)(screenSize.getHeight() * 0.4)); + colGen_.newColorModel(); + bfp_.changePaint(); + + BioFabricNetwork bfn = bfp_.getNetwork(); + int numPre = 4; + if (bfn != null) { + boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); + int linkLog = (int)Math.ceil(Math.log(bfn.getLinkCount(showShadows)) / Math.log(2.0)); + int firstDrawLog = (int)Math.ceil(Math.log(1.0E4) / Math.log(2.0)); + numPre = Math.max(linkLog - firstDrawLog, 4); + } + int[] preZooms = new int[numPre]; + preZooms[0] = 1; + for (int i = 1; i < numPre; i++) { + preZooms[i] = 2 * preZooms[i - 1]; + } + + bfp_.zoomForBuf(preZooms, screenSize); + BufferedImage topImage = null; + if (forMain) { + BufferBuilder bb = new BufferBuilder(null, 1, bfp_); + topImage = bb.buildBufs(preZooms, bfp_, 24); + bfp_.setBufBuilder(bb); + } else { + BufferBuilder bb = new BufferBuilder(bfp_); + topImage = bb.buildOneBuf(preZooms); + bfp_.setBufBuilder(null); + } + return (topImage); + } + + /*************************************************************************** + ** + ** Handles post-recolor operations + */ + + public void postRecolorOperations(BufferedImage topImage) { + topWindow_.getOverview().installImage(topImage, bfp_.getWorldRect()); + return; + } + + /*************************************************************************** + ** + ** Handles post-loading operations + */ + + public void postLoadOperations(BufferedImage topImage) { + topWindow_.getOverview().installImage(topImage, bfp_.getWorldRect()); + bfp_.installModelPost(); + bfp_.installZooms(); + bfp_.initZoom(); + checkForChanges(); + bfp_.repaint(); + return; + } + + /*************************************************************************** + ** + ** Do new model operations all on AWT thread! + */ + + public void newModelOperations(BioFabricNetwork.BuildData bfnbd, boolean forMain) throws IOException { + preLoadOperations(); + BufferedImage topImage = expensiveModelOperations(bfnbd, forMain); + postLoadOperations(topImage); + return; + } + + /*************************************************************************** + ** + ** Do window title + */ + + public void manageWindowTitle(String fileName) { + ResourceManager rMan = ResourceManager.getManager(); + String title; + if (fileName == null) { + title = rMan.getString("window.title"); + } else { + String titleFormat = rMan.getString("window.titleWithName"); + title = MessageFormat.format(titleFormat, new Object[] {fileName}); + } + topWindow_.setTitle(title); + return; } + + /*************************************************************************** + ** + ** Common save activities + */ + + boolean saveToFile(String fileName) { + + File file = null; + if (fileName == null) { + String dirName = getPreference("LoadDirectory"); + while (file == null) { + JFileChooser chooser = new JFileChooser(); + chooser.addChoosableFileFilter(new FileExtensionFilters.SimpleFilter(".bif", "filterName.bif")); + if (dirName != null) { + File startDir = new File(dirName); + if (startDir.exists()) { + chooser.setCurrentDirectory(startDir); + } + } + int option = chooser.showSaveDialog(topWindow_); + if (option != JFileChooser.APPROVE_OPTION) { + return (true); + } + file = chooser.getSelectedFile(); + if (file != null) { + if (!file.exists()) { + if (!FileExtensionFilters.hasSuffix(file.getName(), ".bif")) { + file = new File(file.getAbsolutePath() + ".bif"); + } + } + if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, + FILE_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { + file = null; + continue; + } + } + } + } else { + // given a name, we do not check overwrite: + file = new File(fileName); + if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, + FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { + return (false); + } + } + + + BioFabricNetwork bfn = bfp_.getNetwork(); + + if (bfn.getLinkCount(true) > 5000) { + BackgroundFileWriter bw = new BackgroundFileWriter(); + bw.doBackgroundWrite(file); + return (true); + } else { + try { + saveToOutputStream(new FileOutputStream(file)); + setCurrentXMLFile(file); + manageWindowTitle(file.getName()); + return (true); + } catch (IOException ioe) { + displayFileOutputError(); + return (false); + } + } + } + + /*************************************************************************** + ** + ** Move nodes to match shapes + */ + + public Map doReorderLayout(BioFabricNetwork bfn, + ClusteredLayout.CRParams params, + BTProgressMonitor monitor, + double startFrac, + double endFrac) throws AsynchExitRequestException { + + ClusteredLayout lo = new ClusteredLayout(); + SortedMap connVecs = lo.getConnectivityVectors(bfn); + + ClusteredLayout.ResortParams rp = (ClusteredLayout.ResortParams)params; + + List ordered = new ArrayList(); + int numRows = bfn.getRowCount(); + for (int i = 0; i < numRows; i++) { + ordered.add(Integer.toString(i)); + } + + double currStart = startFrac; + double inc = (endFrac - startFrac) / (double)rp.passCount; + double currEnd = currStart + inc; + + TreeMap rankings = new TreeMap(); + ClusteredLayout.ClusterPrep cprep = lo.setupForResort(bfn, connVecs, ordered, rankings); + Double lastRank = (Double)rankings.get(rankings.lastKey()); + + for (int i = 0; i < rp.passCount; i++) { + monitor.updateRankings(rankings); + List nextOrdered = lo.resort(cprep, monitor, currStart, currEnd); + currStart = currEnd; + currEnd = currStart + inc; + cprep = lo.setupForResort(bfn, connVecs, nextOrdered, rankings); + Integer lastKey = (Integer)rankings.lastKey(); + Double nowRank = (Double)rankings.get(lastKey); + if (rp.terminateAtIncrease) { + if (lastRank.doubleValue() < nowRank.doubleValue()) { + rankings.remove(lastKey); + break; + } + } + ordered = nextOrdered; + lastRank = nowRank; + } + + monitor.updateRankings(rankings); + Map orderedNames = lo.convertOrderToMap(bfn, ordered); + return (orderedNames); + } + + /*************************************************************************** + ** + ** Clustered Layout guts + */ + + public Map doClusteredLayout(BioFabricNetwork bfn, + ClusteredLayout.CRParams params, + BTProgressMonitor monitor, + double startFrac, double endFrac) throws AsynchExitRequestException { + + + + ClusteredLayout lo = new ClusteredLayout(); + ClusteredLayout.ClusterParams cp = (ClusteredLayout.ClusterParams)params; + SortedMap connVecs = lo.getConnectivityVectors(bfn); + + TreeMap dists = new TreeMap(Collections.reverseOrder()); + HashMap connMag = new HashMap(); + + Integer mostConnected = (cp.distanceMethod == ClusteredLayout.ClusterParams.COSINES) ? + lo.getConnectivityCosines(connVecs, dists, connMag, bfn) : + lo.getConnectivityJaccard(connVecs, dists, connMag, bfn); + + ArrayList linkTrace = new ArrayList(); + ArrayList jumpLog = new ArrayList(); + List ordered = lo.orderByDistanceChained(bfn, mostConnected, dists, + connMag, linkTrace, cp.chainLength, + cp.tolerance, jumpLog, monitor, startFrac, endFrac); + Map orderedNames = lo.convertOrderToMap(bfn, ordered); + return (orderedNames); + } + + /*************************************************************************** + ** + ** Common save activities + */ + void saveToOutputStream(OutputStream stream) throws IOException { + PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"))); + Indenter ind = new Indenter(out, Indenter.DEFAULT_INDENT); + BioFabricNetwork bfn = bfp_.getNetwork(); + bfn.writeXML(out, ind); + out.close(); + return; + } /*************************************************************************** ** - ** Never instantiate + ** Displays file reading error message */ + + public void displayFileInputError(IOException ioex) { + ResourceManager rMan = ResourceManager.getManager(); - private FabricCommands() { - // Never instantiate - throw new UnsupportedOperationException(); + if ((ioex == null) || (ioex.getMessage() == null) || (ioex.getMessage().trim().equals(""))) { + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("fileRead.errorMessage"), + rMan.getString("fileRead.errorTitle"), + JOptionPane.ERROR_MESSAGE); + return; + } + String errMsg = ioex.getMessage().trim(); + String format = rMan.getString("fileRead.inputErrorMessageForIOEx"); + String outMsg = MessageFormat.format(format, new Object[] {errMsg}); + JOptionPane.showMessageDialog(topWindow_, outMsg, + rMan.getString("fileRead.errorTitle"), + JOptionPane.ERROR_MESSAGE); + return; + } + + /*************************************************************************** + ** + ** Displays file writing error message + */ + + void displayFileOutputError() { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("fileWrite.errorMessage"), + rMan.getString("fileWrite.errorTitle"), + JOptionPane.ERROR_MESSAGE); + return; + } + + /*************************************************************************** + ** + ** Displays file reading error message for invalid input + */ + + public void displayInvalidInputError(InvalidInputException iiex) { + ResourceManager rMan = ResourceManager.getManager(); + String errKey = iiex.getErrorKey(); + boolean haveKey = (errKey != null) && (!errKey.equals(InvalidInputException.UNSPECIFIED_ERROR)); + int lineno = iiex.getErrorLineNumber(); + boolean haveLine = (lineno != InvalidInputException.UNSPECIFIED_LINE); + String outMsg; + if (haveKey && haveLine) { + String format = rMan.getString("fileRead.inputErrorMessageForLineWithDesc"); + String keyedErr = rMan.getString("invalidInput." + errKey); + outMsg = MessageFormat.format(format, new Object[] {new Integer(lineno + 1), keyedErr}); + } else if (haveKey && !haveLine) { + String format = rMan.getString("fileRead.inputErrorMessageWithDesc"); + String keyedErr = rMan.getString("invalidInput." + errKey); + outMsg = MessageFormat.format(format, new Object[] {keyedErr}); + } else if (!haveKey && haveLine) { + String format = rMan.getString("fileRead.inputErrorMessageForLine"); + outMsg = MessageFormat.format(format, new Object[] {new Integer(lineno + 1)}); + } else { + outMsg = rMan.getString("fileRead.inputErrorMessage"); + } + JOptionPane.showMessageDialog(topWindow_, outMsg, + rMan.getString("fileRead.errorTitle"), + JOptionPane.ERROR_MESSAGE); + return; + } + + /*************************************************************************** + ** + ** Set the fabric panel + */ + + public void setFabricPanel(BioFabricPanel bfp) { + bfp_ = bfp; + return; + } + + /*************************************************************************** + ** + ** Tell us the zoom state has changed + */ + + public void zoomStateChanged(boolean scrollOnly) { + if (!scrollOnly) { + handleZoomButtons(); + } + topWindow_.getOverview().setViewInWorld(bfp_.getViewInWorld()); + return; + } + + /*************************************************************************** + ** + ** Handle zoom buttons + */ + + private void handleZoomButtons() { + // + // Enable/disable zoom actions based on zoom limits: + // + + InOutZoomAction zaOutWI = (InOutZoomAction)withIcons_.get(new Integer(ZOOM_OUT)); + InOutZoomAction zaOutNI = (InOutZoomAction)noIcons_.get(new Integer(ZOOM_OUT)); + InOutZoomAction zaInWI = (InOutZoomAction)withIcons_.get(new Integer(ZOOM_IN)); + InOutZoomAction zaInNI = (InOutZoomAction)noIcons_.get(new Integer(ZOOM_IN)); + // In this case, we do not want to allow a "wide" zoom, since we do not have + // a buffered image to handle it! Restrict to first defined zoom! + if (bfp_.getZoomController().zoomIsFirstDefined()) { + zaOutWI.setConditionalEnabled(false); + if (zaOutNI != null) zaOutNI.setConditionalEnabled(false); + zaInWI.setConditionalEnabled(true); + if (zaInNI != null) zaInNI.setConditionalEnabled(true); + } else if (bfp_.getZoomController().zoomIsMax()) { + zaOutWI.setConditionalEnabled(true); + if (zaOutNI != null) zaOutNI.setConditionalEnabled(true); + zaInWI.setConditionalEnabled(false); + if (zaInNI != null) zaInNI.setConditionalEnabled(false); + } else { + zaOutWI.setConditionalEnabled(true); + if (zaOutNI != null) zaOutNI.setConditionalEnabled(true); + zaInWI.setConditionalEnabled(true); + if (zaInNI != null) zaInNI.setConditionalEnabled(true); + } + return; + } + + /*************************************************************************** + ** + ** Gaggle setup + */ + + public void setGaggleElements(JMenu gaggleGooseChooseMenu, JComboBox gaggleGooseCombo) { + // + // Controls for Gaggle: + // + if ((gaggleGooseChooseMenu != null) && (gaggleGooseCombo != null)) { + gaggleGooseChooseMenu_ = gaggleGooseChooseMenu; + gaggleGooseCombo_ = gaggleGooseCombo; + gaggleGooseCombo_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + if (managingGaggleControls_) { + return; + } + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + ObjChoiceContent occ = (ObjChoiceContent)gaggleGooseCombo_.getSelectedItem(); + goose.setCurrentGaggleTarget((occ == null) ? null : occ.val); + setCurrentGaggleTarget(gaggleGooseCombo_.getSelectedIndex()); + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + }); + } + return; } + + /*************************************************************************** + ** + ** Preferences are stored by package. + */ + + public void setPreference(String key, String val) { + Preferences prefs = Preferences.userNodeForPackage(FabricCommands.class); + prefs.put(key, val); + return; + } + + /*************************************************************************** + ** + ** Preferences are stored by package. + */ + + public String getPreference(String key) { + Preferences prefs = Preferences.userNodeForPackage(FabricCommands.class); + String retval = prefs.get(key, null); + return (retval); + } + + /*************************************************************************** + ** + ** Set the current file + */ + + public void setCurrentXMLFile(File file) { + currentFile_ = file; + if (currentFile_ == null) { + return; + } + setPreference("LoadDirectory", file.getAbsoluteFile().getParent()); + return; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC STATIC METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Get the commands for the given tag + */ + + public static synchronized FabricCommands getCmds(String className) { + if (perClass_ == null) { + throw new IllegalStateException(); + } + FabricCommands fc = (FabricCommands)perClass_.get(className); + if (fc == null) { + throw new IllegalStateException(); + } + return (fc); + } + + /*************************************************************************** + ** + ** Init the commands for the given tag + */ + + public static synchronized FabricCommands initCmds(String className, BioFabricApplication bfa, + BioFabricWindow topWindow, boolean isForMain) { + if (perClass_ == null) { + perClass_ = new HashMap(); + } + FabricCommands fc = (FabricCommands)perClass_.get(className); + if (fc != null) { + throw new IllegalStateException(); + } + fc = new FabricCommands(bfa, topWindow, isForMain); + perClass_.put(className, fc); + return (fc); + } + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Constructor + */ + + private FabricCommands(BioFabricApplication bfa, BioFabricWindow topWindow, boolean isMain) { + bfa_ = bfa; + topWindow_ = topWindow; + withIcons_ = new HashMap(); + noIcons_ = new HashMap(); + colGen_ = new FabricColorGenerator(); + colGen_.newColorModel(); + isForMain_ = isMain; + isAMac_ = System.getProperty("os.name").toLowerCase().startsWith("mac os x"); + FabricDisplayOptionsManager.getMgr().addTracker(this); + EventManager mgr = EventManager.getManager(); + mgr.addSelectionChangeListener(this); + } + + //////////////////////////////////////////////////////////////////////////// + // + // INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Checks if it is enabled or not + */ + + public abstract class ChecksForEnabled extends AbstractAction { + + protected static final int IGNORE = -1; + protected static final int DISABLED = 0; + protected static final int ENABLED = 1; + + protected boolean enabled_ = true; + protected boolean pushed_ = false; + + public void checkIfEnabled() { + enabled_ = checkGuts(); + if (!pushed_) { + this.setEnabled(enabled_); + } + return; + } + + public void pushDisabled(int pushCondition) { + pushed_ = canPush(pushCondition); + boolean reversed = reversePush(pushCondition); + if (pushed_) { + this.setEnabled(reversed); + } + } + + public void setConditionalEnabled(boolean enabled) { + // + // If we are pushed, just stash the value. If not + // pushed, stash and apply. + // + enabled_ = enabled; + if (!pushed_) { + this.setEnabled(enabled_); + } + } + + public boolean isPushed() { + return (pushed_); + } + + public void popDisabled() { + if (pushed_) { + this.setEnabled(enabled_); + pushed_ = false; + } + return; + } + + // Default can always be enabled: + protected boolean checkGuts() { + return (true); + } + + // Default can always be pushed: + protected boolean canPush(int pushCondition) { + return (true); + } + + // Signals we are reverse pushed (enabled when others disabled) + protected boolean reversePush(int pushCondition) { + return (false); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class PropagateDownAction extends ChecksForEnabled { + + PropagateDownAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.PropagateDown")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.PropagateDown")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/PropagateSelected24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.PropagateDownMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.selectionsToSubmodel(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.haveASelection()); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class ZoomToSelected extends ChecksForEnabled { + + ZoomToSelected(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.ZoomToSelected")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToSelected")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/ZoomToAllFabricSelected24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.ZoomToSelectedMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.getZoomController().zoomToSelected(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.haveASelection()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ZoomToModelAction extends ChecksForEnabled { + + ZoomToModelAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.ZoomToModel")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToModel")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/ZoomToAllFabric24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.ZoomToModelMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.getZoomController().zoomToModel(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ZoomToCurrentSelected extends ChecksForEnabled { + + ZoomToCurrentSelected(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.ZoomToCurrentSelected")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToCurrentSelected")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/ZoomToFabricSelected24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.ZoomToCurrentSelectedMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.getZoomController().zoomToCurrentSelected(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.haveASelection()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ZoomToCurrentMouse extends ChecksForEnabled { + + ZoomToCurrentMouse(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.ZoomToCurrentMouse")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToCurrentMouse")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.ZoomToCurrentMouseMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + char accel = rMan.getChar("command.ZoomToCurrentMouseAccel"); + putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricMagnifyingTool fmt = bfp_.getMagnifier(); + Point2D pt = fmt.getMouseLoc(); + Point rcPoint = bfp_.worldToRowCol(pt); + Rectangle rect = bfp_.buildFocusBox(rcPoint); + bfp_.getZoomController().zoomToRect(rect); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ZoomToCurrentMagnify extends ChecksForEnabled { + + ZoomToCurrentMagnify(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.ZoomToCurrentMagnify")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToCurrentMagnify")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/ZoomToFabricSelected24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.ZoomToCurrentMagnifyMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + char accel = rMan.getChar("command.ZoomToCurrentMagnifyAccel"); + putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricMagnifyingTool fmt = bfp_.getMagnifier(); + Rectangle rect = fmt.getClipRect(); + bfp_.getZoomController().zoomToRect(rect); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class CenterOnNextSelected extends ChecksForEnabled { + + CenterOnNextSelected(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.CenterOnNextSelected")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.CenterOnNextSelected")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/Forward24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.CenterOnNextSelectedMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.getZoomController().centerToNextSelected(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.haveASelection()); + } + } + + + /*************************************************************************** + ** + ** Command + */ + + private class CenterOnPreviousSelected extends ChecksForEnabled { + + CenterOnPreviousSelected(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.CenterOnPreviousSelected")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.CenterOnPreviousSelected")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/Back24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.CenterOnPreviousSelectedMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.getZoomController().centerToPreviousSelected(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.haveASelection()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class AddFirstNeighborsAction extends ChecksForEnabled { + + AddFirstNeighborsAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.AddFirstNeighbors")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.AddFirstNeighbors")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/PlusOneDeg24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.AddFirstNeighborsMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.addFirstNeighbors(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.haveASelection()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class BuildSelectAction extends ChecksForEnabled { + + BuildSelectAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.BuildSelect")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.BuildSelect")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.BuildSelectMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.toggleBuildSelect(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class InOutZoomAction extends ChecksForEnabled { + + private char sign_; + + InOutZoomAction(boolean doIcon, char sign) { + sign_ = sign; + ResourceManager rMan = ResourceManager.getManager(); + String iconName; + String stringName; + String mnemName; + String accelName; + if (sign == '+') { + iconName = "ZoomIn24.gif"; + stringName = "command.ZoomIn"; + mnemName = "command.ZoomInMnem"; + accelName = "command.ZoomInAccel"; + } else { + iconName = "ZoomOut24.gif"; + stringName = "command.ZoomOut"; + mnemName = "command.ZoomOutMnem"; + accelName = "command.ZoomOutAccel"; + } + putValue(Action.NAME, rMan.getString(stringName)); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString(stringName)); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/" + iconName); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar(mnemName); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + char accel = rMan.getChar(accelName); + putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.getZoomController().bumpZoomWrapper(sign_); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public void setConditionalEnabled(boolean enabled) { + setEnabled(enabled); + return; + } + + // + // Override: We handle this internally. + // + public void checkIfEnabled() { + } + + protected boolean canPush(int pushCondition) { + return ((pushCondition & FabricCommands.ALLOW_NAV_PUSH) == 0x00); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class ClearSelectionsAction extends ChecksForEnabled { + + ClearSelectionsAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.ClearSel")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ClearSel")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/ClearFabricSelected24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.ClearSelMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.clearSelections(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.haveASelection()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ZoomToRect extends ChecksForEnabled { + + ZoomToRect(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.ZoomToRect")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.ZoomToRect")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/ZoomToFabricRect24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.ZoomToRectMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + char accel = rMan.getChar("command.ZoomToRectAccel"); + putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); + } + + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.setToCollectZoomRect(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class CancelAction extends ChecksForEnabled { + + CancelAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.CancelAddMode")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.CancelAddMode")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/Stop24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.CancelAddModeMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfp_.cancelModals(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (false); + } + + protected boolean reversePush(int pushCondition) { + return ((pushCondition & FabricCommands.ALLOW_NAV_PUSH) != 0x00); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class SearchAction extends ChecksForEnabled { + + SearchAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.Search")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.Search")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/Find24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.SearchMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + boolean haveSelection = bfp_.haveASelection(); + boolean buildingSels = bfp_.amBuildingSelections(); + FabricSearchDialog fsd = new FabricSearchDialog(topWindow_, topWindow_.getFabricPanel().getNetwork(), + haveSelection, buildingSels); + fsd.setVisible(true); + if (fsd.itemWasFound()) { + Set matches = fsd.getMatches(); + boolean doDiscard = fsd.discardSelections(); + topWindow_.getFabricPanel().installSearchResult(matches, doDiscard); + } + return; + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class CompareNodesAction extends ChecksForEnabled { + + CompareNodesAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.CompareNodes")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.CompareNodes")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.CompareNodesMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + Set allNodes = bfp_.getNetwork().getNodeSet(); + CompareNodesSetupDialog fsd = new CompareNodesSetupDialog(topWindow_, allNodes); + fsd.setVisible(true); + if (fsd.haveResult()) { + Set result = fsd.getResults(); + bfp_.installSearchResult(result, true); + bfp_.addFirstNeighbors(); + bfp_.selectionsToSubmodel(); + } + return; + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class CloseAction extends ChecksForEnabled { + + CloseAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.Close")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.Close")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/Stop24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.CloseMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + bfa_.shutdownFabric(); + } catch (Exception ex) { + // Going down (usually) so don't show exception in UI + ex.printStackTrace(); + } + } + } + + /*************************************************************************** + ** + ** Command + */ + + private abstract class LayoutViaAttributesAction extends ChecksForEnabled { + + LayoutViaAttributesAction(boolean doIcon, String name, String mnemStr) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString(name)); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString(name)); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar(mnemStr); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected abstract boolean performOperation(); + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class LayoutNodesViaAttributesAction extends LayoutViaAttributesAction { + + LayoutNodesViaAttributesAction(boolean doIcon) { + super(doIcon, "command.LayoutNodesViaAttributes", "command.LayoutNodesViaAttributesMnem"); + } + + protected boolean performOperation() { + File file = getTheFile(".noa", ".na", "AttribDirectory", "filterName.noa"); + if (file == null) { + return (true); + } + Map nodeAttributes = loadTheFile(file, true); + if (nodeAttributes == null) { + return (true); + } + if (!bfp_.getNetwork().checkNewNodeOrder(nodeAttributes)) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, rMan.getString("attribRead.badRowMessage"), + rMan.getString("attribRead.badRowSemanticsTitle"), + JOptionPane.WARNING_MESSAGE); + return (true); + } + BioFabricNetwork.RelayoutBuildData bfn = + new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.NODE_ATTRIB_LAYOUT); + bfn.setNodeOrder(nodeAttributes); + NetworkRelayout nb = new NetworkRelayout(); + nb.doNetworkRelayout(bfn, null); + return (true); + } + + protected boolean checkGuts() { + return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class LayoutLinksViaAttributesAction extends LayoutViaAttributesAction { + + LayoutLinksViaAttributesAction(boolean doIcon) { + super(doIcon, "command.LayoutLinksViaAttributes", "command.LayoutLinksViaAttributesMnem"); + } + + protected boolean performOperation() { + File file = getTheFile(".eda", ".ed", "AttribDirectory", "filterName.eda"); + if (file == null) { + return (true); + } + Map edgeAttributes = loadTheFile(file, false); + if (edgeAttributes == null) { + return (true); + } + SortedMap modifiedAndChecked = bfp_.getNetwork().checkNewLinkOrder(edgeAttributes); + if (modifiedAndChecked == null) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, rMan.getString("attribRead.badColMessage"), + rMan.getString("attribRead.badColSemanticsTitle"), + JOptionPane.WARNING_MESSAGE); + return (true); + } + BioFabricNetwork.RelayoutBuildData bfn = + new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.LINK_ATTRIB_LAYOUT); + bfn.setLinkOrder(modifiedAndChecked); + NetworkRelayout nb = new NetworkRelayout(); + nb.doNetworkRelayout(bfn, null); + return (true); + } + + protected boolean checkGuts() { + return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class DefaultLayoutAction extends ChecksForEnabled { + + DefaultLayoutAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.DefaultLayout")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.DefaultLayout")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.DefaultLayoutMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + DefaultLayoutAction() { + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + private boolean performOperation(Object[] args) { + + BioFabricNetwork.RelayoutBuildData bfn = + new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.DEFAULT_LAYOUT); + NetworkRelayout nb = new NetworkRelayout(); + nb.doNetworkRelayout(bfn, null); + return (true); + } + + protected boolean checkGuts() { + return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class LayoutViaConnectivityAction extends ChecksForEnabled { + + LayoutViaConnectivityAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.LayoutViaConnectivity")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LayoutViaConnectivity")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.LayoutViaConnectivityMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + LayoutViaConnectivityAction() { + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + private boolean performOperation(Object[] args) { + + ClusteredLayoutParamsDialog clpd = + new ClusteredLayoutParamsDialog(topWindow_, new ClusteredLayout.ClusterParams()); + + clpd.show(); + if (!clpd.haveResult()) { + return (false); + } + + ClusteredLayout.ClusterParams result = clpd.getParams(); + + BioFabricNetwork.RelayoutBuildData bfn = + new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.CLUSTERED_LAYOUT); + NetworkRelayout nb = new NetworkRelayout(); + nb.doNetworkRelayout(bfn, result); + return (true); + } + + protected boolean checkGuts() { + return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class LayoutViaShapeMatchAction extends ChecksForEnabled { + + LayoutViaShapeMatchAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.LayoutViaShapeMatch")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LayoutViaShapeMatch")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.LayoutViaShapeMatchMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + LayoutViaShapeMatchAction() { + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + private boolean performOperation(Object[] args) { + + ReorderLayoutParamsDialog clpd = + new ReorderLayoutParamsDialog(topWindow_, new ClusteredLayout.ResortParams()); + + clpd.show(); + if (!clpd.haveResult()) { + return (false); + } + + ClusteredLayout.ResortParams result = clpd.getParams(); + + BioFabricNetwork.RelayoutBuildData bfn = + new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.REORDER_LAYOUT); + NetworkRelayout nb = new NetworkRelayout(); + nb.doNetworkRelayout(bfn, result); + return (true); + } + + protected boolean checkGuts() { + return (bfp_.hasAModel() && (bfp_.getNetwork().getLinkCount(true) != 0)); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class SetLinkGroupsAction extends ChecksForEnabled { + + SetLinkGroupsAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.SetLinkGroups")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.SetLinkGroups")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.SetLinkGroupsMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + SetLinkGroupsAction() { + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + private boolean performOperation(Object[] args) { + + BioFabricNetwork bfn = bfp_.getNetwork(); + List currentTags = bfn.getLinkGroups(); + ArrayList links = new ArrayList(bfn.getAllLinks(true)); + Set allRelations = BioFabricNetwork.extractRelations(links).keySet(); + LinkGroupingSetupDialog lgsd = new LinkGroupingSetupDialog(topWindow_, currentTags, allRelations); + lgsd.show(); + if (!lgsd.haveResult()) { + return (false); + } + + List newGroupings = lgsd.getGroups(); + if (newGroupings.equals(currentTags)) { + return (true); + } + + BioFabricNetwork.RelayoutBuildData bfnd = + new BioFabricNetwork.RelayoutBuildData(bfp_.getNetwork(), BioFabricNetwork.LINK_GROUP_CHANGE); + bfnd.setLinkGroups(newGroupings); + NetworkRelayout nb = new NetworkRelayout(); + nb.doNetworkRelayout(bfnd, null); + return (true); + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ImportSIFAction extends ChecksForEnabled { + + ImportSIFAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.LoadSIF")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LoadSIF")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.LoadSIFMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + ImportSIFAction() { + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + private boolean performOperation(Object[] args) { + + File file = null; + String filename = getPreference("LoadDirectory"); + while (file == null) { + JFileChooser chooser = new JFileChooser(); + chooser.addChoosableFileFilter(new FileExtensionFilters.SimpleFilter(".sif", "filterName.sif")); + if (filename != null) { + File startDir = new File(filename); + if (startDir.exists()) { + chooser.setCurrentDirectory(startDir); + } + } + + int option = chooser.showOpenDialog(topWindow_); + if (option != JFileChooser.APPROVE_OPTION) { + return (true); + } + file = chooser.getSelectedFile(); + if (file == null) { + return (true); + } + if (!standardFileChecks(file, FILE_MUST_EXIST, FILE_CAN_CREATE_DONT_CARE, + FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE_DONT_CARE, FILE_CAN_READ)) { + file = null; + continue; + } + } + return (loadFromSifSource(file, null)); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class LoadXMLAction extends ChecksForEnabled { + + LoadXMLAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.LoadXML")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LoadXML")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.LoadXMLMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + char accel = rMan.getChar("command.LoadXMLAccel"); + putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); + } + + LoadXMLAction() { + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + private boolean performOperation(Object[] args) { + + File file = null; + String filename = getPreference("LoadDirectory"); + while (file == null) { + JFileChooser chooser = new JFileChooser(); + chooser.addChoosableFileFilter(new FileExtensionFilters.SimpleFilter(".bif", "filterName.bif")); + if (filename != null) { + File startDir = new File(filename); + if (startDir.exists()) { + chooser.setCurrentDirectory(startDir); + } + } + + int option = chooser.showOpenDialog(topWindow_); + if (option != JFileChooser.APPROVE_OPTION) { + return (true); + } + file = chooser.getSelectedFile(); + if (file == null) { + return (true); + } + if (!standardFileChecks(file, FILE_MUST_EXIST, FILE_CAN_CREATE_DONT_CARE, + FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE_DONT_CARE, FILE_CAN_READ)) { + file = null; + continue; + } + } + return (loadXMLFromSource(file)); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class LoadWithNodeAttributesAction extends ChecksForEnabled { + + LoadWithNodeAttributesAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.LoadSIFWithNodeAttributes")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.LoadSIFWithNodeAttributes")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.LoadSIFWithNodeAttributesMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + LoadWithNodeAttributesAction() { + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + private boolean performOperation(Object[] args) { + File file = null; + String filename = getPreference("LoadDirectory"); + while (file == null) { + JFileChooser chooser = new JFileChooser(); + chooser.addChoosableFileFilter(new FileExtensionFilters.SimpleFilter(".sif", "filterName.sif")); + if (filename != null) { + File startDir = new File(filename); + if (startDir.exists()) { + chooser.setCurrentDirectory(startDir); + } + } + + int option = chooser.showOpenDialog(topWindow_); + if (option != JFileChooser.APPROVE_OPTION) { + return (true); + } + file = chooser.getSelectedFile(); + if (file == null) { + return (true); + } + if (!standardFileChecks(file, FILE_MUST_EXIST, FILE_CAN_CREATE_DONT_CARE, + FILE_DONT_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE_DONT_CARE, FILE_CAN_READ)) { + file = null; + continue; + } + } + + File attribFile = getTheFile(".noa", ".na", "AttribDirectory", "filterName.noa"); + if (attribFile == null) { + return (true); + } + + Map attribs = loadTheFile(attribFile, true); + if (attribs == null) { + return (true); + } + + return (loadFromSifSource(file, attribs)); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class SaveAsAction extends ChecksForEnabled { + + SaveAsAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.SaveAs")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.SaveAs")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/SaveAs24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.SaveAsMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + SaveAsAction() { + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public boolean performOperation(Object[] args) { + if (args == null) { + return (saveToFile(null)); + } else { + if (((Boolean)args[0]).booleanValue()) { + String fileName = (String)args[1]; + return (saveToFile(fileName)); + } else { + OutputStream stream = (OutputStream)args[1]; + try { + saveToOutputStream(stream); + } catch (IOException ioe) { + displayFileOutputError(); // Which is kinda bogus... + return (false); + } + return (true); + } + } + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class SaveAction extends ChecksForEnabled { + + SaveAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.Save")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.Save")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/Save24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.SaveMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + char accel = rMan.getChar("command.SaveAccel"); + putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); + } + + public void actionPerformed(ActionEvent e) { + try { + if (currentFile_ != null) { + saveToFile(currentFile_.getAbsolutePath()); + } else { + saveToFile(null); + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private abstract class ExportOrderAction extends ChecksForEnabled { + + ExportOrderAction(boolean doIcon, String name, String mnemStr) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString(name)); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString(name)); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar(mnemStr); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected abstract FileFilter getFilter(); + protected abstract List getSuffixList(); + protected abstract String getPrefSuffix(); + protected abstract void writeItOut(File file) throws IOException; + + public boolean performOperation(Object[] args) { + File file = null; + String dirName = getPreference("AttribDirectory"); + while (file == null) { + JFileChooser chooser = new JFileChooser(); + chooser.addChoosableFileFilter(getFilter()); + if (dirName != null) { + File startDir = new File(dirName); + if (startDir.exists()) { + chooser.setCurrentDirectory(startDir); + } + } + int option = chooser.showSaveDialog(topWindow_); + if (option != JFileChooser.APPROVE_OPTION) { + return (true); + } + file = chooser.getSelectedFile(); + if (file != null) { + if (!file.exists()) { + List cand = getSuffixList(); + if (!FileExtensionFilters.hasASuffix(file.getName(), "", cand)) { + file = new File(file.getAbsolutePath() + getPrefSuffix()); + } + } + if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, + FILE_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { + file = null; + continue; + } + } + } + + try { + writeItOut(file); + } catch (IOException ioe) { + displayFileOutputError(); + return (false); + } + setPreference("AttribDirectory", file.getAbsoluteFile().getParent()); + return (true); + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class ExportNodeOrderAction extends ExportOrderAction { + + ExportNodeOrderAction(boolean doIcon) { + super(doIcon, "command.ExportNodeOrder", "command.ExportNodeOrderMnem"); + } + + protected FileFilter getFilter() { + return (new FileExtensionFilters.DoubleExtensionFilter(".noa", ".na", "filterName.noa")); + } + + protected List getSuffixList() { + ArrayList cand = new ArrayList(); + cand.add(".noa"); + cand.add(".na"); + return (cand); + } + + protected String getPrefSuffix() { + return (".noa"); + } + + protected void writeItOut(File file) throws IOException { + PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))); + bfp_.getNetwork().writeNOA(out); + out.close(); + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ExportLinkOrderAction extends ExportOrderAction { + + + ExportLinkOrderAction(boolean doIcon) { + super(doIcon, "command.ExportLinkOrder", "command.ExportLinkOrderMnem"); + } + + protected FileFilter getFilter() { + return (new FileExtensionFilters.DoubleExtensionFilter(".eda", ".ea", "filterName.eda")); + } + + protected List getSuffixList() { + ArrayList cand = new ArrayList(); + cand.add(".eda"); + cand.add(".ea"); + return (cand); + } + + protected String getPrefSuffix() { + return (".eda"); + } + + protected void writeItOut(File file) throws IOException { + PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))); + bfp_.getNetwork().writeEDA(out); + out.close(); + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ExportSelectedNodesAction extends ExportOrderAction { + + + ExportSelectedNodesAction(boolean doIcon) { + super(doIcon, "command.ExportSelectedNodes", "command.ExportSelectedNodesMnem"); + } + + protected FileFilter getFilter() { + return (new FileExtensionFilters.SimpleFilter(".txt", "filterName.txt")); + } + + protected List getSuffixList() { + ArrayList cand = new ArrayList(); + cand.add(".txt"); + return (cand); + } + + protected String getPrefSuffix() { + return (".txt"); + } + + protected void writeItOut(File file) throws IOException { + PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))); + Set sels = bfp_.getNodeSelections(); + Iterator sit = sels.iterator(); + while (sit.hasNext()) { + String node = (String)sit.next(); + out.println(node); + } + out.close(); + return; + } + + protected boolean checkGuts() { + return (super.checkGuts() && !bfp_.getNodeSelections().isEmpty()); + } + + } + + /*************************************************************************** + ** + ** Command + */ + + private class PrintAction extends ChecksForEnabled { + + PrintAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.Print")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.Print")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/Print24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.PrintMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + char accel = rMan.getChar("command.PrintAccel"); + putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(accel, Event.CTRL_MASK, false)); + } + + public void actionPerformed(ActionEvent e) { + try { + PrinterJob pj = PrinterJob.getPrinterJob(); + PageFormat pf = pj.defaultPage(); + pf.setOrientation(PageFormat.LANDSCAPE); + // FIX ME: Needed for Win32? Linux won't default to landscape without this? + //PageFormat pf2 = pj.pageDialog(pf); + pj.setPrintable(bfp_, pf); + if (pj.printDialog()) { + try { + pj.print(); + } catch (PrinterException pex) { + System.err.println(pex); + } + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + } + + + /*************************************************************************** + ** + ** Command + */ + + private abstract class ExportImageAction extends ChecksForEnabled { + + ExportImageAction(boolean doIcon, String res, String mnemStr) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString(res)); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString(res)); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar(mnemStr); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + performOperation(null); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected abstract ExportSettingsDialog.ExportSettings getExportSettings(); + + + public boolean performOperation(Object[] args) { + + ExportSettingsDialog.ExportSettings set; + if (args == null) { + set = getExportSettings(); + if (set == null) { + return (true); + } + } else { + set = (ExportSettingsDialog.ExportSettings)args[0]; + } + + File file = null; + OutputStream stream = null; + + if (args == null) { // not headless... + List supported = ImageExporter.getSupportedFileSuffixes(); + String filename = getPreference("ExportDirectory"); + while (file == null) { + JFileChooser chooser = new JFileChooser(); + chooser.addChoosableFileFilter(new FileExtensionFilters.MultiExtensionFilter(supported, "filterName.img")); + if (filename != null) { + File startDir = new File(filename); + if (startDir.exists()) { + chooser.setCurrentDirectory(startDir); + } + } + + int option = chooser.showSaveDialog(topWindow_); + if (option != JFileChooser.APPROVE_OPTION) { + return (true); + } + file = chooser.getSelectedFile(); + if (file == null) { + continue; + } + if (!file.exists()) { + List suffs = ImageExporter.getFileSuffixesForType(set.formatType); + if (!FileExtensionFilters.hasASuffix(file.getName(), "." , suffs)) { + file = new File(file.getAbsolutePath() + "." + + ImageExporter.getPreferredSuffixForType(set.formatType)); + } + } + if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, + FILE_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { + file = null; + continue; + } + } + } else { + if (((Boolean)args[1]).booleanValue()) { + file = new File((String)args[2]); + if (!standardFileChecks(file, FILE_MUST_EXIST_DONT_CARE, FILE_CAN_CREATE, + FILE_CHECK_OVERWRITE, FILE_MUST_BE_FILE, + FILE_CAN_WRITE, FILE_CAN_READ_DONT_CARE)) { + return (false); + } + } else { + stream = (OutputStream)args[2]; + } + } + + try { + if (file != null) { + bfp_.exportToFile(file, set.formatType, set.res, set.zoomVal, set.size); + } else { + bfp_.exportToStream(stream, set.formatType, set.res, set.zoomVal, set.size); + } + if (args == null) { + setPreference("ExportDirectory", file.getAbsoluteFile().getParent()); + } + } catch (IOException ioe) { + displayFileOutputError(); + return (false); + } + + return (true); + } + + protected boolean checkGuts() { + return (bfp_.hasAModel()); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class ExportSimpleAction extends ExportImageAction { + + ExportSimpleAction(boolean doIcon) { + super(doIcon, "command.Export", "command.ExportMnem"); + } + + protected ExportSettingsDialog.ExportSettings getExportSettings() { + Rectangle wr = bfp_.getWorldRect(); + ExportSettingsDialog esd = new ExportSettingsDialog(topWindow_, wr.width, wr.height); + esd.show(); + ExportSettingsDialog.ExportSettings set = esd.getResults(); + return (set); + } + } + + + /*************************************************************************** + ** + ** Command + */ + + private class ExportPublishAction extends ExportImageAction { + + ExportPublishAction(boolean doIcon) { + super(doIcon, "command.ExportPublish", "command.ExportPublishMnem"); + } + + protected ExportSettingsDialog.ExportSettings getExportSettings() { + Rectangle wr = bfp_.getWorldRect(); + ExportSettingsPublishDialog esd = new ExportSettingsPublishDialog(topWindow_, wr.width, wr.height); + esd.show(); + ExportSettingsDialog.ExportSettings set = esd.getResults(); + return (set); + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class EmptyNetworkAction extends ChecksForEnabled { + + EmptyNetworkAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.EmptyNet")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.EmptyNet")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.EmptyNetMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + manageWindowTitle(null); + BioFabricNetwork.OrigBuildData obd = new BioFabricNetwork.OrigBuildData(new HashSet(), new HashSet(), colGen_, BioFabricNetwork.BUILD_FROM_SIF); + newModelOperations(obd, true); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class SetDisplayOptionsAction extends ChecksForEnabled { + + SetDisplayOptionsAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.SetDisplayOpts")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.SetDisplayOpts")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/FIXME.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.SetDisplayOptsMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricDisplayOptionsDialog dod = new FabricDisplayOptionsDialog(topWindow_); + dod.setVisible(true); + if (dod.haveResult()) { + FabricDisplayOptionsManager dopmgr = FabricDisplayOptionsManager.getMgr(); + dopmgr.setDisplayOptions(dod.getNewOpts(), dod.needsRebuild(), dod.needsRecolor()); + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + public class SetCurrentGaggleTargetAction extends ChecksForEnabled { + + private String gooseName_; + private int gooseIndex_; + + public SetCurrentGaggleTargetAction(String gooseName, int gooseIndex) { + gooseName_ = gooseName; + gooseIndex_ = gooseIndex; + putValue(Action.NAME, gooseName); + } + + public void actionPerformed(ActionEvent e) { + try { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + goose.setCurrentGaggleTarget(gooseName_); + } + setCurrentGaggleTarget(gooseIndex_); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class GaggleUpdateGeese extends ChecksForEnabled { + + private ImageIcon standard_; + private ImageIcon inbound_; + + GaggleUpdateGeese(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.GaggleUpdateGeese")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.GaggleUpdateGeese")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/U24.gif"); + standard_ = new ImageIcon(ugif); + if (isAMac_) { + ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/U24Selected.gif"); + inbound_ = new ImageIcon(ugif); + } + putValue(Action.SMALL_ICON, standard_); + } else { + char mnem = rMan.getChar("command.GaggleUpdateGeeseMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + setButtonCondition(false); + updateGaggleTargetActions(); + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public void setButtonCondition(boolean activate) { + if (isAMac_) { + putValue(Action.SMALL_ICON, (activate) ? inbound_ : standard_); + gaggleUpdateGooseButton_.validate(); + } else { + gaggleUpdateGooseButton_.setBackground((activate) ? Color.orange : gaggleButtonOffColor_); + } + return; + } + } + + + /*************************************************************************** + ** + ** Command + */ + + private class GaggleRaiseGoose extends ChecksForEnabled { + + GaggleRaiseGoose(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.GaggleRaiseGoose")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.GaggleRaiseGoose")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/S24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.GaggleRaiseGooseMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + goose.raiseCurrentTarget(); + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class GaggleLowerGoose extends ChecksForEnabled { + + GaggleLowerGoose(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.GaggleLowerGoose")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.GaggleLowerGoose")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/H24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.GaggleLowerGooseMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + goose.hideCurrentTarget(); + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class GaggleSendNetwork extends ChecksForEnabled { + + GaggleSendNetwork(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.GaggleSendNetwork")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.GaggleSendNetwork")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/N24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.GaggleSendNetworkMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + SelectionSupport ss = goose.getSelectionSupport(); + SelectionSupport.NetworkForSpecies net = ss.getOutboundNetwork(); + if ((net == null) || net.getLinks().isEmpty()) { + return; + } + goose.transmitNetwork(net); + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class GaggleSendNameList extends ChecksForEnabled { + + GaggleSendNameList(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.GaggleSendNameList")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.GaggleSendNameList")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/L24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.GaggleSendNameListMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + goose.transmitSelections(); + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class GaggleProcessInbound extends ChecksForEnabled { + + private ImageIcon standard_; + private ImageIcon inbound_; + + GaggleProcessInbound(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.GaggleProcessInbound")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.GaggleProcessInbound")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/P24.gif"); + standard_ = new ImageIcon(ugif); + if (isAMac_) { + ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/P24Selected.gif"); + inbound_ = new ImageIcon(ugif); + } + putValue(Action.SMALL_ICON, standard_); + } else { + char mnem = rMan.getChar("command.GaggleProcessInboundMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + // Will be on background thread for awhile; don't lose incoming commands + //gaggleButton_.setBackground(gaggleButtonOffColor_); + setButtonCondition(false); + SelectionSupport ss = goose.getSelectionSupport(); + // Kinda hackish. First time in, set the targets when this button is pressed! + List targets = ss.getGooseList(); + int numTarg = targets.size(); + if (numTarg != gaggleGooseCombo_.getItemCount()) { + updateGaggleTargetActions(); + } + List pending = ss.getPendingCommands(); + Iterator pit = pending.iterator(); + while (pit.hasNext()) { + InboundGaggleOp op = (InboundGaggleOp)pit.next(); + op.executeOp(); + } + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public void setButtonCondition(boolean activate) { + if (isAMac_) { + putValue(Action.SMALL_ICON, (activate) ? inbound_ : standard_); + gaggleButton_.validate(); + } else { + gaggleButton_.setBackground((activate) ? Color.orange : gaggleButtonOffColor_); + } + return; + } + } + + /*************************************************************************** + ** + ** Command + */ + + private class GaggleConnect extends ChecksForEnabled { + + private boolean forConnect_; + + GaggleConnect(boolean doIcon, boolean forConnect) { + forConnect_ = forConnect; + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString((forConnect) ? "command.GaggleConnect" : "command.GaggleDisconnect")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString((forConnect) ? "command.GaggleConnect" + : "command.GaggleDisconnect")); + URL ugif = getClass().getResource((forConnect) ? "/org/systemsbiology/biotapestry/biofabric/images/C24.gif" : "/org/systemsbiology/biotapestry/biofabric/images/D24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar((forConnect) ? "command.GaggleConnectMnem" : "command.GaggleDisconnectMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + } + + public void actionPerformed(ActionEvent e) { + try { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + if (forConnect_) { + goose.connect(); + } else { + goose.disconnect(); + } + } + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + protected boolean checkGuts() { + FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + if ((goose != null) && goose.isActivated()) { + if (forConnect_) { + return (!goose.isConnected()); + } else { + return (goose.isConnected()); + } + } + return (false); + } + } + + /*************************************************************************** + ** + ** Command + */ + + public class AboutAction extends ChecksForEnabled { + + private URL aboutURL_; + private JEditorPane pane_; + private JFrame frame_; + private FixedJButton buttonB_; + private URL gnuUrl_; + private URL sunUrl_; + + AboutAction(boolean doIcon) { + ResourceManager rMan = ResourceManager.getManager(); + putValue(Action.NAME, rMan.getString("command.About")); + if (doIcon) { + putValue(Action.SHORT_DESCRIPTION, rMan.getString("command.About")); + URL ugif = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/images/About24.gif"); + putValue(Action.SMALL_ICON, new ImageIcon(ugif)); + } else { + char mnem = rMan.getChar("command.AboutMnem"); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); + } + aboutURL_ = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/license/about.html"); + } + + // + // Having an image link in the html turns out to be problematic + // starting Fall 2008 with URL security holes being plugged. So + // change the window. Note we use a back button now too! + + public void actionPerformed(ActionEvent e) { + try { + if (frame_ != null) { + frame_.setExtendedState(JFrame.NORMAL); + frame_.toFront(); + return; + } + try { + pane_ = new JEditorPane(aboutURL_); + } catch (IOException ioex) { + ExceptionHandler.getHandler().displayException(ioex); + return; + } + // 8/09: COMPLETELY BOGUS, but URLs are breaking everywhere in the latest JVMs, an I don't + // have time to fix this in a more elegant fashion! + gnuUrl_ = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/license/LICENSE"); + sunUrl_ = getClass().getResource("/org/systemsbiology/biotapestry/biofabric/license/LICENSE-SUN"); + ResourceManager rMan = ResourceManager.getManager(); + pane_.setEditable(false); + frame_ = new JFrame(rMan.getString("window.aboutTitle")); + pane_.addHyperlinkListener(new HyperlinkListener() { + public void hyperlinkUpdate(HyperlinkEvent ev) { + try { + if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + URL toUse = (ev.getDescription().indexOf("-SUN") != -1) ? sunUrl_ : gnuUrl_; + pane_.setPage(toUse); + buttonB_.setEnabled(true); + } + } catch (IOException ex) { + } + } + }); + frame_.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + frame_ = null; + e.getWindow().dispose(); + } + }); + + JPanel cp = (JPanel)frame_.getContentPane(); + cp.setBackground(Color.white); + cp.setBorder(new EmptyBorder(20, 20, 20, 20)); + cp.setLayout(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + // URL sugif = getClass().getResource( + // "/org/systemsbiology/biotapestry/images/BioTapestrySplash.gif"); + JLabel label = new JLabel(); //new ImageIcon(sugif)); + + UiUtil.gbcSet(gbc, 0, 0, 1, 3, UiUtil.BO, 0, 0, 5, 5, 5, 5, UiUtil.CEN, 1.0, 0.0); + cp.add(label, gbc); + + JScrollPane jsp = new JScrollPane(pane_); + UiUtil.gbcSet(gbc, 0, 3, 1, 2, UiUtil.BO, 0, 0, 5, 5, 5, 5, UiUtil.CEN, 1.0, 1.0); + cp.add(jsp, gbc); + + + buttonB_ = new FixedJButton(rMan.getString("dialogs.back")); + buttonB_.setEnabled(false); + buttonB_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + pane_.setPage(aboutURL_); + buttonB_.setEnabled(false); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + FixedJButton buttonC = new FixedJButton(rMan.getString("dialogs.close")); + buttonC.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + frame_.setVisible(false); + frame_.dispose(); + frame_ = null; + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + Box buttonPanel = Box.createHorizontalBox(); + buttonPanel.add(Box.createHorizontalGlue()); + buttonPanel.add(buttonB_); + buttonPanel.add(Box.createHorizontalStrut(10)); + buttonPanel.add(buttonC); + UiUtil.gbcSet(gbc, 0, 5, 1, 1, UiUtil.HOR, 0, 0, 5, 5, 5, 5, UiUtil.SE, 1.0, 0.0); + cp.add(buttonPanel, gbc); + frame_.setSize(700, 700); + frame_.setLocationRelativeTo(topWindow_); + frame_.setVisible(true); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + } + + /*************************************************************************** + ** + ** Class for building networks + */ + + public class NetworkBuilder implements BackgroundWorkerOwner { + + private BioFabricNetwork.PreBuiltBuildData restore_; + + public void doNetworkBuild(BioFabricNetwork.BuildData bfn, boolean isMain) { + try { + if (bfn.canRestore()) { + BioFabricNetwork net = bfp_.getNetwork(); + restore_ = new BioFabricNetwork.PreBuiltBuildData(net, BioFabricNetwork.BUILD_FROM_XML); + } else { + restore_ = null; + } + preLoadOperations(); + NewNetworkRunner runner = new NewNetworkRunner(bfn, isMain); + BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, + "netBuild.waitTitle", "netBuild.wait", null, false); + runner.setClient(bwc); + bwc.launchWorker(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public boolean handleRemoteException(Exception remoteEx) { + if (remoteEx instanceof IOException) { + finishedImport(null, (IOException)remoteEx); + return (true); + } + return (false); + } + + public void cleanUpPreEnable(Object result) { + return; + } + + public void handleCancellation() { + BioFabricNetwork.BuildData ubd; + if (restore_ != null) { + ubd = restore_; + } else { + ubd = new BioFabricNetwork.OrigBuildData(new HashSet(), new HashSet(), colGen_, BioFabricNetwork.BUILD_FROM_SIF); + } + try { + newModelOperations(ubd, true); + } catch (IOException ioex) { + //Silent fail + } + return; + } + + public void cleanUpPostRepaint(Object result) { + finishedImport(result, null); + return; + } + + private void finishedImport(Object result, IOException ioEx) { + if (ioEx != null) { + displayFileInputError(ioEx); + return; + } + // FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + // if ((goose != null) && goose.isActivated()) { + // SelectionSupport ss = goose.getSelectionSupport(); + // ss.setSpecies(species_); + // } + postLoadOperations((BufferedImage)result); + return; + } + } + + /*************************************************************************** + ** + ** Class for relayout of networks + */ + + public class NetworkRelayout implements BackgroundWorkerOwner { + + private BioFabricNetwork.PreBuiltBuildData restore_; + + public void doNetworkRelayout(BioFabricNetwork.RelayoutBuildData bfn, ClusteredLayout.CRParams result) { + if (bfn.canRestore()) { + BioFabricNetwork net = bfp_.getNetwork(); + restore_ = new BioFabricNetwork.PreBuiltBuildData(net, BioFabricNetwork.BUILD_FROM_XML); + } else { + restore_ = null; + } + + try { + preLoadOperations(); + NetworkRelayoutRunner runner = new NetworkRelayoutRunner(bfn, result); + BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, + "netRelayout.waitTitle", "netRelayout.wait", null, true); + if (bfn.getMode() == BioFabricNetwork.REORDER_LAYOUT) { + bwc.makeSuperChart(); + } + runner.setClient(bwc); + bwc.launchWorker(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public boolean handleRemoteException(Exception remoteEx) { + if (remoteEx instanceof IOException) { + finishedImport(null, (IOException)remoteEx); + return (true); + } + return (false); + } + + public void cleanUpPreEnable(Object result) { + return; + } + + public void handleCancellation() { + BioFabricNetwork.BuildData ubd; + if (restore_ != null) { + ubd = restore_; + } else { + ubd = new BioFabricNetwork.OrigBuildData(new HashSet(), new HashSet(), colGen_, BioFabricNetwork.BUILD_FROM_SIF); + } + try { + newModelOperations(ubd, true); + } catch (IOException ioex) { + //Silent fail + } + return; + } + + public void cleanUpPostRepaint(Object result) { + finishedImport(result, null); + return; + } + + private void finishedImport(Object result, IOException ioEx) { + if (ioEx != null) { + displayFileInputError(ioEx); + return; + } + // FabricGooseInterface goose = FabricGooseManager.getManager().getGoose(); + // if ((goose != null) && goose.isActivated()) { + // SelectionSupport ss = goose.getSelectionSupport(); + // ss.setSpecies(species_); + // } + postLoadOperations((BufferedImage)result); + return; + } + } + + /*************************************************************************** + ** + ** Class for loading huge files in + */ + + public class BackgroundFileReader implements BackgroundWorkerOwner { + + private FabricFactory ff_; + private Exception ex_; + + private File file_; + private List links_; + private Set loneNodes_; + private FabricSIFLoader.SIFStats sss_; + + public void doBackgroundSIFRead(File file, List links, Set loneNodes, Map nameMap, FabricSIFLoader.SIFStats sss) { + file_ = file; + links_ = links; + loneNodes_ = loneNodes; + sss_ = sss; + try { + SIFReaderRunner runner = new SIFReaderRunner(file, links, loneNodes, nameMap, sss); + BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, + "fileLoad.waitTitle", "fileLoad.wait", null, false); + runner.setClient(bwc); + bwc.launchWorker(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public void doBackgroundRead(FabricFactory ff, SUParser sup, File file) { + ff_ = ff; + file_ = file; + try { + ReaderRunner runner = new ReaderRunner(sup, file); + BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, + "fileLoad.waitTitle", "fileLoad.wait", null, false); + runner.setClient(bwc); + bwc.launchWorker(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public boolean handleRemoteException(Exception remoteEx) { + if (remoteEx instanceof IOException) { + ex_ = remoteEx; + return (true); + } + return (false); + } + + public void cleanUpPreEnable(Object result) { + return; + } + + public void handleCancellation() { + throw new UnsupportedOperationException(); + } + + public void cleanUpPostRepaint(Object result) { + finishedLoad(); + return; + } + + private void finishedLoad() { + if (ex_ != null) { + displayFileInputError((IOException)ex_); + return; + } + if (ff_ != null) { + setCurrentXMLFile(file_); + postXMLLoad(ff_, file_.getName()); + } else { + finishLoadFromSIFSource(file_, sss_, links_, loneNodes_); + } + return; + } + } + + /*************************************************************************** + ** + ** Class for writing huge files out + */ + + public class BackgroundFileWriter implements BackgroundWorkerOwner { + + private Exception ex_; + private File file_; + + public void doBackgroundWrite(File file) { + file_ = file; + try { + WriterRunner runner = new WriterRunner(file); + BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, + "fileWrite.waitTitle", "fileWrite.wait", null, false); + runner.setClient(bwc); + bwc.launchWorker(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public boolean handleRemoteException(Exception remoteEx) { + if (remoteEx instanceof IOException) { + ex_ = remoteEx; + return (true); + } + return (false); + } + + public void cleanUpPreEnable(Object result) { + return; + } + + public void handleCancellation() { + throw new UnsupportedOperationException(); + } + + public void cleanUpPostRepaint(Object result) { + finishedOut(); + return; + } + + private void finishedOut() { + if (ex_ != null) { + displayFileOutputError(); + return; + } + setCurrentXMLFile(file_); + manageWindowTitle(file_.getName()); + return; + } + } + + /*************************************************************************** + ** + ** Class for recoloring networks + */ + + public class NetworkRecolor implements BackgroundWorkerOwner { + + public void doNetworkRecolor(boolean isMain) { + try { + bfp_.shutdown(); + RecolorNetworkRunner runner = new RecolorNetworkRunner(isMain); + BackgroundWorkerClient bwc = new BackgroundWorkerClient(this, runner, topWindow_, topWindow_, + "netRecolor.waitTitle", "netRecolor.wait", null, false); + runner.setClient(bwc); + bwc.launchWorker(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + return; + } + + public boolean handleRemoteException(Exception remoteEx) { + if (remoteEx instanceof IOException) { + finishedRecolor(null, (IOException)remoteEx); + return (true); + } + return (false); + } + + public void cleanUpPreEnable(Object result) { + return; + } + + public void handleCancellation() { + // Not allowing cancellation! + return; + } + + public void cleanUpPostRepaint(Object result) { + finishedRecolor(result, null); + return; + } + + private void finishedRecolor(Object result, IOException ioEx) { + postRecolorOperations((BufferedImage)result); + return; + } + } + + /*************************************************************************** + ** + ** Background network import + */ + + private class NewNetworkRunner extends BackgroundWorker { + + private BioFabricNetwork.BuildData bfn_; + private boolean forMain_; + + public NewNetworkRunner(BioFabricNetwork.BuildData bfn, boolean forMain) { + super("Early Result"); + bfn_ = bfn; + forMain_ = forMain; + } + + public Object runCore() throws AsynchExitRequestException { + try { + BufferedImage bi = expensiveModelOperations(bfn_, forMain_); + return (bi); + } catch (IOException ex) { + stashException(ex); + return (null); + } + } + + public Object postRunCore() { + return (null); + } + } + + /*************************************************************************** + ** + ** Background network layout + */ + + private class NetworkRelayoutRunner extends BackgroundWorker { + + private BioFabricNetwork.RelayoutBuildData rbd_; + private int mode_; + private ClusteredLayout.CRParams params_; + + public NetworkRelayoutRunner(BioFabricNetwork.RelayoutBuildData rbd, ClusteredLayout.CRParams params) { + super("Early Result"); + rbd_ = rbd; + mode_ = rbd.getMode(); + params_ = params; + } + + public Object runCore() throws AsynchExitRequestException { + try { + switch (mode_) { + case BioFabricNetwork.DEFAULT_LAYOUT: + case BioFabricNetwork.NODE_ATTRIB_LAYOUT: + case BioFabricNetwork.LINK_ATTRIB_LAYOUT: + case BioFabricNetwork.LINK_GROUP_CHANGE: + // previously installed.... + break; + case BioFabricNetwork.REORDER_LAYOUT: + rbd_.setNodeOrder(doReorderLayout(rbd_.bfn, params_, this, 0.0, 1.0)); + break; + case BioFabricNetwork.CLUSTERED_LAYOUT: + rbd_.setNodeOrder(doClusteredLayout(rbd_.bfn, params_, this, 0.0, 1.0)); + break; + case BioFabricNetwork.SHADOW_LINK_CHANGE: + case BioFabricNetwork.BUILD_FOR_SUBMODEL: + case BioFabricNetwork.BUILD_FROM_XML: + case BioFabricNetwork.BUILD_FROM_SIF: + case BioFabricNetwork.BUILD_FROM_GAGGLE: + default: + throw new IllegalArgumentException(); + } + BufferedImage bi = expensiveModelOperations(rbd_, true); + return (bi); + } catch (IOException ex) { + stashException(ex); + return (null); + } + } + + public Object postRunCore() { + return (null); + } + } + + /*************************************************************************** + ** + ** Background network recolor + */ + + private class RecolorNetworkRunner extends BackgroundWorker { + + private boolean forMain_; + + public RecolorNetworkRunner(boolean forMain) { + super("Early Result"); + forMain_ = forMain; + } + + public Object runCore() throws AsynchExitRequestException { + try { + BufferedImage bi = expensiveRecolorOperations(forMain_); + return (bi); + } catch (IOException ex) { + stashException(ex); + return (null); + } + } + + public Object postRunCore() { + return (null); + } + } + + /*************************************************************************** + ** + ** Background file load + */ + + private class ReaderRunner extends BackgroundWorker { + + private File myFile_; + private SUParser myParser_; + + public ReaderRunner(SUParser sup, File file) { + super("Early Result"); + myFile_ = file; + myParser_ = sup; + } + public Object runCore() throws AsynchExitRequestException { + try { + myParser_.parse(myFile_); + return (new Boolean(true)); + } catch (IOException ioe) { + stashException(ioe); + return (null); + } + } + public Object postRunCore() { + return (null); + } + } + + /*************************************************************************** + ** + ** Background file load + */ + + private class SIFReaderRunner extends BackgroundWorker { + + private File myFile_; + private List links_; + private Set loneNodes_; + private Map nameMap_; + private FabricSIFLoader.SIFStats sss_; + + public SIFReaderRunner(File file, List links, Set loneNodes, Map nameMap, FabricSIFLoader.SIFStats sss) { + super("Early Result"); + myFile_ = file; + links_ = links; + loneNodes_ = loneNodes; + nameMap_ = nameMap; + sss_ = sss; + } + + public Object runCore() throws AsynchExitRequestException { + try { + FabricSIFLoader.SIFStats sss = (new FabricSIFLoader()).readSIF(myFile_, links_, loneNodes_, nameMap_); + sss_.copyInto(sss); + return (new Boolean(true)); + } catch (IOException ioe) { + stashException(ioe); + return (null); + } + } + public Object postRunCore() { + return (null); + } + } + + /*************************************************************************** + ** + ** Background file write + */ + + private class WriterRunner extends BackgroundWorker { + + private File myFile_; + + public WriterRunner(File file) { + super("Early Result"); + myFile_ = file; + } + public Object runCore() throws AsynchExitRequestException { + try { + saveToOutputStream(new FileOutputStream(myFile_)); + return (new Boolean(true)); + } catch (IOException ioe) { + stashException(ioe); + return (null); + } + } + public Object postRunCore() { + return (null); + } + } } diff --git a/src/org/systemsbiology/biofabric/ui/FabricDisplayOptions.java b/src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptions.java similarity index 72% rename from src/org/systemsbiology/biofabric/ui/FabricDisplayOptions.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptions.java index 5d4eaa5..502c6cd 100644 --- a/src/org/systemsbiology/biofabric/ui/FabricDisplayOptions.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptions.java @@ -17,18 +17,17 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.biofabric; import java.io.IOException; import java.io.PrintWriter; import org.xml.sax.Attributes; -import org.systemsbiology.biofabric.io.FabricFactory; -import org.systemsbiology.biofabric.parser.AbstractFactoryClient; -import org.systemsbiology.biofabric.util.AttributeExtractor; -import org.systemsbiology.biofabric.util.CharacterEntityMapper; -import org.systemsbiology.biofabric.util.Indenter; +import org.systemsbiology.biotapestry.parser.AbstractFactoryClient; +import org.systemsbiology.biotapestry.util.AttributeExtractor; +import org.systemsbiology.biotapestry.util.CharacterEntityMapper; +import org.systemsbiology.biotapestry.util.Indenter; /**************************************************************************** @@ -61,13 +60,9 @@ public class FabricDisplayOptions implements Cloneable { private static final double DEFAULT_LINK_DARKER_LEVEL_ = 0.43; private static final boolean DEFAULT_DISPLAY_SHADOWS_ = false; private static final boolean DEFAULT_SHADE_NODES_ = false; - private static final boolean DEFAULT_OFFER_NODE_BROWSER_ = false; - private static final boolean DEFAULT_OFFER_LINK_BROWSER_ = false; - private static final boolean DEFAULT_OFFER_MOUSEOVER_VIEW_ = false; private static final boolean DEFAULT_MINIMIZE_SHADOW_SUBMODEL_LINKS_ = true; private static final String DEFAULT_BROWSER_URL_ = "http://www.genecards.org/cgi-bin/carddisp.pl?gene=" + NODE_NAME_PLACEHOLDER; private static final String DEFAULT_LINK_BROWSER_URL_ = "http://localhost:8080/setToYourPage.jsp?src=" + LINK_SRC_PLACEHOLDER + "&rel=" + LINK_REL_PLACEHOLDER + "&trg=" + LINK_TRG_PLACEHOLDER; - private static final String DEFAULT_MOUSEOVER_URL_ = "/Users/bill/Desktop/ForBrains/" + NODE_NAME_PLACEHOLDER + ".jpg"; //////////////////////////////////////////////////////////////////////////// // @@ -81,12 +76,8 @@ public class FabricDisplayOptions implements Cloneable { private boolean displayShadows_; private boolean shadeNodes_; private boolean minShadSubLinks_; - private boolean offerNodeBrowser_; - private boolean offerLinkBrowser_; - private boolean offerMouseOverView_; private String browserURL_; private String browserLinkURL_; - private String mouseOverURL_; //////////////////////////////////////////////////////////////////////////// // @@ -108,11 +99,6 @@ public FabricDisplayOptions() { browserURL_ = DEFAULT_BROWSER_URL_; browserLinkURL_ = DEFAULT_LINK_BROWSER_URL_; minShadSubLinks_ = DEFAULT_MINIMIZE_SHADOW_SUBMODEL_LINKS_; - - offerNodeBrowser_ = DEFAULT_OFFER_NODE_BROWSER_; - offerLinkBrowser_ = DEFAULT_OFFER_LINK_BROWSER_; - offerMouseOverView_ = DEFAULT_OFFER_MOUSEOVER_VIEW_; - mouseOverURL_= DEFAULT_MOUSEOVER_URL_; } /*************************************************************************** @@ -122,9 +108,8 @@ public FabricDisplayOptions() { FabricDisplayOptions(String selectionOpaqueLevelStr, String nodeLighterLevelStr, String linkDarkerLevelStr, String displayShadowsStr, - String shadeNodesStr, String minShadSubLinksStr, - String offerNodeBrowser, String offerLinkBrowser, String offerMouseOverView, - String browserURL, String browserLinkURL, String mouseOverURL) throws IOException { + String shadeNodesStr, String minShadSubLinksStr, String browserURL, + String browserLinkURL) throws IOException { if (selectionOpaqueLevelStr != null) { try { @@ -173,24 +158,6 @@ public FabricDisplayOptions() { } else { minShadSubLinks_ = DEFAULT_MINIMIZE_SHADOW_SUBMODEL_LINKS_; } - - if (offerNodeBrowser != null) { - offerNodeBrowser_ = Boolean.valueOf(offerNodeBrowser).booleanValue(); - } else { - offerNodeBrowser_ = DEFAULT_OFFER_NODE_BROWSER_; - } - - if (offerLinkBrowser != null) { - offerLinkBrowser_ = Boolean.valueOf(offerLinkBrowser).booleanValue(); - } else { - offerLinkBrowser_ = DEFAULT_OFFER_LINK_BROWSER_; - } - - if (offerMouseOverView != null) { - offerMouseOverView_ = Boolean.valueOf(offerMouseOverView).booleanValue(); - } else { - offerMouseOverView_ = DEFAULT_OFFER_MOUSEOVER_VIEW_; - } if (browserURL != null) { browserURL_ = browserURL; @@ -203,12 +170,7 @@ public FabricDisplayOptions() { } else { browserLinkURL_ = DEFAULT_LINK_BROWSER_URL_; } - - if (mouseOverURL != null) { - mouseOverURL_ = mouseOverURL; - } else { - mouseOverURL_ = DEFAULT_MOUSEOVER_URL_; - } + } //////////////////////////////////////////////////////////////////////////// @@ -255,25 +217,6 @@ public void setBrowserLinkURL(String browserLinkURL) { return; } - /*************************************************************************** - ** - ** Get mouseover URL - */ - - public String getMouseOverURL() { - return (mouseOverURL_); - } - - /*************************************************************************** - ** - ** Set mouseover URL - */ - - public void setMouseOverURL(String mouseOverURL) { - mouseOverURL_ = mouseOverURL; - return; - } - /*************************************************************************** ** ** Get Selection Opaque level @@ -397,70 +340,12 @@ public void setShadeNodes(boolean shade) { return; } - /*************************************************************************** - ** - ** Get if we are to offer node browser option - */ - - public boolean getOfferNodeBrowser() { - return (offerNodeBrowser_); - } - - /*************************************************************************** - ** - ** Set if we are to offer node browser option - */ - - public void setOfferNodeBrowser(boolean offerNodeBrowser) { - offerNodeBrowser_ = offerNodeBrowser; - return; - } - - /*************************************************************************** - ** - ** Get if we are to offer link browser option - */ - - public boolean getOfferLinkBrowser() { - return (offerLinkBrowser_); - } - - /*************************************************************************** - ** - ** Set if we are to offer link browser option - */ - - public void setOfferLinkBrowser(boolean offerLinkBrowser) { - offerLinkBrowser_ = offerLinkBrowser; - return; - } - - /*************************************************************************** - ** - ** Get if we are to offer mouseover view - */ - - public boolean getOfferMouseOverView() { - return (offerMouseOverView_); - } - - /*************************************************************************** - ** - ** Set if we are to offer mouseover view - */ - - public void setOfferMouseOverView(boolean offerMouseOverView) { - offerMouseOverView_ = offerMouseOverView; - return; - } - /*************************************************************************** ** ** Clone */ - @Override - public FabricDisplayOptions clone() { + public Object clone() { try { FabricDisplayOptions retval = (FabricDisplayOptions)super.clone(); return (retval); @@ -514,25 +399,7 @@ public void writeXML(PrintWriter out, Indenter ind) { out.print(minShadSubLinks_); out.print("\" "); } - - if (offerNodeBrowser_ != DEFAULT_OFFER_NODE_BROWSER_) { - out.print("offerNodeBrowser=\""); - out.print(offerNodeBrowser_); - out.print("\" "); - } - - if (offerLinkBrowser_ != DEFAULT_OFFER_LINK_BROWSER_) { - out.print("offerLinkBrowser=\""); - out.print(offerLinkBrowser_); - out.print("\" "); - } - - if (offerMouseOverView_ != DEFAULT_OFFER_MOUSEOVER_VIEW_) { - out.print("offerMouseOverView=\""); - out.print(offerMouseOverView_); - out.print("\" "); - } - + if (!browserURL_.equals(DEFAULT_BROWSER_URL_)) { out.print("browserURL=\""); out.print(CharacterEntityMapper.mapEntities(browserURL_, false)); @@ -545,11 +412,7 @@ public void writeXML(PrintWriter out, Indenter ind) { out.print("\" "); } - if (!mouseOverURL_.equals(DEFAULT_MOUSEOVER_URL_)) { - out.print("mouseOverURL=\""); - out.print(CharacterEntityMapper.mapEntities(mouseOverURL_, false)); - out.print("\" "); - } + out.println("/>"); return; @@ -592,21 +455,15 @@ private FabricDisplayOptions buildFromXML(String elemName, Attributes attrs) thr String displayShadowsStr = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "shadows", false); String shadeNodesStr = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "shading", false); String minShadSubLinks = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "minShadSubLinks", false); - String offerNodeBrowserStr = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "offerNodeBrowser", false); - String offerLinkBrowserStr = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "offerLinkBrowser", false); - String offerMouseOverViewStr = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "offerMouseOverView", false); String browserURL = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "browserURL", false); String browserLinkURL = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "browserLinkURL", false); - String mouseOverURL = AttributeExtractor.extractAttribute(elemName, attrs, "displayOptions", "mouseOverURL", false); browserURL = (browserURL == null) ? null : CharacterEntityMapper.unmapEntities(browserURL, false); browserLinkURL = (browserLinkURL == null) ? null : CharacterEntityMapper.unmapEntities(browserLinkURL, false); return (new FabricDisplayOptions(selectionOpaqueLevelStr, nodeLighterLevelStr, linkDarkerLevelStr, displayShadowsStr, - shadeNodesStr, minShadSubLinks, - offerNodeBrowserStr, offerLinkBrowserStr, offerMouseOverViewStr, - browserURL, browserLinkURL, mouseOverURL)); + shadeNodesStr, minShadSubLinks, browserURL, browserLinkURL)); } } diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/FabricDisplayOptionsDialog.java b/src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptionsDialog.java similarity index 84% rename from src/org/systemsbiology/biofabric/ui/dialogs/FabricDisplayOptionsDialog.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptionsDialog.java index ce2db6c..77ab214 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/FabricDisplayOptionsDialog.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptionsDialog.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -18,27 +18,23 @@ */ -package org.systemsbiology.biofabric.ui.dialogs; +package org.systemsbiology.biotapestry.biofabric; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.net.MalformedURLException; import java.net.URL; - import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JCheckBox; import javax.swing.JOptionPane; -import org.systemsbiology.biofabric.ui.FabricDisplayOptions; -import org.systemsbiology.biofabric.ui.FabricDisplayOptionsManager; -import org.systemsbiology.biofabric.ui.dialogs.utils.BTStashResultsDialog; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.ui.dialogs.utils.BTStashResultsDialog; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ExceptionHandler; /**************************************************************************** ** @@ -53,8 +49,6 @@ public class FabricDisplayOptionsDialog extends BTStashResultsDialog { // //////////////////////////////////////////////////////////////////////////// - private static final long serialVersionUID = 1L; - //////////////////////////////////////////////////////////////////////////// // // PRIVATE INSTANCE MEMBERS @@ -67,12 +61,8 @@ public class FabricDisplayOptionsDialog extends BTStashResultsDialog { private JCheckBox displayShadowsBox_; private JCheckBox minShadSublinksBox_; private JCheckBox shadeNodesBox_; - private JCheckBox offerNodeBrowser_; private JTextField browserURLField_; - private JCheckBox offerLinkBrowser_; private JTextField browserLinkURLField_; - private JCheckBox offerMouseOverView_; - private JTextField mouseOverTemplateField_; private FabricDisplayOptions newOpts_; private boolean needRebuild_; @@ -90,7 +80,7 @@ public class FabricDisplayOptionsDialog extends BTStashResultsDialog { */ public FabricDisplayOptionsDialog(JFrame parent) { - super(parent, "displayOptions.title", new Dimension(1000, 600), 2); + super(parent, "displayOptions.title", new Dimension(1000, 400), 2); ResourceManager rMan = ResourceManager.getManager(); parent_ = parent; @@ -133,30 +123,14 @@ public void actionPerformed(ActionEvent ev) { shadeNodesBox_.setSelected(options.getShadeNodes()); addWidgetFullRow(shadeNodesBox_, false); - offerNodeBrowser_ = new JCheckBox(rMan.getString("displayOptions.offerNodeBrowser")); - offerNodeBrowser_.setSelected(options.getOfferNodeBrowser()); - addWidgetFullRow(offerNodeBrowser_, false); - browserURLField_ = new JTextField(options.getBrowserURL()); label = new JLabel(rMan.getString("displayOptions.browserURL")); addLabeledWidget(label, browserURLField_, false, false); - offerLinkBrowser_ = new JCheckBox(rMan.getString("displayOptions.offerLinkBrowser")); - offerLinkBrowser_.setSelected(options.getOfferLinkBrowser()); - addWidgetFullRow(offerLinkBrowser_, false); - browserLinkURLField_ = new JTextField(options.getBrowserLinkURL()); label = new JLabel(rMan.getString("displayOptions.browserLinkURL")); addLabeledWidget(label, browserLinkURLField_, false, false); - offerMouseOverView_ = new JCheckBox(rMan.getString("displayOptions.offerMouseOverView")); - offerMouseOverView_.setSelected(options.getOfferMouseOverView()); - addWidgetFullRow(offerMouseOverView_, false); - - mouseOverTemplateField_ = new JTextField(options.getMouseOverURL()); - label = new JLabel(rMan.getString("displayOptions.MouseOverURL")); - addLabeledWidget(label, mouseOverTemplateField_, false, false); - // // Build extra button: // @@ -267,15 +241,6 @@ protected boolean stashForOK() { newOpts_.setShadeNodes(currShade); needRecolor_ = needRecolor_ || (oldOpts.getShadeNodes() != newOpts_.getShadeNodes()); - boolean offerNode = offerNodeBrowser_.isSelected(); - newOpts_.setOfferNodeBrowser(offerNode); - - boolean offerLink = offerLinkBrowser_.isSelected(); - newOpts_.setOfferLinkBrowser(offerLink); - - boolean offerMO = offerMouseOverView_.isSelected(); - newOpts_.setOfferMouseOverView(offerMO); - String browserURL = browserURLField_.getText().trim(); if (!testURL(browserURL, true)) { return (false); @@ -287,11 +252,7 @@ protected boolean stashForOK() { return (false); } newOpts_.setBrowserLinkURL(browserLinkURL); - - String mouseOverURL = this.mouseOverTemplateField_.getText().trim(); - UiUtil.fixMePrintout("Test this URL for correctness"); - newOpts_.setMouseOverURL(mouseOverURL); - + return (true); } @@ -394,7 +355,6 @@ private void resetDefaults() { shadeNodesBox_.setSelected(defOptions.getShadeNodes()); browserURLField_.setText(defOptions.getBrowserURL()); browserLinkURLField_.setText(defOptions.getBrowserLinkURL()); - mouseOverTemplateField_.setText(defOptions.getMouseOverURL()); return; } } diff --git a/src/org/systemsbiology/biofabric/ui/FabricDisplayOptionsManager.java b/src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptionsManager.java similarity index 92% rename from src/org/systemsbiology/biofabric/ui/FabricDisplayOptionsManager.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptionsManager.java index 08f3471..d9376df 100644 --- a/src/org/systemsbiology/biofabric/ui/FabricDisplayOptionsManager.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricDisplayOptionsManager.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,12 +17,11 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.biofabric; import java.io.PrintWriter; import java.util.ArrayList; - -import org.systemsbiology.biofabric.util.Indenter; +import org.systemsbiology.biotapestry.util.Indenter; /**************************************************************************** ** @@ -45,7 +44,7 @@ public class FabricDisplayOptionsManager { private static FabricDisplayOptionsManager singleton_; private FabricDisplayOptions options_; - private ArrayList trackers_; + private ArrayList trackers_; //////////////////////////////////////////////////////////////////////////// // @@ -69,10 +68,10 @@ public FabricDisplayOptions getDisplayOptions() { */ public void setDisplayOptions(FabricDisplayOptions opts, boolean needRebuild, boolean needRecolor) { - options_ = opts.clone(); + options_ = (FabricDisplayOptions)opts.clone(); int numTrack = trackers_.size(); for (int i = 0; i < numTrack; i++) { - DisplayOptionTracker dot = trackers_.get(i); + DisplayOptionTracker dot = (DisplayOptionTracker)trackers_.get(i); dot.optionsHaveChanged(needRebuild, needRecolor); } return; @@ -151,6 +150,6 @@ public interface DisplayOptionTracker { private FabricDisplayOptionsManager() { options_ = new FabricDisplayOptions(); - trackers_ = new ArrayList(); + trackers_ = new ArrayList(); } } diff --git a/src/org/systemsbiology/biofabric/io/FabricFactory.java b/src/org/systemsbiology/biotapestry/biofabric/FabricFactory.java similarity index 78% rename from src/org/systemsbiology/biofabric/io/FabricFactory.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricFactory.java index 951bb80..68820fd 100644 --- a/src/org/systemsbiology/biofabric/io/FabricFactory.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricFactory.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2016 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.io; +package org.systemsbiology.biotapestry.biofabric; import java.util.Set; import java.util.HashSet; @@ -25,17 +25,11 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; -import java.util.Map; import org.xml.sax.Attributes; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.parser.ParserClient; -import org.systemsbiology.biofabric.ui.FabricColorGenerator; -import org.systemsbiology.biofabric.ui.FabricDisplayOptions; -import org.systemsbiology.biofabric.ui.NamedColor; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.UniqueLabeller; +import org.systemsbiology.biotapestry.parser.ParserClient; +import org.systemsbiology.biotapestry.ui.NamedColor; /**************************************************************************** ** @@ -50,9 +44,9 @@ public class FabricFactory implements ParserClient { // //////////////////////////////////////////////////////////////////////////// - private HashSet allKeys_; + private HashSet allKeys_; private ParserClient currClient_; - private HashMap clients_; + private HashMap clients_; private FactoryWhiteboard whiteBoard_; //////////////////////////////////////////////////////////////////////////// @@ -68,23 +62,23 @@ public class FabricFactory implements ParserClient { public FabricFactory() { - allKeys_ = new HashSet(); + allKeys_ = new HashSet(); whiteBoard_ = new FactoryWhiteboard(); BioFabricNetwork.NetworkDataWorker ndw = new BioFabricNetwork.NetworkDataWorker(whiteBoard_); - ArrayList alist = new ArrayList(); + ArrayList alist = new ArrayList(); alist.add(ndw); allKeys_.addAll(ndw.keywordsOfInterest()); - Iterator cit = alist.iterator(); - clients_ = new HashMap(); + Iterator cit = alist.iterator(); + clients_ = new HashMap(); while (cit.hasNext()) { - ParserClient pc = cit.next(); - Set keys = pc.keywordsOfInterest(); - Iterator ki = keys.iterator(); + ParserClient pc = (ParserClient)cit.next(); + Set keys = pc.keywordsOfInterest(); + Iterator ki = keys.iterator(); while (ki.hasNext()) { - String key = ki.next(); + String key = (String)ki.next(); Object prev = clients_.put(key, pc); if (prev != null) { throw new IllegalArgumentException(); @@ -156,7 +150,7 @@ public void processCharacters(char[] chars, int start, int length) { ** */ - public Set keywordsOfInterest() { + public Set keywordsOfInterest() { return (allKeys_); } @@ -172,7 +166,7 @@ public Object processElement(String elemName, Attributes attrs) throws IOExcepti return (currClient_.processElement(elemName, attrs)); } - ParserClient pc = clients_.get(elemName); + ParserClient pc = (ParserClient)clients_.get(elemName); if (pc != null) { currClient_ = pc; return (currClient_.processElement(elemName, attrs)); @@ -181,7 +175,6 @@ public Object processElement(String elemName, Attributes attrs) throws IOExcepti } public static class FactoryWhiteboard { - public UniqueLabeller ulb; public BioFabricNetwork bfn; public BioFabricNetwork.LinkInfo linkInfo; public BioFabricNetwork.NodeInfo nodeInfo; @@ -190,14 +183,9 @@ public static class FactoryWhiteboard { public int colTarg; public String groupTag; public FabricDisplayOptions displayOpts; - public Map legacyMap; - public Map wnMap; public FactoryWhiteboard() { colTarg = FabricColorGenerator.UNCHANGED; - ulb = new UniqueLabeller(); - legacyMap = new HashMap(); - wnMap = new HashMap(); } } diff --git a/src/org/systemsbiology/biotapestry/biofabric/FabricGoose.java b/src/org/systemsbiology/biotapestry/biofabric/FabricGoose.java new file mode 100644 index 0000000..e802c4f --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricGoose.java @@ -0,0 +1,695 @@ +/* +** Copyright (C) 2003-2009 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ +// +// Ported to Gaggle 2007-4 by Dan Tenenbaum +// in September 2007 +// + +/* START HIDE GAGGLE CODE */ /* + +package org.systemsbiology.biotapestry.biofabric; + +import java.util.ArrayList; +import java.awt.Frame; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.net.MalformedURLException; +import java.rmi.RemoteException; +import java.rmi.NotBoundException; +import java.rmi.ConnectException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; + +import org.systemsbiology.gaggle.geese.common.GooseShutdownHook; +import org.systemsbiology.gaggle.geese.common.GaggleConnectionListener; +import org.systemsbiology.gaggle.core.Boss; +import org.systemsbiology.gaggle.core.Goose; +import org.systemsbiology.gaggle.core.datatypes.Cluster; +import org.systemsbiology.gaggle.core.datatypes.DataMatrix; +import org.systemsbiology.gaggle.core.datatypes.GaggleTuple; +import org.systemsbiology.gaggle.core.datatypes.Interaction; +import org.systemsbiology.gaggle.core.datatypes.Namelist; +import org.systemsbiology.gaggle.core.datatypes.Network; +import org.systemsbiology.gaggle.geese.common.RmiGaggleConnector; +import org.systemsbiology.gaggle.util.MiscUtil; + +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.ExceptionHandler; + +//** +//** Used for gaggle communication. +// + +public class FabricGoose implements Goose, FabricGooseInterface, GaggleConnectionListener { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + private static final String NODE_TYPE_TAG_ = "NodeType"; + private static final String LINK_SIGN_TAG_ = "LinkSign"; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + private BioFabricWindow topWindow_; + private String name_; + private Boss gaggleBoss_; + private SelectionSupport selSupport_; + private String targetName_; + private boolean activated_; + private boolean connected_; + private RmiGaggleConnector connector_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + ///*************************************************************************** + //** + //** Null Constructor + // + + public FabricGoose() { + activated_ = false; + connected_ = false; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC METHODS + // + //////////////////////////////////////////////////////////////////////////// + + //*************************************************************************** + //** + //** Set goose parameters - called on AWT thread + // + + public void setParameters(BioFabricWindow topWindow, String species) { + if (activated_) { + throw new IllegalStateException(); + } + selSupport_ = new SelectionSupport(topWindow, species); + topWindow_ = topWindow; + name_ = "BioFabric"; + targetName_ = "boss"; + } + + ///*************************************************************************** + //** + //** Activate the goose - called on AWT thread + // + + public void activate() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + activated_ = false; + connector_ = new RmiGaggleConnector(this); + new GooseShutdownHook(connector_); + connectToGaggle(); // sets activated_, connected_ on success + connector_.addListener(this); + return; + } + + ///*************************************************************************** + //** + //** A function to find out if goose is connected - called on AWT thread + // + + public boolean isConnected() { + return (connected_); + } + + ///*************************************************************************** + //** + //** connect to gaggle - called on AWT thread + // + + public void connect() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + try { + connector_.connectToGaggle(); + connected_ = true; + } catch (RemoteException rex) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToConnect"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } catch (Exception rex) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToDisconnect"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } + return; + } + + ///*************************************************************************** + //** + //** Disconnect from gaggle - called on AWT thread + // + + public void disconnect() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + try { + connector_.disconnectFromGaggle(false); + connected_ = true; + } catch (Exception rex) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToDisconnect"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } + return; + } + + ///*************************************************************************** + //** + //** A function to find out if goose is active - called on AWT thread + // + + public boolean isActivated() { + return (activated_); + } + + ///*************************************************************************** + //** + //** A function to get selection support - called on AWT thread + // + + public SelectionSupport getSelectionSupport() { + return (selSupport_); + } + + ///*************************************************************************** + //** + //** A function set the current target - called on AWT thread + // + + public void setCurrentGaggleTarget(String gooseName) { + targetName_ = gooseName; + return; + } + + ///*************************************************************************** + //** + // ** A function to transmit selections to the gaggle boss. - called on AWT thread + // + + public void transmitSelections() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + try { + SelectionSupport.SelectionsForSpecies sel = selSupport_.getSelections(); + ArrayList list = new ArrayList(sel.selections); + Namelist namelist = new Namelist(); + namelist.setSpecies(sel.species); + namelist.setNames((String[])list.toArray(new String[list.size()])); + gaggleBoss_.broadcastNamelist(name_, targetName_, namelist); + } catch (RemoteException rex) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToContactBoss"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } + return; + } + + ///*************************************************************************** + // ** + //** A function to transmit a network - called on AWT thread + // + + public void transmitNetwork(SelectionSupport.NetworkForSpecies net) { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + try { + Network gaggleNet = new Network(); + String species = net.getSpecies(); + List links = net.getLinks(); + Iterator ltit = links.iterator(); + while (ltit.hasNext()) { + FabricLink link = (FabricLink)ltit.next(); + String src = link.getSrc(); + String trg = link.getTrg(); + FabricLink.AugRelation aug = link.getAugRelation(); + if (aug.isShadow) { + continue; + } + Interaction interact = new Interaction(src, trg, aug.relation, link.isDirected()); + gaggleNet.add(interact); + } + gaggleNet.setSpecies(species); + gaggleBoss_.broadcastNetwork(name_, targetName_, gaggleNet); + } catch (RemoteException rex) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToContactBoss"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } + return; + } + + ///*************************************************************************** + // ** + // ** A function to show the current target - called on AWT thread + // + + public void raiseCurrentTarget() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + try { + gaggleBoss_.show(targetName_); + } catch (RemoteException rex) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToContactBoss"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } + } + + ///*************************************************************************** + //** + //** A function to hide the current target - called on AWT thread + // + + public void hideCurrentTarget() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + try { + gaggleBoss_.hide(targetName_); + } catch (RemoteException rex) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToContactBoss"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } + return; + } + + ///*************************************************************************** + // ** + //** A function to shut down the gaggle infrastructure - called on AWT thread + // + + public void closeDown() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + try { + connector_.disconnectFromGaggle(true); + activated_ = false; + } catch (Exception ex) { + ex.printStackTrace(); + // We are going down, so don't display in UI + } + + return; + } + + ///*************************************************************************** + //** + //** Tell us if we are connected (GaggleConnectionListener req'd - called on RMI thread) + //** dt. Geese can now connect and disconnect independently. + // + + public void setConnected(boolean connected, Boss boss) { + gaggleBoss_ = boss; + try { + selSupport_.changeConnectionStatus(connected); + } catch (Exception ex) { + final Exception exF = ex; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ExceptionHandler.getHandler().displayException(exF); + } + }); + } + return; + } + + ///*************************************************************************** + //** + //** Connect to the boss (called on AWT thread) + // dt. Geese can now connect and disconnect independently. You may want to add + // some UI elements to handle this. You can use connector_.isConnected() to find out + // if you are connected, or to be notified when connection status changes, implement + // GaggleConnectionListener, which defines a method setConnected(boolean connected, Boss boss). + // See org.systemsbiology.gaggle.geese.sample.SampleGoose for an example. + + public void connectToGaggle() { + if (!SwingUtilities.isEventDispatchThread()) { + throw new IllegalStateException(); + } + try { + // + // Goose will look to see if there is a boss and if not, will start + // an invisible boss using java web start. + // + connector_.setAutoStartBoss(true); + connector_.connectToGaggle(); + activated_ = true; + connected_ = true; + } catch (ConnectException ce) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToConnectToBoss"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } catch (NotBoundException nbe) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToLookupBoss"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } catch (RemoteException re) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToContactBoss"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } catch (MalformedURLException nbe) { + throw new IllegalStateException(); + } catch (Exception ex) { // required by 2007-4 interface + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, + rMan.getString("gaggleSupport.failedToConnectToBoss"), + rMan.getString("gaggleSupport.commFailureTitle"), + JOptionPane.WARNING_MESSAGE); + } + + gaggleBoss_ = connector_.getBoss(); + return; + } + + ///*************************************************************************** + //** + //** Get the goose name (Goose req'd - called on RMI thread) + // + + public String getName() { + return (name_); + } + + ///*************************************************************************** + //** + // ** Set the goose name (Goose req'd - called on RMI thread) + // + + public void setName(String newName) { + this.name_ = newName; + return; + } + + ///*************************************************************************** + // ** + // ** Hide the application (Goose req'd - called on RMI thread) + // + + public void doHide() { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { + topWindow_.hide(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + return; + } + + ///*************************************************************************** + // ** + // ** Show the application (Goose req'd - called on RMI thread) + // + + public void doShow() { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { + if (topWindow_.getExtendedState() != Frame.NORMAL) { + topWindow_.setExtendedState (Frame.NORMAL); + } + MiscUtil.setJFrameAlwaysOnTop(topWindow_, true); + topWindow_.setVisible(true); + MiscUtil.setJFrameAlwaysOnTop(topWindow_, false); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + return; + } + + ///*************************************************************************** + // ** + // ** Inbound request to do a broadcast (Goose req'd - called on RMI thread) + // + // + // * @deprecated //dt this is no longer the right way to do this but so many geese still + // use it, so we were lazy and left it in the interface but marked it deprecated. + // + public void doBroadcastList() { + try { + SelectionSupport.SelectionsForSpecies sel = selSupport_.getSelections(); + ArrayList list = new ArrayList(sel.selections); + Namelist namelist = new Namelist(); + namelist.setSpecies(sel.species); + namelist.setNames((String[])list.toArray(new String[list.size()])); + gaggleBoss_.broadcastNamelist(name_, BOSS_NAME, namelist); + } catch (Exception ex) { + final Exception exF = ex; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ExceptionHandler.getHandler().displayException(exF); + } + }); + } + return; + } + + // /*************************************************************************** + // ** + // ** Request for program to exit (Goose req'd - called on RMI thread) + // + + public void doExit() { + try { + connector_.disconnectFromGaggle(true); + activated_ = false; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { + topWindow_.getApplication().shutdownFabric(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + }); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + ///*************************************************************************** + //** + //** Inbound request to handle a name list (Goose req'd - called on RMI thread) + // + + public void handleNameList(String source, Namelist namelist) { + try { + selSupport_.addSelectionCommand(namelist.getSpecies(), namelist.getNames()); + } catch (Exception ex) { + final Exception exF = ex; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ExceptionHandler.getHandler().displayException(exF); + } + }); + } + return; + } + + ///*************************************************************************** + //** + //** Inbound request to handle a matrix (Goose req'd - called on RMI thread) + // + + public void handleMatrix(String source, DataMatrix matrix) { + try { + selSupport_.addUnsupportedCommand(); + } catch (Exception ex) { + final Exception exF = ex; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ExceptionHandler.getHandler().displayException(exF); + } + }); + } + } + + ///*************************************************************************** + //** + //** Inbound request to handle a map (Goose req'd - called on RMI thread) + // + + public void handleTuple(String source, GaggleTuple gaggleTuple) { + try { + selSupport_.addUnsupportedCommand(); + } catch (Exception ex) { + final Exception exF = ex; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ExceptionHandler.getHandler().displayException(exF); + } + }); + } + } + + ///*************************************************************************** + //** + //** Inbound request to handle a cluster (Goose req'd - called on RMI thread) + // + + public void handleCluster(String source, Cluster cluster) { + try { + selSupport_.addUnsupportedCommand(); + } catch (Exception ex) { + final Exception exF = ex; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ExceptionHandler.getHandler().displayException(exF); + } + }); + } + } + + ///*************************************************************************** + //** + //** Inbound request to handle a network (Goose req'd - called on RMI thread) + // + + public void handleNetwork(String source, Network network) { + HashSet directedRels = new HashSet(); + directedRels.add("pd"); + try { + ArrayList linkList = new ArrayList(); + Interaction[] interact = network.getInteractions(); + int numInter = interact.length; + for (int i = 0; i < numInter; i++) { + String src = interact[i].getSource(); + String trg = interact[i].getTarget(); + String rel = interact[i].getType(); + boolean isDirected = interact[i].isDirected(); + FabricLink nextLink = new FabricLink(src, trg, rel, false, new Boolean(isDirected)); + linkList.add(nextLink); + nextLink = new FabricLink(src, trg, rel, true, new Boolean(isDirected)); + linkList.add(nextLink); + } + String[] singletons = network.getOrphanNodes(); + List singlesList = new ArrayList(Arrays.asList(singletons)); + selSupport_.createNewNetwork(network.getSpecies(), linkList, singlesList); + } catch (Exception ex) { + final Exception exF = ex; + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ExceptionHandler.getHandler().displayException(exF); + } + }); + } + } + + ///*************************************************************************** + //** + //** Inbound notification of current geese (Goose req'd - called on RMI thread) + // + + public void update(String[] updatedGeese) { + List gooseList = new ArrayList(Arrays.asList(updatedGeese)); + gooseList.remove(name_); + Collections.sort(gooseList); + selSupport_.registerNewGooseList(gooseList); + return; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CLASS METHODS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// +} +*/ // FINISH HIDE GAGGLE CODE diff --git a/src/org/systemsbiology/biotapestry/biofabric/FabricGooseInterface.java b/src/org/systemsbiology/biotapestry/biofabric/FabricGooseInterface.java new file mode 100644 index 0000000..79fee45 --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricGooseInterface.java @@ -0,0 +1,133 @@ +/* +** Copyright (C) 2003-2007 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + + +/**************************************************************************** +** +** Defines goose application interface +*/ + +public interface FabricGooseInterface { + + public static final String BOSS_NAME = "boss"; + + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Activate the goose - called on AWT thread + */ + + public void activate(); + + /*************************************************************************** + ** + ** Set goose parameters - called on AWT thread + */ + + public void setParameters(BioFabricWindow topWindow, String species); + + /*************************************************************************** + ** + ** A function to find out if goose is active - called on AWT thread + */ + + public boolean isActivated(); + + + /*************************************************************************** + ** + ** A function to find out if goose is connected - called on AWT thread + */ + + public boolean isConnected(); + + /*************************************************************************** + ** + ** A function to connect to gaggle - called on AWT thread + */ + + public void connect(); + + /*************************************************************************** + ** + ** Disconnect from gaggle - called on AWT thread + */ + + public void disconnect(); + + /*************************************************************************** + ** + ** A function to get selection support - called on AWT thread + */ + + public SelectionSupport getSelectionSupport(); + + /*************************************************************************** + ** + ** A function to set the current gaggle target - called on AWT thread + */ + + public void setCurrentGaggleTarget(String gooseName); + + /*************************************************************************** + ** + ** A function to transmit selections to the gaggle boss. - called on AWT thread + */ + + public void transmitSelections(); + + /*************************************************************************** + ** + ** A function to transmit a network - called on AWT thread + */ + + public void transmitNetwork(SelectionSupport.NetworkForSpecies net); + + /*************************************************************************** + ** + ** A function to show the current target - called on AWT thread + */ + + public void raiseCurrentTarget(); + + /*************************************************************************** + ** + ** A function to hide the current target - called on AWT thread + */ + + public void hideCurrentTarget(); + + /*************************************************************************** + ** + ** A function to shut down the gaggle infrastructure - called on AWT thread + */ + + public void closeDown(); + + /*************************************************************************** + ** + ** Connect to the boss (Goose req'd - called on AWT thread) + */ + + public void connectToGaggle(); + +} diff --git a/src/org/systemsbiology/biofabric/ui/display/MouseOverView.java b/src/org/systemsbiology/biotapestry/biofabric/FabricGooseManager.java similarity index 54% rename from src/org/systemsbiology/biofabric/ui/display/MouseOverView.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricGooseManager.java index 03e93a7..066cc83 100644 --- a/src/org/systemsbiology/biofabric/ui/display/MouseOverView.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricGooseManager.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2017 Institute for Systems Biology +** Copyright (C) 2003-2005 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,120 +17,120 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.display; - -import javax.swing.JPanel; +package org.systemsbiology.biotapestry.biofabric; /**************************************************************************** ** -** This panel gives a view for mouseovers +** Used for getting the current goose. This is a Singleton. */ -public class MouseOverView { +public class FabricGooseManager { //////////////////////////////////////////////////////////////////////////// // // PRIVATE CONSTANTS // - //////////////////////////////////////////////////////////////////////////// - + //////////////////////////////////////////////////////////////////////////// + + private static FabricGooseManager singleton_; + + private FabricGooseInterface goose_; + //////////////////////////////////////////////////////////////////////////// // // PUBLIC CONSTANTS // //////////////////////////////////////////////////////////////////////////// - + //////////////////////////////////////////////////////////////////////////// // - // PRIVATE INSTANCE MEMBERS + // PRIVATE VARIABLES // //////////////////////////////////////////////////////////////////////////// - - private MouseOverViewPanel pan1_; - private MouseOverViewPanel pan2_; - private boolean isAlive_; - + //////////////////////////////////////////////////////////////////////////// // // PUBLIC CONSTRUCTORS // //////////////////////////////////////////////////////////////////////////// - /*************************************************************************** - ** - ** Constructor - */ - - public MouseOverView() { - pan1_ = new MouseOverViewPanel(); - pan2_ = new MouseOverViewPanel(); - isAlive_ = false; - } - //////////////////////////////////////////////////////////////////////////// // // PUBLIC METHODS // //////////////////////////////////////////////////////////////////////////// - + /*************************************************************************** - ** - ** Show or hide the view + ** + ** Set the goose */ - public void setIsAlive(boolean alive) { - isAlive_ = alive; + public void setGoose(FabricGooseInterface gai) { + if (goose_ != null) { + throw new IllegalStateException(); + } + goose_ = gai; return; - } + } /*************************************************************************** - ** - ** Set file locations to use for image files + ** + ** Get the goose. May be null early in program execution. */ - public void setFileLocations(String path, String filePrefix, String fileSuffix) { - pan1_.setFileLocations(path, filePrefix, fileSuffix); - pan2_.setFileLocations(path, filePrefix, fileSuffix); - return; + public FabricGooseInterface getGoose() { + return (goose_); } - - /*************************************************************************** - ** - ** Show or hide the view - */ + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CLASS METHODS + // + //////////////////////////////////////////////////////////////////////////// - public void showView(boolean enabled) { - pan1_.showView(enabled); - pan2_.showView(enabled); - return; - } - /*************************************************************************** - ** - ** SGet the view + ** + ** Get the singleton goose manager */ - public JPanel getPanel(int num) { - return ((num == 0) ? pan1_ : pan2_); + public static synchronized FabricGooseManager getManager() { + if (singleton_ == null) { + singleton_ = new FabricGooseManager(); + } + return (singleton_); } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + /*************************************************************************** - ** - ** Install a model + ** + ** Constructor */ - public void showForNode(BioFabricPanel.MouseLocInfo mlo) { - if (!isAlive_) { - return; - } - pan1_.showForNode(mlo.zoneDesc.equals("") ? null : mlo.zoneDesc); - if (mlo.linkDesc.equals("")) { - pan2_.showForNode(null); - } else { - String other = mlo.zoneDesc.equals(mlo.linkSrcDesc) ? mlo.linkTrgDesc : mlo.linkSrcDesc; - pan2_.showForNode(other); - } - return; - } + private FabricGooseManager() { + goose_ = null; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// } diff --git a/src/org/systemsbiology/biofabric/model/FabricLink.java b/src/org/systemsbiology/biotapestry/biofabric/FabricLink.java similarity index 55% rename from src/org/systemsbiology/biofabric/model/FabricLink.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricLink.java index dd5154b..c697ea0 100644 --- a/src/org/systemsbiology/biofabric/model/FabricLink.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricLink.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2016 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,47 +17,40 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.model; - -import java.util.Comparator; -import java.util.Map; - -import org.systemsbiology.biofabric.io.AttributeLoader; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.NID; +package org.systemsbiology.biotapestry.biofabric; /**************************************************************************** ** ** A Class */ -public class FabricLink implements Cloneable, AttributeLoader.AttributeKey { - private NID.WithName srcID_; - private NID.WithName trgID_; +public class FabricLink implements Cloneable, Comparable { + private String src_; + private String trg_; private String relation_; private Boolean directed_; private boolean isShadow_; - public FabricLink(NID.WithName srcID, NID.WithName trgID, String relation, boolean isShadow, Boolean directed) { - if ((srcID == null) || (trgID == null) || (relation == null)) { + public FabricLink(String src, String trg, String relation, boolean isShadow, Boolean directed) { + if ((src == null) || (trg == null) || (relation == null)) { throw new IllegalArgumentException(); } - srcID_ = srcID; - trgID_ = trgID; + src_ = src; + trg_ = trg; relation_ = relation; isShadow_ = isShadow; directed_ = directed; } - public FabricLink(NID.WithName srcID, NID.WithName trgID, String relation, boolean isShadow) { - this(srcID, trgID, relation, isShadow, null); + public FabricLink(String src, String trg, String relation, boolean isShadow) { + this(src, trg, relation, isShadow, null); } public FabricLink flipped() { if (isFeedback()) { throw new IllegalStateException(); } - return (new FabricLink(trgID_, srcID_, relation_, isShadow_, directed_)); + return (new FabricLink(trg_, src_, relation_, isShadow_, directed_)); } public boolean directionFrozen() { @@ -71,11 +64,10 @@ public void installDirection(Boolean isDirected) { directed_ = isDirected; return; } - - @Override - public FabricLink clone() { + + public Object clone() { try { - return ((FabricLink)super.clone()); + return (super.clone()); } catch (CloneNotSupportedException cnse) { throw new IllegalStateException(); } @@ -90,18 +82,14 @@ public void dropShadowStatus() { return; } - public NID.WithName getTrgID() { - return (trgID_); + public String getTrg() { + return (trg_); } - public NID.WithName getSrcID() { - return (srcID_); + public String getSrc() { + return (src_); } - - public String getRelation() { - return (relation_); - } - + public AugRelation getAugRelation() { return (new AugRelation(relation_, isShadow_)); } @@ -114,23 +102,21 @@ public boolean isDirected() { } public boolean isFeedback() { - return (srcID_.equals(trgID_)); + return (src_.equals(trg_)); } - - @Override + public int hashCode() { - return (srcID_.hashCode() + trgID_.hashCode() + DataUtil.normKey(relation_).hashCode() + ((isShadow_) ? 17 : 31) + + return (src_.hashCode() + trg_.hashCode() + relation_.hashCode() + ((isShadow_) ? 17 : 31) + ((directed_ == null) ? 0 : directed_.hashCode())); } - @Override public String toString() { - return ("srcID = " + srcID_ + " trgID = " + trgID_ + "rel = " + relation_ + " directed_ = " + directed_ + " isShadow_ = " + isShadow_); + return ("src = " + src_ + " trg = " + trg_ + "rel = " + relation_ + " directed_ = " + directed_ + " isShadow_ = " + isShadow_); } public String toDisplayString() { StringBuffer buf = new StringBuffer(); - buf.append(srcID_.getName()); + buf.append(src_); buf.append((isDirected()) ? '-' : '\u2190'); if (isShadow_) { buf.append("shdw"); @@ -139,13 +125,13 @@ public String toDisplayString() { buf.append(relation_); buf.append(")"); buf.append('\u2192'); // For bidirectional '\u2194' - buf.append(trgID_.getName()); + buf.append(trg_); return (buf.toString()); } - public String toEOAString(Map nodeInfo) { + public String toEOAString() { StringBuffer buf = new StringBuffer(); - buf.append(nodeInfo.get(srcID_).getNodeName()); + buf.append(src_); if (isShadow_) { buf.append(" shdw"); } else { @@ -154,11 +140,10 @@ public String toEOAString(Map nodeInfo) buf.append("("); buf.append(relation_); buf.append(") "); - buf.append(nodeInfo.get(trgID_).getNodeName()); + buf.append(trg_); return (buf.toString()); } - @Override public boolean equals(Object other) { if (other == null) { return (false); @@ -171,10 +156,10 @@ public boolean equals(Object other) { } FabricLink otherLink = (FabricLink)other; - if (!this.srcID_.equals(otherLink.srcID_)) { + if (!this.src_.equals(otherLink.src_)) { return (false); } - if (!this.trgID_.equals(otherLink.trgID_)) { + if (!this.trg_.equals(otherLink.trg_)) { return (false); } @@ -182,7 +167,7 @@ public boolean equals(Object other) { return (false); } - if (!DataUtil.normKey(this.relation_).equals(DataUtil.normKey(otherLink.relation_))) { + if (!this.relation_.equals(otherLink.relation_)) { return (false); } @@ -200,29 +185,29 @@ public boolean synonymous(FabricLink other) { if (this.isDirected() || other.isDirected()) { return (false); } - if (!DataUtil.normKey(this.relation_).equals(DataUtil.normKey(other.relation_))) { + if (!this.relation_.equals(other.relation_)) { return (false); } if (this.isShadow_ != other.isShadow_) { return (false); } - if (!this.srcID_.equals(other.trgID_)) { + if (!this.src_.equals(other.trg_)) { return (false); } - return (this.trgID_.equals(other.srcID_)); + return (this.trg_.equals(other.src_)); } public boolean shadowPair(FabricLink other) { if (this.equals(other)) { return (false); } - if (!this.srcID_.equals(other.srcID_)) { + if (!this.src_.equals(other.src_)) { return (false); } - if (!this.trgID_.equals(other.trgID_)) { + if (!this.trg_.equals(other.trg_)) { return (false); } - if (!DataUtil.normKey(this.relation_).equals(DataUtil.normKey(other.relation_))) { + if (!this.relation_.equals(other.relation_)) { return (false); } @@ -239,51 +224,25 @@ public boolean shadowPair(FabricLink other) { return (true); } - /*************************************************************************** - ** - ** Comparator for Fabric Links - */ - - public static class FabLinkComparator implements Comparator { - - public int compare(FabricLink one, FabricLink otherLink) { - if (one.equals(otherLink)) { - return (0); - } - - String srcOne = DataUtil.normKey(one.srcID_.getName()); - String trgOne = DataUtil.normKey(one.trgID_.getName()); - String srcTwo = DataUtil.normKey(otherLink.srcID_.getName()); - String trgTwo = DataUtil.normKey(otherLink.trgID_.getName()); - - if (!srcOne.equals(srcTwo)) { - return (srcOne.compareTo(srcTwo)); - } - if (!trgOne.equals(trgTwo)) { - return (trgOne.compareTo(trgTwo)); - } - if (one.isShadow_ != otherLink.isShadow_) { - return ((one.isShadow_) ? -1 : 1); - } - if (!DataUtil.normKey(one.relation_).equals(DataUtil.normKey(otherLink.relation_))) { - return (one.relation_.compareToIgnoreCase(otherLink.relation_)); - } - - // - // Gatta catch the far-out case where two links with same source and target node names but different - // internal IDs get to here. Can't let it fall through - // - - if (!one.srcID_.equals(otherLink.srcID_)) { - return (one.srcID_.compareTo(otherLink.srcID_)); - } - if (!one.trgID_.equals(otherLink.trgID_)) { - return (one.trgID_.compareTo(otherLink.trgID_)); - } + public int compareTo(Object o) { + if (this.equals(o)) { + return (0); + } + FabricLink otherLink = (FabricLink)o; - throw new IllegalStateException(); - } - + if (!this.src_.equals(otherLink.src_)) { + return (this.src_.compareToIgnoreCase(otherLink.src_)); + } + if (!this.trg_.equals(otherLink.trg_)) { + return (this.trg_.compareToIgnoreCase(otherLink.trg_)); + } + if (this.isShadow_ != otherLink.isShadow_) { + return ((this.isShadow_) ? -1 : 1); + } + if (!this.relation_.equals(otherLink.relation_)) { + return (this.relation_.compareToIgnoreCase(otherLink.relation_)); + } + throw new IllegalStateException(); } /*************************************************************************** @@ -291,39 +250,39 @@ public int compare(FabricLink one, FabricLink otherLink) { ** Augmented relation */ - public static class AugRelation implements Cloneable, Comparable { + public static class AugRelation implements Cloneable, Comparable { public String relation; public boolean isShadow; - public AugRelation(String relation, boolean isShadow) { + AugRelation(String relation, boolean isShadow) { this.relation = relation; this.isShadow = isShadow; } - @Override - public AugRelation clone() { + public Object clone() { try { - return ((AugRelation)super.clone()); + return (super.clone()); } catch (CloneNotSupportedException cnse) { throw new IllegalStateException(); } } - public int compareTo(AugRelation otherAug) { - if (this.equals(otherAug)) { + public int compareTo(Object o) { + if (this.equals(o)) { return (0); } + AugRelation otherAug = (AugRelation)o; if (this.isShadow != otherAug.isShadow) { return ((this.isShadow) ? -1 : 1); } - if (!this.relation.toUpperCase().equals(otherAug.relation.toUpperCase())) { + if (!this.relation.equals(otherAug.relation)) { return (this.relation.compareToIgnoreCase(otherAug.relation)); } throw new IllegalStateException(); } - @Override + public boolean equals(Object other) { if (other == null) { return (false); @@ -340,15 +299,13 @@ public boolean equals(Object other) { return (false); } - return (this.relation.toUpperCase().equals(otherAug.relation.toUpperCase())); + return (this.relation.equals(otherAug.relation)); } - - @Override + public int hashCode() { - return (relation.toUpperCase().hashCode() + ((isShadow) ? 17 : 31)); + return (relation.hashCode() + ((isShadow) ? 17 : 31)); } - @Override public String toString() { return ("rel = " + relation + " isShadow = " + isShadow); } diff --git a/src/org/systemsbiology/biofabric/ui/display/FabricLocation.java b/src/org/systemsbiology/biotapestry/biofabric/FabricLocation.java similarity index 85% rename from src/org/systemsbiology/biofabric/ui/display/FabricLocation.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricLocation.java index ed27b5e..d20807f 100644 --- a/src/org/systemsbiology/biofabric/ui/display/FabricLocation.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricLocation.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.display; +package org.systemsbiology.biotapestry.biofabric; import java.awt.Color; import java.awt.GridBagConstraints; @@ -25,7 +25,7 @@ import javax.swing.JLabel; import javax.swing.JPanel; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.UiUtil; /**************************************************************************** ** @@ -39,8 +39,6 @@ public class FabricLocation extends JPanel { // PRIVATE CONSTANTS // //////////////////////////////////////////////////////////////////////////// - - private static final long serialVersionUID = 1L; //////////////////////////////////////////////////////////////////////////// // @@ -99,11 +97,10 @@ public FabricLocation() { ** Drawing routine */ - public void setNodeAndLink(BioFabricPanel.MouseLocInfo mlo) { - UiUtil.fixMePrintout("This baby is causing e.g. *magnifier* validation on EVERY mouse move!"); - nodeName_.setText("Mouse Over Node Row: " + mlo.nodeDesc); - linkName_.setText("Mouse Over Link: " + mlo.linkDesc); - linkZone_.setText("Mouse Over Node Link Zone: " + mlo.zoneDesc); + public void setNodeAndLink(String nodeName, String linkName, String drainZone) { + nodeName_.setText("Mouse Over Node Row: " + nodeName); + linkName_.setText("Mouse Over Link: " + linkName); + linkZone_.setText("Mouse Over Node Link Zone: " + drainZone); nodeName_.invalidate(); linkName_.invalidate(); linkZone_.invalidate(); diff --git a/src/org/systemsbiology/biofabric/ui/display/FabricMagnifier.java b/src/org/systemsbiology/biotapestry/biofabric/FabricMagnifier.java similarity index 84% rename from src/org/systemsbiology/biofabric/ui/display/FabricMagnifier.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricMagnifier.java index a328a8e..c99d2c1 100644 --- a/src/org/systemsbiology/biofabric/ui/display/FabricMagnifier.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricMagnifier.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.display; +package org.systemsbiology.biotapestry.biofabric; import java.awt.AlphaComposite; import java.awt.BasicStroke; @@ -33,13 +33,6 @@ import java.awt.image.BufferedImage; import javax.swing.JPanel; -import org.systemsbiology.biofabric.ui.FabricColorGenerator; -import org.systemsbiology.biofabric.ui.FabricDisplayOptions; -import org.systemsbiology.biofabric.ui.FabricDisplayOptionsManager; -import org.systemsbiology.biofabric.ui.render.PaintCache; -import org.systemsbiology.biofabric.ui.render.PaintCache.FloaterSet; -import org.systemsbiology.biofabric.util.UiUtil; - /**************************************************************************** ** ** This is the magnifying glass! @@ -49,14 +42,15 @@ public class FabricMagnifier extends JPanel { //////////////////////////////////////////////////////////////////////////// // - // PUBLIC CONSTANTS + // PRIVATE CONSTANTS // //////////////////////////////////////////////////////////////////////////// - public static final int PREF_SIZE = 10; - public static final int MIN_SIZE = 2; - public static final int MAX_SIZE = 10; - public static final int MAG_GRID = 20; + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // @@ -64,14 +58,15 @@ public class FabricMagnifier extends JPanel { // //////////////////////////////////////////////////////////////////////////// - private int miniSize_; - private boolean needInit_; + private int miniCols_; + private int miniRows_; private PaintCache painter_; private PaintCache selectionPainter_; private AffineTransform miniTrans_; private Rectangle worldRec_; private Rectangle clipRec_; private Point2D center_; + private Point2D viewCenter_; private Point centerRC_; private boolean ignore_; private boolean mouseIn_; @@ -79,8 +74,6 @@ public class FabricMagnifier extends JPanel { private BioFabricOverview bfo_; private BufferedImage bim_; private PaintCache.FloaterSet floaters_; - private int currSize_; - private static final long serialVersionUID = 1L; //////////////////////////////////////////////////////////////////////////// // @@ -94,13 +87,13 @@ public class FabricMagnifier extends JPanel { */ public FabricMagnifier(FabricColorGenerator colGen) { - currSize_ = PREF_SIZE; - miniSize_ = PREF_SIZE; + miniCols_ = 10; + miniRows_ = 10; ignore_ = false; byTour_ = false; mouseIn_ = false; - needInit_ = true; center_ = new Point2D.Double(0.0, 0.0); + viewCenter_ = new Point2D.Double(0.0, 0.0); centerRC_ = new Point(0, 0); miniTrans_ = new AffineTransform(); setBackground(Color.white); @@ -134,40 +127,19 @@ public void setFabricOverview(BioFabricOverview bfo) { return; } - /*************************************************************************** - ** - ** Set the size. The value coming in the door is the number of rows & cols - ** at maximum magnification. - */ - - public void setCurrSize(int size) { - if ((size == miniSize_) && !needInit_) { - return; - } - needInit_ = false; - int oldSize = miniSize_; - miniSize_ = (size < MIN_SIZE) ? MIN_SIZE : size; - int newCurr = (currSize_ / oldSize) * miniSize_; - setZoom(newCurr); - return; - } - /*************************************************************************** ** ** Sizing */ - @Override public Dimension getPreferredSize() { - return (new Dimension(miniSize_ * MAG_GRID, miniSize_ * MAG_GRID)); + return (new Dimension(200, 200)); } - @Override public Dimension getMinimumSize() { - return (new Dimension(miniSize_ * MAG_GRID, miniSize_ * MAG_GRID)); + return (getPreferredSize()); } - @Override public Dimension getMaximumSize() { return (getPreferredSize()); } @@ -177,10 +149,8 @@ public Dimension getMaximumSize() { ** Set bounds */ - @Override public void setBounds(int x, int y, int width, int height) { super.setBounds(x, y, width, height); - setMiniZoom(); repaint(); return; } @@ -190,7 +160,6 @@ public void setBounds(int x, int y, int width, int height) { ** Paint */ - @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; @@ -204,9 +173,9 @@ public void paintComponent(Graphics g) { */ public void bumpGridSize(boolean up) { - int newSize = (up) ? currSize_ * 2 : currSize_ / 2; - if (newSize < miniSize_) { - newSize = miniSize_; + int newSize = (up) ? miniCols_ * 2 : miniCols_ / 2; + if (newSize < 10) { + newSize = 10; } setZoom(newSize); return; @@ -228,7 +197,7 @@ public void toggleFreeze() { */ public void up() { - int inc = getZoom() / currSize_; + int inc = getZoom() / 10; centerRC_.y -= inc; center_.setLocation(center_.getX(), center_.getY() - (BioFabricPanel.GRID_SIZE * inc)); setMiniZoom(); @@ -242,7 +211,7 @@ public void up() { */ public void down() { - int inc = getZoom() / currSize_; + int inc = getZoom() / 10; centerRC_.y += inc; center_.setLocation(center_.getX(), center_.getY() + (BioFabricPanel.GRID_SIZE * inc)); setMiniZoom(); @@ -256,7 +225,7 @@ public void down() { */ public void left() { - int inc = getZoom() / currSize_; + int inc = getZoom() / 10; centerRC_.x -= inc; center_.setLocation(center_.getX() - (BioFabricPanel.GRID_SIZE * inc), center_.getY()); setMiniZoom(); @@ -270,7 +239,7 @@ public void left() { */ public void right() { - int inc = getZoom() / currSize_; + int inc = getZoom() / 10; centerRC_.x += inc; center_.setLocation(center_.getX() + (BioFabricPanel.GRID_SIZE * inc), center_.getY()); setMiniZoom(); @@ -284,7 +253,8 @@ public void right() { */ public void setZoom(int gridsize) { - currSize_ = gridsize; + miniCols_ = gridsize; + miniRows_ = gridsize; setMiniZoom(); repaint(); return; @@ -296,7 +266,7 @@ public void setZoom(int gridsize) { */ public int getZoom() { - return (currSize_); + return (miniCols_); } /*************************************************************************** @@ -364,8 +334,8 @@ public void setMouseIn(boolean isIn) { public void setMiniZoom() { Dimension screenDim = getSize(); - int worldWidth = (currSize_ * BioFabricPanel.GRID_SIZE); - int worldHeight = (currSize_ * BioFabricPanel.GRID_SIZE); + int worldWidth = (miniCols_ * BioFabricPanel.GRID_SIZE); + int worldHeight = (miniRows_ * BioFabricPanel.GRID_SIZE); worldRec_ = new Rectangle((int)center_.getX() - (worldWidth / 2), (int)center_.getY() - (worldHeight / 2), worldWidth, worldHeight); @@ -417,8 +387,7 @@ private void drawingGuts(Graphics g) { painter_.paintIt(g2, true, clipRec_, false); g2.setTransform(saveTrans); if (selectionPainter_.needToPaint()) { - UiUtil.fixMePrintout("THIS IS NEEDED"); - // drawSelections(g2, clipRec_); + drawSelections(g2, clipRec_); } if (floaters_ != null) { g2.transform(miniTrans_); diff --git a/src/org/systemsbiology/biofabric/ui/display/FabricMagnifyingTool.java b/src/org/systemsbiology/biotapestry/biofabric/FabricMagnifyingTool.java similarity index 78% rename from src/org/systemsbiology/biofabric/ui/display/FabricMagnifyingTool.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricMagnifyingTool.java index 25eba1d..926416b 100644 --- a/src/org/systemsbiology/biofabric/ui/display/FabricMagnifyingTool.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricMagnifyingTool.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2017 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.display; +package org.systemsbiology.biotapestry.biofabric; import java.awt.BasicStroke; import java.awt.CardLayout; @@ -54,15 +54,10 @@ import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.ui.FabricColorGenerator; -import org.systemsbiology.biofabric.ui.FabricDisplayOptionsManager; -import org.systemsbiology.biofabric.ui.render.PaintCache; -import org.systemsbiology.biofabric.util.ColorListRenderer; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.MinMax; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.ColorListRenderer; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.MinMax; +import org.systemsbiology.biotapestry.util.UiUtil; /**************************************************************************** @@ -78,8 +73,6 @@ public class FabricMagnifyingTool extends JPanel { // //////////////////////////////////////////////////////////////////////////// - private static final float TOP_LINK_SPACING_ = 12.0F; - //////////////////////////////////////////////////////////////////////////// // // PUBLIC CONSTANTS @@ -107,11 +100,9 @@ public class FabricMagnifyingTool extends JPanel { private boolean byTour_; private boolean accept_; private Point2D mouseCenter_; - private int currSize_; - private boolean neverSet_; + private JPanel hidingPanel_; private CardLayout myCard_; - private static final long serialVersionUID = 1L; //////////////////////////////////////////////////////////////////////////// // @@ -129,7 +120,6 @@ public FabricMagnifyingTool(FabricColorGenerator colGen) { colGen_ = colGen; ignore_ = false; accept_ = true; - neverSet_ = true; lockPanel_ = new JPanel(); Font micro = new Font("SansSerif", Font.PLAIN, 10); lockStatus_ = new JLabel("Tracking", JLabel.CENTER); @@ -144,7 +134,7 @@ public FabricMagnifyingTool(FabricColorGenerator colGen) { toPan.setFont(micro); JLabel toPan2 = new JLabel("Pan: \u2190,\u2191,\u2193,\u2192", JLabel.CENTER); toPan2.setFont(micro); - lockPanel_.setLayout(new GridLayout(0,1)); + lockPanel_.setLayout(new GridLayout(5,1)); lockPanel_.add(lockStatus_); lockPanel_.add(toLock_); lockPanel_.add(toZoom); @@ -153,14 +143,31 @@ public FabricMagnifyingTool(FabricColorGenerator colGen) { myMag_ = new FabricMagnifier(colGen); myMag_.addMouseListener(new MouseHandler()); nodeLabels_ = new NodeLabels(); - topLinkLabels_ = new LinkLabels(); + topLinkLabels_= new LinkLabels(); linkDisplay_ = new LinkDisplay(); myMag_.setFocusable(true); mouseIn_ = false; byTour_ = false; - currSize_ = FabricMagnifier.PREF_SIZE; - JPanel realGuts = sizeGuts(currSize_); + JPanel realGuts = new JPanel(); + + realGuts.setLayout(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + + UiUtil.gbcSet(gbc, 0, 0, 10, 14, UiUtil.BO, 0, 0, 0, 0, 0, 0, UiUtil.N, 0.5, 0.0); + realGuts.add(lockPanel_, gbc); + + UiUtil.gbcSet(gbc, 10, 0, 45, 14, UiUtil.HOR, 0, 0, 0, 0, 0, 0, UiUtil.CEN, 0.5, 0.0); + realGuts.add(topLinkLabels_, gbc); + + UiUtil.gbcSet(gbc, 0, 14, 10, 20, UiUtil.HOR, 0, 0, 0, 0, 0, 0, UiUtil.CEN, 0.5, 0.0); + realGuts.add(nodeLabels_, gbc); + + UiUtil.gbcSet(gbc, 10, 14, 20, 20, UiUtil.NONE, 0, 0, 0, 0, 0, 0, UiUtil.CEN, 0.0, 0.0); + realGuts.add(myMag_, gbc); + + UiUtil.gbcSet(gbc, 30, 14, 25, 20, UiUtil.BO, 0, 0, 0, 0, 0, 0, UiUtil.CEN, 0.5, 0.0); + realGuts.add(linkDisplay_, gbc); myCard_ = new CardLayout(); setLayout(myCard_); @@ -227,7 +234,6 @@ public void keyInstall(JPanel cpane) { iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, KeyEvent.CTRL_DOWN_MASK), "MagnifyFreeze"); aMap.put("MagnifyFreeze", new AbstractAction() { - private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { if (!accept_) { @@ -252,7 +258,6 @@ public void actionPerformed(ActionEvent e) { iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, 0), "MagnifyMore"); iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, 0), "MagnifyMore"); aMap.put("MagnifyMore", new AbstractAction() { - private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { if (!accept_) { @@ -270,7 +275,6 @@ public void actionPerformed(ActionEvent e) { iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, 0), "MagnifyLess"); iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, 0), "MagnifyLess"); aMap.put("MagnifyLess", new AbstractAction() { - private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { if (!accept_) { @@ -290,7 +294,6 @@ public void actionPerformed(ActionEvent e) { iMapf.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "MagnifyUp"); iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "MagnifyUp"); aMap.put("MagnifyUp", new AbstractAction() { - private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { if (!accept_) { @@ -309,7 +312,6 @@ public void actionPerformed(ActionEvent e) { iMapf.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "MagnifyDown"); iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, 0), "MagnifyDown"); aMap.put("MagnifyDown", new AbstractAction() { - private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { if (!accept_) { @@ -328,7 +330,6 @@ public void actionPerformed(ActionEvent e) { iMapf.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "MagnifyLeft"); iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "MagnifyLeft"); aMap.put("MagnifyLeft", new AbstractAction() { - private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { if (!accept_) { @@ -347,7 +348,6 @@ public void actionPerformed(ActionEvent e) { iMapf.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "MagnifyRight"); iMapw.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "MagnifyRight"); aMap.put("MagnifyRight", new AbstractAction() { - private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { if (!accept_) { @@ -370,23 +370,16 @@ public void actionPerformed(ActionEvent e) { ** Sizing */ - @Override public Dimension getPreferredSize() { - return (getMinimumSize()); + return (new Dimension(550, 340)); } - @Override public Dimension getMinimumSize() { - if (neverSet_) { - return (new Dimension(550, (2 * (FabricMagnifier.PREF_SIZE * FabricMagnifier.MAG_GRID)))); - } else { - return (new Dimension(550, (2 * (FabricMagnifier.MIN_SIZE * FabricMagnifier.MAG_GRID)))); - } + return (getPreferredSize()); } - @Override public Dimension getMaximumSize() { - return (new Dimension(4000, (2 * (FabricMagnifier.MAX_SIZE * FabricMagnifier.MAG_GRID)) + 40)); + return (new Dimension(4000, 340)); } /*************************************************************************** @@ -414,13 +407,8 @@ public void setModel(BioFabricNetwork model) { ** */ - @Override public void setBounds(int x, int y, int width, int height) { - neverSet_ = false; - currSize_ = (int)Math.floor(height / (FabricMagnifier.MAG_GRID + TOP_LINK_SPACING_)); - myMag_.setCurrSize(currSize_); super.setBounds(x, y, width, height); - linkSync(); repaint(); return; } @@ -466,11 +454,11 @@ public void setMouseIn(boolean isIn) { */ public void linkSync() { - List links; + List links; if (model_ != null) { links = linkDisplay_.calcLinks(); } else { - links = new ArrayList(); + links = new ArrayList(); } linkDisplay_.setLinks(links); return; @@ -503,68 +491,6 @@ public Rectangle getClipRect() { public Point2D getMouseLoc() { return (mouseCenter_); } - - //////////////////////////////////////////////////////////////////////////// - // - // PRIVATE METHODS - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Set sizing - */ - - private JPanel sizeGuts(int magSize) { - - JPanel realGuts = new JPanel(); - - realGuts.setLayout(new GridBagLayout()); - GridBagConstraints gbc = new GridBagConstraints(); - - // - // NOTE NO GROWTH ALLOWED IN VERTICAL DIRECTION. - // Dividing real dims by 10 to make GridBag happy... - // - // 10C x 14R - int col = 0; - int row = 0; - int wth = 10; - int ht = (int)Math.ceil((((magSize + 1) * TOP_LINK_SPACING_) / 10) + 4); - UiUtil.gbcSet(gbc, col, row, wth, ht, UiUtil.BO, 0, 0, 0, 0, 0, 0, UiUtil.N, 0.25, 0.0); - realGuts.add(lockPanel_, gbc); - - // 45C x 14R - col = wth; - row = 0; - wth = 45; - ht = (int)Math.ceil((((magSize + 1) * TOP_LINK_SPACING_) / 10) + 4); - UiUtil.gbcSet(gbc, col, row, wth, ht, UiUtil.BO, 0, 0, 0, 0, 0, 0, UiUtil.SW, 0.75, 0.0); - realGuts.add(topLinkLabels_, gbc); - - // 10C x 20R - col = 0; - row = ht; - wth = 10; - ht = (magSize * FabricMagnifier.MAG_GRID) / 10; - UiUtil.gbcSet(gbc, col, row, wth, ht, UiUtil.BO, 0, 0, 0, 0, 0, 0, UiUtil.CEN, 0.25, 0.0); - realGuts.add(nodeLabels_, gbc); - - // 20C x 20R NO GROWTH AT ALL! - col = wth; - wth = (magSize * FabricMagnifier.MAG_GRID) / 10; - ht = (magSize * FabricMagnifier.MAG_GRID) / 10; - UiUtil.gbcSet(gbc, col, row, wth, ht, UiUtil.NONE, 0, 0, 0, 0, 0, 0, UiUtil.CEN, 0.0, 0.0); - realGuts.add(myMag_, gbc); - - // 25C x 20R - col = col + wth; - wth = 45 - wth; - ht = (magSize * FabricMagnifier.MAG_GRID) / 10; - UiUtil.gbcSet(gbc, col, row, wth, ht, UiUtil.BO, 0, 0, 0, 0, 0, 0, UiUtil.CEN, 0.75, 0.0); - realGuts.add(linkDisplay_, gbc); - return (realGuts); - } /*************************************************************************** ** @@ -572,24 +498,19 @@ private JPanel sizeGuts(int magSize) { */ private class NodeLabels extends JPanel { - private static final long serialVersionUID = 1L; - NodeLabels() { setBackground(new Color(245, 245, 245)); } - @Override public Dimension getPreferredSize() { - return (new Dimension(100, (currSize_ * FabricMagnifier.MAG_GRID))); + return (new Dimension(100, 200)); } - @Override public Dimension getMinimumSize() { - return (new Dimension(100, 10)); + return (getPreferredSize()); } - @Override public Dimension getMaximumSize() { - return (new Dimension(4000, (currSize_ * FabricMagnifier.MAG_GRID))); + return (new Dimension(4000, 200)); } - @Override + public void paintComponent(Graphics g) { super.paintComponent(g); if (model_ == null) { @@ -601,7 +522,7 @@ public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; Point myCen = myMag_.getCenterRC(); int myZoom = myMag_.getZoom(); - if (myZoom != currSize_) { + if (myZoom != 10) { return; } Point2D atPoint = new Point2D.Double(0.0, 0.0); @@ -611,20 +532,20 @@ public void paintComponent(Graphics g) { g2.setFont(tiny_); g2.setPaint(Color.BLACK); FontRenderContext frc = g2.getFontRenderContext(); - int startCen = myCen.y - (currSize_ / 2) - 1; - int endCen = myCen.y + (currSize_ / 2) + 1; + int startCen = myCen.y - 6; + int endCen = myCen.y + 6; for (int i = startCen; i <= endCen; i++) { - NID.WithName node = model_.getNodeIDForRow(Integer.valueOf(i)); + String node = model_.getNodeForRow(new Integer(i)); if (node == null) { continue; } BioFabricNetwork.NodeInfo ni = model_.getNodeDefinition(node); MinMax nimm = ni.getColRange(showShadows); - if ((nimm.min <= myCen.x + (currSize_ / 2)) && (nimm.max >= myCen.x - (currSize_ / 2))) { - Rectangle2D bounds = tiny_.getStringBounds(node.getName(), frc); + if ((nimm.min <= myCen.x + 5) && (nimm.max >= myCen.x - 5)) { + Rectangle2D bounds = tiny_.getStringBounds(node, frc); atPoint.setLocation(0.0, (double)(i * BioFabricPanel.GRID_SIZE)); ac.transform(atPoint, drawPoint); - g2.drawString(node.getName(), getWidth() - (float)bounds.getWidth() - 5.0F, (float)drawPoint.getY() + ((float)bounds.getHeight() / 3.0F)); + g2.drawString(node, getWidth() - (float)bounds.getWidth() - 5.0F, (float)drawPoint.getY() + ((float)bounds.getHeight() / 3.0F)); } } return; @@ -637,22 +558,20 @@ public void paintComponent(Graphics g) { */ private class LinkLabels extends JPanel { - private static final long serialVersionUID = 1L; LinkLabels() { setBackground(new Color(245, 245, 245)); } - @Override public Dimension getPreferredSize() { - return (new Dimension(450, (int)((currSize_ + 1) * TOP_LINK_SPACING_))); + return (new Dimension(450, 140)); } - @Override + public Dimension getMinimumSize() { - return (new Dimension(450, (int)((currSize_ + 1) * TOP_LINK_SPACING_))); + return (getPreferredSize()); } public Dimension getMaximumSize() { - return (new Dimension(4000, (int)((currSize_ + 1) * TOP_LINK_SPACING_))); + return (new Dimension(4000, 140)); } public void paintComponent(Graphics g) { super.paintComponent(g); @@ -665,7 +584,7 @@ public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; Point myCen = myMag_.getCenterRC(); int myZoom = myMag_.getZoom(); - if (myZoom != currSize_) { + if (myZoom != 10) { return; } boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); @@ -678,26 +597,26 @@ public void paintComponent(Graphics g) { FontRenderContext frc = g2.getFontRenderContext(); int numCol = model_.getColumnCount(showShadows); - int startCen = myCen.x - (currSize_ / 2); + int startCen = myCen.x - 5; if (startCen < 0) { startCen = 0; } if (startCen >= numCol) { return; } - int endCen = myCen.x + (currSize_ / 2); + int endCen = myCen.x + 5; if (endCen >= numCol) { endCen = numCol - 1; } int count = -1; - float deltaY = TOP_LINK_SPACING_; - float startY = TOP_LINK_SPACING_; + float deltaY = 12.0F; + float startY = 12.0F; for (int i = startCen; i <= endCen; i++) { count++; - Integer colObj = Integer.valueOf(i); - NID.WithName src = model_.getSourceIDForColumn(colObj, showShadows); - NID.WithName trg = model_.getTargetIDForColumn(colObj, showShadows); + Integer colObj = new Integer(i); + String src = model_.getSourceForColumn(colObj, showShadows); + String trg = model_.getTargetForColumn(colObj, showShadows); if ((src == null) || (trg == null)) { continue; } @@ -708,11 +627,10 @@ public void paintComponent(Graphics g) { int minRow = li.topRow(); int maxRow = li.bottomRow(); - UiUtil.fixMePrintout("Mother Plutarch Mabeuf (rightmost) link not appearing in clustered LesMiz"); - if ((minRow <= (myCen.y + (currSize_ / 2))) && (maxRow >= (myCen.y - (currSize_ / 2)))) { + if ((minRow <= (myCen.y + 5)) && (maxRow >= (myCen.y - 5))) { String linkDisp = li.getLink().toDisplayString(); Rectangle2D bounds = tiny_.getStringBounds(linkDisp, frc); - atPoint.setLocation((i * BioFabricPanel.GRID_SIZE), 0.0); + atPoint.setLocation((double)(i * BioFabricPanel.GRID_SIZE), 0.0); ac.transform(atPoint, drawPoint); //float baseptX = nodeLabels_.getWidth() + (float)drawPoint.getX(); // if ((baseptX < nodeLabels_.getWidth()) || (baseptX > nodeLabels_.getWidth() + 200)) { @@ -720,7 +638,7 @@ public void paintComponent(Graphics g) { // } float baseptX = (float)drawPoint.getX(); - if ((baseptX < 0) || (baseptX > (currSize_ * FabricMagnifier.MAG_GRID))) { + if ((baseptX < 0) || (baseptX > 200)) { continue; } float baseptY = startY + (count * deltaY); @@ -728,7 +646,7 @@ public void paintComponent(Graphics g) { g2.drawString(linkDisp, baseptX + 5.0F, baseptY); Color paintCol = colGen_.getModifiedColor(li.getColorKey(), FabricColorGenerator.DARKER); float boxBaseY = baseptY - ((float)bounds.getHeight() / 3.0F); - Line2D line = new Line2D.Float(baseptX, boxBaseY, baseptX, 400.0F); + Line2D line = new Line2D.Float(baseptX, boxBaseY, baseptX, 160.F); g2.setColor(paintCol); g2.draw(line); Rectangle2D rect = new Rectangle2D.Float(baseptX - 2.0F, boxBaseY - 2.0F, 5.0F, 5.0F); @@ -741,14 +659,13 @@ public void paintComponent(Graphics g) { /*************************************************************************** ** - ** Displays all the links in a JList + ** Labels the links */ private class LinkDisplay extends JPanel { private JList linkList_; private ColorListRenderer renderer_; - private static final long serialVersionUID = 1L; LinkDisplay() { ArrayList myList = new ArrayList(); @@ -764,26 +681,26 @@ private class LinkDisplay extends JPanel { } public Dimension getPreferredSize() { - return (new Dimension(250, (currSize_ * FabricMagnifier.MAG_GRID))); + return (new Dimension(250, 200)); } public Dimension getMinimumSize() { - return (new Dimension(200, (currSize_ * FabricMagnifier.MAG_GRID))); + return (getPreferredSize()); } public Dimension getMaximumSize() { - return (new Dimension(4000, (currSize_ * FabricMagnifier.MAG_GRID))); + return (new Dimension(4000, 200)); } - public void setLinks(List links) { + public void setLinks(List links) { linkList_.clearSelection(); linkList_.setListData(links.toArray()); renderer_.setValues(links); return; } - public List calcLinks() { - ArrayList list = new ArrayList(); + public List calcLinks() { + ArrayList list = new ArrayList(); if (!mouseIn_ && !byTour_ && !ignore_) { return (list); } @@ -796,8 +713,8 @@ public List calcLinks() { boolean showShadows = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getDisplayShadows(); for (int i = startCen; i <= endCen; i++) { - Integer colObj = Integer.valueOf(i); - NID.WithName src = model_.getSourceIDForColumn(colObj, showShadows); + Integer colObj = new Integer(i); + String src = model_.getSourceForColumn(colObj, showShadows); if (src == null) { continue; } @@ -844,7 +761,7 @@ public String getDescription(){ /*************************************************************************** ** - ** Handles click events WHY IS THIS EVEN HERE???? + ** Handles click events */ public class MouseHandler extends MouseAdapter { diff --git a/src/org/systemsbiology/biotapestry/biofabric/FabricNavTool.java b/src/org/systemsbiology/biotapestry/biofabric/FabricNavTool.java new file mode 100644 index 0000000..c15024b --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricNavTool.java @@ -0,0 +1,513 @@ +/* +** Copyright (C) 2003-2011 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + +import java.awt.Color; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.Box; +import javax.swing.JCheckBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.border.EmptyBorder; + +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ResourceManager; + + +/**************************************************************************** +** +** This is the navigator +*/ + +public class FabricNavTool extends JPanel { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE MEMBERS + // + //////////////////////////////////////////////////////////////////////////// + + private BioFabricPanel bfp_; + private FixedJButton startAtCurrent_; + private FixedJButton chooseAStart_; + private JLabel nodeName_; + private JLabel linkName_; + private FixedJButton buttonUp_; + private FixedJButton buttonRight_; + private FixedJButton buttonFarRight_; + private FixedJButton buttonLeft_; + private FixedJButton buttonFarLeft_; + private FixedJButton buttonDown_; + private FixedJButton buttonZoom_; + private FixedJButton buttonLinkZone_; + private FixedJButton buttonClear_; + private JCheckBox selectedOnly_; + private BioFabricPanel.TourStatus currTstat_; + private boolean haveSelection_; + private boolean haveAModel_; + private boolean controlsEnabled_; + private JFrame topWindow_; + private boolean doSOReset_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Constructor + */ + + public FabricNavTool(JFrame topWindow) { + ResourceManager rMan = ResourceManager.getManager(); + + setBorder(new EmptyBorder(20, 20, 20, 20)); + setLayout(new GridLayout(1, 1)); + setBackground(Color.WHITE); + nodeName_ = new JLabel("", JLabel.CENTER); + linkName_ = new JLabel("", JLabel.CENTER); + controlsEnabled_ = true; + topWindow_ = topWindow; + doSOReset_ = false; + + startAtCurrent_ = new FixedJButton(rMan.getString("navTool.startAtCurrent")); + startAtCurrent_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + BioFabricPanel.TourStatus tstat = bfp_.startTourFromSelection(calcSelectedOnly()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + startAtCurrent_.setEnabled(false); + + chooseAStart_ = new FixedJButton(rMan.getString("navTool.chooseAStart")); + chooseAStart_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + bfp_.setToCollectTourStart(calcSelectedOnly()); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + chooseAStart_.setEnabled(false); + haveAModel_ = false; + + buttonUp_ = new FixedJButton(rMan.getString("navTool.up")); + buttonUp_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + BioFabricPanel.TourStatus tstat = bfp_.goUp(calcSelectedOnly()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + buttonRight_ = new FixedJButton(rMan.getString("navTool.right")); + buttonRight_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + BioFabricPanel.TourStatus tstat = bfp_.goRight(calcSelectedOnly()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + buttonFarRight_ = new FixedJButton(">>"); + buttonFarRight_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + BioFabricPanel.TourStatus tstat = bfp_.goFarRight(calcSelectedOnly()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + buttonLeft_ = new FixedJButton(rMan.getString("navTool.left")); + buttonLeft_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + BioFabricPanel.TourStatus tstat = bfp_.goLeft(calcSelectedOnly()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + buttonFarLeft_ = new FixedJButton("<<"); + buttonFarLeft_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + BioFabricPanel.TourStatus tstat = bfp_.goFarLeft(calcSelectedOnly()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + buttonDown_ = new FixedJButton(rMan.getString("navTool.down")); + buttonDown_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + BioFabricPanel.TourStatus tstat = bfp_.goDown(calcSelectedOnly()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + buttonClear_ = new FixedJButton(rMan.getString("navTool.clear")); + buttonClear_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + bfp_.clearTour(); + clearTour(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + buttonZoom_ = new FixedJButton(rMan.getString("navTool.zoom")); + buttonZoom_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + bfp_.zoomToTourStop(); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + buttonLinkZone_ = new FixedJButton(rMan.getString("navTool.dropZone")); + buttonLinkZone_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + BioFabricPanel.TourStatus tstat = bfp_.tourToDrainZone(calcSelectedOnly()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + + selectedOnly_ = new JCheckBox(rMan.getString("navTool.skip")); + selectedOnly_.setOpaque(true); + selectedOnly_.setBackground(Color.white); + selectedOnly_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + try { + if (doSOReset_) { + return; + } + if ((currTstat_ != null) && (currTstat_.currStopUnselected) && selectedOnly_.isSelected()) { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(topWindow_, rMan.getString("navTool.currLocUnselected"), + rMan.getString("navTool.currLocUnselectedTitle"), + JOptionPane.ERROR_MESSAGE); + doSOReset_ = true; + selectedOnly_.setSelected(false); + doSOReset_ = false; + return; + } + BioFabricPanel.TourStatus tstat = bfp_.getTourDirections(selectedOnly_.isSelected()); + installNames(tstat); + } catch (Exception ex) { + ExceptionHandler.getHandler().displayException(ex); + } + } + }); + haveSelection_ = false; + selectedOnly_.setEnabled(false); + + + Box cbuttonPanel = Box.createHorizontalBox(); + cbuttonPanel.add(Box.createHorizontalGlue()); + cbuttonPanel.add(startAtCurrent_); + cbuttonPanel.add(Box.createHorizontalStrut(10)); + cbuttonPanel.add(chooseAStart_); + cbuttonPanel.add(Box.createHorizontalGlue()); + + Box nodePanel = Box.createHorizontalBox(); + nodePanel.add(Box.createHorizontalStrut(10)); + nodePanel.add(nodeName_); + nodePanel.add(Box.createHorizontalStrut(10)); + + Box linkPanel = Box.createHorizontalBox(); + linkPanel.add(Box.createHorizontalStrut(10)); + linkPanel.add(linkName_); + linkPanel.add(Box.createHorizontalStrut(10)); + + Box dbuttonPanel = Box.createHorizontalBox(); + dbuttonPanel.add(Box.createHorizontalGlue()); + dbuttonPanel.add(buttonUp_); + dbuttonPanel.add(Box.createHorizontalGlue()); + + Box ebuttonPanel = Box.createHorizontalBox(); + ebuttonPanel.add(Box.createHorizontalGlue()); + ebuttonPanel.add(buttonFarLeft_); + ebuttonPanel.add(Box.createHorizontalStrut(10)); + ebuttonPanel.add(buttonLeft_); + ebuttonPanel.add(Box.createHorizontalStrut(10)); + ebuttonPanel.add(buttonRight_); + ebuttonPanel.add(Box.createHorizontalStrut(10)); + ebuttonPanel.add(buttonFarRight_); + ebuttonPanel.add(Box.createHorizontalGlue()); + + Box fbuttonPanel = Box.createHorizontalBox(); + fbuttonPanel.add(Box.createHorizontalGlue()); + fbuttonPanel.add(buttonDown_); + fbuttonPanel.add(Box.createHorizontalGlue()); + + Box hbuttonPanel = Box.createHorizontalBox(); + hbuttonPanel.add(Box.createHorizontalGlue()); + hbuttonPanel.add(buttonClear_); + hbuttonPanel.add(Box.createHorizontalStrut(10)); + hbuttonPanel.add(buttonZoom_); + hbuttonPanel.add(Box.createHorizontalStrut(10)); + hbuttonPanel.add(buttonLinkZone_); + hbuttonPanel.add(Box.createHorizontalGlue()); + + Box ibuttonPanel = Box.createHorizontalBox(); + ibuttonPanel.add(Box.createHorizontalGlue()); + ibuttonPanel.add(selectedOnly_); + ibuttonPanel.add(Box.createHorizontalGlue()); + + Box gbuttonPanel = Box.createVerticalBox(); + gbuttonPanel.add(Box.createVerticalGlue()); + gbuttonPanel.add(cbuttonPanel); + gbuttonPanel.add(Box.createVerticalStrut(10)); + gbuttonPanel.add(nodePanel); + gbuttonPanel.add(Box.createVerticalStrut(10)); + gbuttonPanel.add(linkPanel); + gbuttonPanel.add(Box.createVerticalStrut(10)); + gbuttonPanel.add(dbuttonPanel); + gbuttonPanel.add(Box.createVerticalStrut(10)); + gbuttonPanel.add(dbuttonPanel); + gbuttonPanel.add(Box.createVerticalStrut(10)); + gbuttonPanel.add(ebuttonPanel); + gbuttonPanel.add(Box.createVerticalStrut(10)); + gbuttonPanel.add(fbuttonPanel); + gbuttonPanel.add(Box.createVerticalStrut(10)); + gbuttonPanel.add(hbuttonPanel); + gbuttonPanel.add(Box.createVerticalStrut(10)); + gbuttonPanel.add(ibuttonPanel); + gbuttonPanel.add(Box.createVerticalGlue()); + + add(gbuttonPanel); + clearTour(); + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Reset the skip selections + */ + + public void resetSkipSelections() { + selectedOnly_.setSelected(false); + return; + } + + /*************************************************************************** + ** + ** Enable or disable the panel + */ + + public void enableControls(boolean enabled) { + controlsEnabled_ = enabled; + if (!enabled) { + disableControls(); + } else { + syncToState(); + } + return; + } + + /*************************************************************************** + ** + ** Let us know we have a model + */ + + public void haveAModel(boolean haveIt) { + haveAModel_ = haveIt; + chooseAStart_.setEnabled(controlsEnabled_ && haveAModel_); + if (!haveAModel_) { + currTstat_ = null; + disableControls(); + } + repaint(); + return; + } + /*************************************************************************** + ** + ** Let us know we have a selection + */ + + public void haveASelection(boolean haveIt) { + startAtCurrent_.setEnabled(haveIt); + selectedOnly_.setEnabled(haveIt); + if (currTstat_ != null) { + currTstat_.currStopUnselected = bfp_.tourStopNowUnselected(); + } + haveSelection_ = haveIt; + repaint(); + return; + } + + /*************************************************************************** + ** + ** Enable/disable tour + */ + + private void clearTour() { + nodeName_.setText(""); + nodeName_.invalidate(); + linkName_.setText(""); + linkName_.invalidate(); + revalidate(); + disableControls(); + return; + } + + /*************************************************************************** + ** + ** Give valid answer to use selected only + */ + + private boolean calcSelectedOnly() { + return (selectedOnly_.isEnabled() && selectedOnly_.isSelected()); + } + + /*************************************************************************** + ** + ** Drawing routine + */ + + public void setFabricPanel(BioFabricPanel bfp) { + bfp_ = bfp; + return; + } + + /*************************************************************************** + ** + ** install Names + */ + + public void installNames(BioFabricPanel.TourStatus tstat) { + if (tstat == null) { + return; + } + currTstat_ = (BioFabricPanel.TourStatus)tstat.clone(); + syncToState(); + return; + } + + /*************************************************************************** + ** + ** Enable/disable tour + */ + + private void disableControls() { + buttonUp_.setEnabled(false); + buttonRight_.setEnabled(false); + buttonFarRight_.setEnabled(false); + buttonLeft_.setEnabled(false); + buttonFarLeft_.setEnabled(false); + buttonDown_.setEnabled(false); + buttonClear_.setEnabled(false); + buttonZoom_.setEnabled(false); + buttonLinkZone_.setEnabled(false); + nodeName_.setEnabled(false); + linkName_.setEnabled(false); + selectedOnly_.setEnabled(false); + repaint(); + return; + } + + /*************************************************************************** + ** + ** Sync to state! + */ + + private void syncToState() { + chooseAStart_.setEnabled(haveAModel_); + if (currTstat_ == null) { + disableControls(); + return; + } + buttonZoom_.setEnabled(true); + buttonLinkZone_.setEnabled(true); + buttonClear_.setEnabled(true); + nodeName_.setEnabled(true); + linkName_.setEnabled(true); + nodeName_.setText(currTstat_.nodeName); + linkName_.setText(currTstat_.linkName); + nodeName_.invalidate(); + linkName_.invalidate(); + buttonUp_.setEnabled(currTstat_.upEnabled); + buttonRight_.setEnabled(currTstat_.rightEnabled); + buttonFarRight_.setEnabled(currTstat_.farRightEnabled); + buttonLeft_.setEnabled(currTstat_.leftEnabled); + buttonFarLeft_.setEnabled(currTstat_.farLeftEnabled); + buttonDown_.setEnabled(currTstat_.downEnabled); + selectedOnly_.setEnabled(haveSelection_); + startAtCurrent_.setEnabled(haveSelection_); + revalidate(); + repaint(); + return; + } +} diff --git a/src/org/systemsbiology/biofabric/io/FabricSIFLoader.java b/src/org/systemsbiology/biotapestry/biofabric/FabricSIFLoader.java similarity index 62% rename from src/org/systemsbiology/biofabric/io/FabricSIFLoader.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricSIFLoader.java index f231be4..49005cb 100644 --- a/src/org/systemsbiology/biofabric/io/FabricSIFLoader.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricSIFLoader.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2016 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,24 +17,17 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.io; +package org.systemsbiology.biotapestry.biofabric; -import java.io.FileInputStream; +import java.io.FileReader; import java.io.BufferedReader; import java.io.File; -import java.io.InputStreamReader; import java.util.ArrayList; -import java.util.HashMap; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.UniqueLabeller; - /**************************************************************************** ** ** This loads SIF files @@ -87,17 +80,12 @@ public FabricSIFLoader() { ** Process a SIF input */ - public SIFStats readSIF(File infile, UniqueLabeller idGen, List links, - Set loneNodeIDs, Map nameMap, Integer magBins) throws IOException { + public SIFStats readSIF(File infile, List links, Set loneNodes, Map nameMap) throws IOException { SIFStats retval = new SIFStats(); - HashMap nameToID = new HashMap(); - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(infile), "UTF-8")); - ArrayList tokSets = new ArrayList(); + BufferedReader in = new BufferedReader(new FileReader(infile)); + ArrayList tokSets = new ArrayList(); String line = null; while ((line = in.readLine()) != null) { - if (line.trim().equals("")) { - continue; - } String[] tokens = line.split("\\t"); if ((tokens.length == 1) && (line.indexOf("\\t") == -1)) { tokens = line.split(" "); @@ -113,9 +101,13 @@ public SIFStats readSIF(File infile, UniqueLabeller idGen, List link } in.close(); + // + // Build link set: + // + int numLines = tokSets.size(); for (int i = 0; i < numLines; i++) { - String[] tokens = tokSets.get(i); + String[] tokens = (String[])tokSets.get(i); if (tokens.length == 3) { String source = tokens[0].trim(); if ((source.indexOf("\"") == 0) && (source.lastIndexOf("\"") == (source.length() - 1))) { @@ -125,77 +117,39 @@ public SIFStats readSIF(File infile, UniqueLabeller idGen, List link if ((target.indexOf("\"") == 0) && (target.lastIndexOf("\"") == (target.length() - 1))) { target = target.replaceAll("\"", ""); } - // - // This name map is for the load SIF with node attributes feature: - // - if (nameMap != null) { - String mappedSource = nameMap.get(source); + String mappedSource = (String)nameMap.get(source); if (mappedSource != null) { source = mappedSource; } - String mappedTarget = nameMap.get(target); + String mappedTarget = (String)nameMap.get(target); if (mappedTarget != null) { target = mappedTarget; } } - - // - // Map the name to an ID, if none yet, get a new ID and assign it - // - - String normSrc = DataUtil.normKey(source); - String normTrg = DataUtil.normKey(target); - - NID.WithName srcID = nameToID.get(normSrc); - if (srcID == null) { - NID srcNID = idGen.getNextOID(); - srcID = new NID.WithName(srcNID, source); - nameToID.put(normSrc, srcID); - } - - NID.WithName trgID = nameToID.get(normTrg); - if (trgID == null) { - NID trgNID = idGen.getNextOID(); - trgID = new NID.WithName(trgNID, target); - nameToID.put(normTrg, trgID); - } - String rel = tokens[1].trim(); if ((rel.indexOf("\"") == 0) && (rel.lastIndexOf("\"") == (rel.length() - 1))) { rel = rel.replaceAll("\"", ""); } - - FabricLink nextLink = new FabricLink(srcID, trgID, rel, false); - links.add(nextLink); - - // We never create shadow feedback links! - if (!srcID.equals(trgID)) { - FabricLink nextShadowLink = new FabricLink(srcID, trgID, rel, true); - links.add(nextShadowLink); - } - + FabricLink nextLink = new FabricLink(source, target, rel, false); + links.add(nextLink); + // We never create shadow feedback links! + if (!source.equals(target)) { + FabricLink nextShadowLink = new FabricLink(source, target, rel, true); + links.add(nextShadowLink); + } } else { String loner = tokens[0].trim(); if ((loner.indexOf("\"") == 0) && (loner.lastIndexOf("\"") == (loner.length() - 1))) { loner = loner.replaceAll("\"", ""); } if (nameMap != null) { - String mappedLoner = nameMap.get(loner); + String mappedLoner = (String)nameMap.get(loner); if (mappedLoner != null) { loner = mappedLoner; } } - - String normLoner = DataUtil.normKey(loner); - - NID.WithName loneID = nameToID.get(normLoner); - if (loneID == null) { - NID loneNID = idGen.getNextOID(); - NID.WithName lwn = new NID.WithName(loneNID, loner); - nameToID.put(normLoner, lwn); - } - loneNodeIDs.add(loneID); + loneNodes.add(loner); } } return (retval); @@ -208,14 +162,14 @@ public SIFStats readSIF(File infile, UniqueLabeller idGen, List link //////////////////////////////////////////////////////////////////////////// public static class SIFStats { - public ArrayList badLines; + public ArrayList badLines; - public SIFStats() { - badLines = new ArrayList(); + SIFStats() { + badLines = new ArrayList(); } public void copyInto(SIFStats other) { - this.badLines = new ArrayList(other.badLines); + this.badLines = new ArrayList(other.badLines); return; } } diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/FabricSearchDialog.java b/src/org/systemsbiology/biotapestry/biofabric/FabricSearchDialog.java similarity index 91% rename from src/org/systemsbiology/biofabric/ui/dialogs/FabricSearchDialog.java rename to src/org/systemsbiology/biotapestry/biofabric/FabricSearchDialog.java index a002077..796c48a 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/FabricSearchDialog.java +++ b/src/org/systemsbiology/biotapestry/biofabric/FabricSearchDialog.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2017 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.ui.dialogs; +package org.systemsbiology.biotapestry.biofabric; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; @@ -37,15 +37,12 @@ import javax.swing.JComboBox; import javax.swing.JOptionPane; - -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.util.ChoiceContent; -import org.systemsbiology.biofabric.util.DataUtil; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.UiUtil; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ChoiceContent; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.DataUtil; /**************************************************************************** ** @@ -70,14 +67,13 @@ public class FabricSearchDialog extends JDialog { // //////////////////////////////////////////////////////////////////////////// - private static final long serialVersionUID = 1L; private JTextField stringField_; private JFrame parent_; private boolean itemFound_; private JComboBox matchTypeCombo_; private JCheckBox discardSelections_; private BioFabricNetwork bfn_; - private Set result_; + private Set result_; private boolean doDiscard_; //////////////////////////////////////////////////////////////////////////// @@ -172,7 +168,7 @@ public boolean itemWasFound() { ** */ - public Set getMatches() { + public Set getMatches() { return (result_); } @@ -242,9 +238,9 @@ private JPanel buildNodeSearchTab(boolean haveSelection, boolean buildingSelecti ** Get combo box guts */ - private Vector getMatchChoices() { + private Vector getMatchChoices() { ResourceManager rMan = ResourceManager.getManager(); - Vector retval = new Vector(); + Vector retval = new Vector(); retval.add(new ChoiceContent(rMan.getString("nsearch.fullMatch"), FULL_MATCH_)); retval.add(new ChoiceContent(rMan.getString("nsearch.partialMatch"), PARTIAL_MATCH_)); return (retval); diff --git a/src/org/systemsbiology/biofabric/ui/render/ImageCache.java b/src/org/systemsbiology/biotapestry/biofabric/ImageCache.java similarity index 86% rename from src/org/systemsbiology/biofabric/ui/render/ImageCache.java rename to src/org/systemsbiology/biotapestry/biofabric/ImageCache.java index 9ca4ff8..d51e9c7 100644 --- a/src/org/systemsbiology/biofabric/ui/render/ImageCache.java +++ b/src/org/systemsbiology/biotapestry/biofabric/ImageCache.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.render; +package org.systemsbiology.biotapestry.biofabric; import java.awt.image.BufferedImage; import java.io.File; @@ -61,9 +61,9 @@ public class ImageCache { //////////////////////////////////////////////////////////////////////////// private String cachePref_; - private HashMap imgCache_; - private HashMap handleToFile_; - private ArrayList queue_; + private HashMap imgCache_; + private HashMap handleToFile_; + private ArrayList queue_; private int nextHandle_; private int maxMeg_; private int currSize_; @@ -81,9 +81,9 @@ public class ImageCache { public ImageCache(String cachePref, int maxMeg) { cachePref_ = cachePref; - imgCache_ = new HashMap(); - handleToFile_ = new HashMap(); - queue_ = new ArrayList(); + imgCache_ = new HashMap(); + handleToFile_ = new HashMap(); + queue_ = new ArrayList(); nextHandle_ = 0; if (maxMeg == 0) { throw new IllegalArgumentException(); @@ -104,7 +104,7 @@ public ImageCache(String cachePref, int maxMeg) { */ public BufferedImage getAnImage(String handle) throws IOException { - BufferedImage retval = imgCache_.get(handle); + BufferedImage retval = (BufferedImage)imgCache_.get(handle); if (retval != null) { queue_.remove(handle); queue_.add(0, handle); @@ -115,7 +115,7 @@ public BufferedImage getAnImage(String handle) throws IOException { // Not in memory cache, look for file: // - String fileName = handleToFile_.get(handle); + String fileName = (String)handleToFile_.get(handle); if (fileName == null) { return (null); @@ -191,7 +191,7 @@ public void dropAnImage(String handle) throws IOException { queue_.remove(handle); imgCache_.remove(handle); - String fileName = handleToFile_.get(handle); + String fileName = (String)handleToFile_.get(handle); if (fileName != null) { File dropFile = new File(fileName); if (dropFile.exists()) { @@ -223,7 +223,7 @@ public String replaceAnImage(String handle, BufferedImage bi) throws IOException imgCache_.put(handle, bi); currSize_ += sizeEst; - String fileName = handleToFile_.get(handle); + String fileName = (String)handleToFile_.get(handle); if (fileName != null) { File holdFile = new File(fileName); writePNGImage(bi, holdFile); @@ -238,9 +238,9 @@ public String replaceAnImage(String handle, BufferedImage bi) throws IOException private void maintainSize(int sizeEst) throws IOException { while (((sizeEst + currSize_) > maxMeg_) && (queue_.size() > 0)) { - String goodBye = queue_.remove(queue_.size() - 1); - BufferedImage bye = imgCache_.remove(goodBye); - String fileName = handleToFile_.get(goodBye); + String goodBye = (String)queue_.remove(queue_.size() - 1); + BufferedImage bye = (BufferedImage)imgCache_.remove(goodBye); + String fileName = (String)handleToFile_.get(goodBye); if (fileName == null) { File holdFile = getAFile(); writePNGImage(bye, holdFile); @@ -257,10 +257,7 @@ private void maintainSize(int sizeEst) throws IOException { /*************************************************************************** ** - ** Get temp file: - ** On Mac 10.5.8, JDK 1.6, this seems to go into: - ** /private/var/folders/[2 characters]/[Random string of characters]/-Tmp- - ** Note: To cd into -Tmp-, use "cd -- -Tmp-" + ** Get temp file */ private File getAFile() throws IOException { @@ -312,14 +309,7 @@ private BufferedImage readImageFromFile(File readFile) throws IOException { if (!readers.hasNext()) { throw new IOException(); } - BufferedImage retval = ImageIO.read(iis); - // At first blush, it would seem that an iis.close() call here would - // be the answer to issue #13, but that throws an IOException that the - // stream is already closed! Reading the javadocs, it turns out that the - // stream is closed UNLESS it returns null. - if (retval == null) { - iis.close(); - } + BufferedImage retval = ImageIO.read(iis); return (retval); } } diff --git a/src/org/systemsbiology/biotapestry/biofabric/InboundConnectionOp.java b/src/org/systemsbiology/biotapestry/biofabric/InboundConnectionOp.java new file mode 100644 index 0000000..4ac6d2c --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/InboundConnectionOp.java @@ -0,0 +1,57 @@ +/* +** Copyright (C) 2003-2011 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + +/**************************************************************************** +** +** Inbound connection change +*/ + +public class InboundConnectionOp extends InboundGaggleOp { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + private boolean connected_; + + /*************************************************************************** + ** + ** Create the op - called on RMI thread + */ + + public InboundConnectionOp(BioFabricWindow bfw, boolean connected) { + super(bfw); + connected_ = connected; + return; + } + + /*************************************************************************** + ** + ** Execute the op - called on AWT thread + */ + + public void executeOp() { + bfw_.connectedToGaggle(connected_); + return; + } +} diff --git a/src/org/systemsbiology/biotapestry/biofabric/InboundGaggleOp.java b/src/org/systemsbiology/biotapestry/biofabric/InboundGaggleOp.java new file mode 100644 index 0000000..2f06ecc --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/InboundGaggleOp.java @@ -0,0 +1,65 @@ +/* +** Copyright (C) 2003-2011 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + +import javax.swing.JOptionPane; + +import org.systemsbiology.biotapestry.util.ResourceManager; + +/**************************************************************************** +** +** Base class for inbound op +*/ + +public class InboundGaggleOp { + + //////////////////////////////////////////////////////////////////////////// + // + // PROTECTED INSTANCE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + protected BioFabricWindow bfw_; + + /*************************************************************************** + ** + ** Create the op - called on RMI thread + */ + + public InboundGaggleOp(BioFabricWindow bfw) { + bfw_ = bfw; + return; + } + + /*************************************************************************** + ** + ** Execute the op - called on AWT thread + */ + + public void executeOp() { + ResourceManager rMan = ResourceManager.getManager(); + JOptionPane.showMessageDialog(bfw_, + rMan.getString("gaggle.opNotSupported"), + rMan.getString("gaggle.opNotSupportedTitle"), + JOptionPane.WARNING_MESSAGE); + return; + } + +} diff --git a/src/org/systemsbiology/biotapestry/biofabric/InboundNetworkOp.java b/src/org/systemsbiology/biotapestry/biofabric/InboundNetworkOp.java new file mode 100644 index 0000000..310b0d1 --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/InboundNetworkOp.java @@ -0,0 +1,72 @@ +/* +** Copyright (C) 2003-2012 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + +import java.util.ArrayList; +import java.util.List; + + +/**************************************************************************** +** +** Class for operation to build a network +*/ + +public class InboundNetworkOp extends InboundGaggleOp { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + private ArrayList links_; + private ArrayList singles_; + private String species_; + + /*************************************************************************** + ** + ** Create the op - called on RMI thread + */ + + public InboundNetworkOp(String species, List links, List singles) { + super(null); + links_ = new ArrayList(); + int iLen = links.size(); + for (int i = 0; i < iLen; i++) { + links_.add(((FabricLink)links.get(i)).clone()); + } + singles_ = new ArrayList(singles); + species_ = species; + return; + } + +//////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Execute the op - called on AWT thread + */ + + public void executeOp() { + FabricCommands fc = FabricCommands.getCmds("mainWindow"); + fc.loadFromGaggle(links_, singles_); + return; + } +} diff --git a/src/org/systemsbiology/biotapestry/biofabric/InboundSelectionOp.java b/src/org/systemsbiology/biotapestry/biofabric/InboundSelectionOp.java new file mode 100644 index 0000000..2b88aa3 --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/InboundSelectionOp.java @@ -0,0 +1,62 @@ +/* +** Copyright (C) 2003-2011 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + +/**************************************************************************** +** +** Inbound selections +*/ + +public class InboundSelectionOp extends InboundGaggleOp { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + private SelectionSupport.SelectionsForSpecies sfs_; + + /*************************************************************************** + ** + ** Create the op - called on RMI thread + */ + + public InboundSelectionOp(BioFabricWindow bfw, SelectionSupport.SelectionsForSpecies sfs) { + super(bfw); + sfs_ = sfs; + return; + } + + /*************************************************************************** + ** + ** Execute the op - called on AWT thread + */ + + public void executeOp() { + BioFabricPanel bfp = bfw_.getFabricPanel(); + if (sfs_.selections.isEmpty()) { + bfp.clearSelections(); + } else { + bfp.selectFromGaggle(sfs_); + } + return; + } +} diff --git a/src/org/systemsbiology/biotapestry/biofabric/LinkGroupingSetupDialog.java b/src/org/systemsbiology/biotapestry/biofabric/LinkGroupingSetupDialog.java new file mode 100644 index 0000000..b5b2abb --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/LinkGroupingSetupDialog.java @@ -0,0 +1,295 @@ +/* +** Copyright (C) 2003-2012 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +package org.systemsbiology.biotapestry.biofabric; + +import java.awt.GridBagLayout; +import java.awt.GridBagConstraints; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JOptionPane; +import javax.swing.border.EmptyBorder; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.UiUtil; +import org.systemsbiology.biotapestry.util.DataUtil; +import org.systemsbiology.biotapestry.ui.dialogs.utils.DialogSupport; +import org.systemsbiology.biotapestry.ui.dialogs.utils.EditableTable; + +/**************************************************************************** +** +** Dialog box for specifying link groupings +*/ + +public class LinkGroupingSetupDialog extends JDialog implements DialogSupport.DialogSupportClient { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE MEMBERS + // + //////////////////////////////////////////////////////////////////////////// + + private boolean haveResult_; + private List linkGroupResult_; + private EditableTable est_; + private JFrame parent_; + private Set allRelations_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Constructor + */ + + public LinkGroupingSetupDialog(JFrame parent, List currentTags, Set allRelations) { + super(parent, ResourceManager.getManager().getString("linkGroupEdit.title"), true); + parent_ = parent; + allRelations_ = allRelations; + + setSize(650, 300); + JPanel cp = (JPanel)getContentPane(); + cp.setBorder(new EmptyBorder(20, 20, 20, 20)); + cp.setLayout(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + + est_ = new EditableTable(new LinkGroupingTableModel(), parent_); + EditableTable.TableParams etp = new EditableTable.TableParams(); + etp.addAlwaysAtEnd = false; + etp.buttons = EditableTable.ALL_BUT_EDIT_BUTTONS; + etp.singleSelectOnly = true; + JPanel tablePan = est_.buildEditableTable(etp); + + UiUtil.gbcSet(gbc, 0, 0, 10, 8, UiUtil.BO, 0, 0, 5, 5, 5, 5, UiUtil.CEN, 1.0, 1.0); + cp.add(tablePan, gbc); + + DialogSupport ds = new DialogSupport(this, ResourceManager.getManager(), gbc); + ds.buildAndInstallButtonBox(cp, 10, 10, false, true); + est_.getModel().extractValues((currentTags == null) ? new ArrayList() : currentTags) ; + setLocationRelativeTo(parent); + } + + /*************************************************************************** + ** + ** Answer if we have a result + ** + */ + + public boolean haveResult() { + return (haveResult_); + } + + /*************************************************************************** + ** + ** Return results + ** + */ + + public List getGroups() { + return (linkGroupResult_); + } + + /*************************************************************************** + ** + ** Standard apply + ** + */ + + public void applyAction() { + throw new UnsupportedOperationException(); + } + + /*************************************************************************** + ** + ** Standard ok + ** + */ + + public void okAction() { + if (stashResults(true)) { + setVisible(false); + dispose(); + } + return; + } + + /*************************************************************************** + ** + ** Standard close + ** + */ + + public void closeAction() { + if (stashResults(false)) { + setVisible(false); + dispose(); + } + return; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** The table + */ + + class LinkGroupingTableModel extends EditableTable.TableModel { + + private final static int GROUP_TAG_ = 0; + private final static int NUM_COL_ = 1; + + LinkGroupingTableModel() { + super(NUM_COL_); + colNames_ = new String[] {"linkGroupEdit.suffix"}; + colClasses_ = new Class[] {String.class}; + } + + public List getValuesFromTable() { + ArrayList retval = new ArrayList(); + for (int i = 0; i < this.rowCount_; i++) { + retval.add((String)columns_[GROUP_TAG_].get(i)); + } + return (retval); + } + + public void extractValues(List prsList) { + super.extractValues(prsList); + Iterator rit = prsList.iterator(); + while (rit.hasNext()) { + columns_[GROUP_TAG_].add(rit.next()); + } + return; + } + + List applyValues() { + List vals = getValuesFromTable(); + + // + // Make sure the groups are OK. Names must be unique, non-blank, present as suffixes in the + // provided set of link relations, and they must cover the set. + // + + ResourceManager rMan = ResourceManager.getManager(); + ArrayList seenTags = new ArrayList(); + int size = vals.size(); + if (size == 0) { + return (seenTags); + } + + for (int i = 0; i < size; i++) { + String tag = (String)vals.get(i); + if ((tag == null) || (tag.trim().equals(""))) { + JOptionPane.showMessageDialog(parent_, rMan.getString("rsedit.badRegion"), + rMan.getString("rsedit.badRegionTitle"), + JOptionPane.ERROR_MESSAGE); + return (null); + } + + tag = tag.trim(); + + if (DataUtil.containsKey(seenTags, tag)) { + JOptionPane.showMessageDialog(parent_, rMan.getString("rsedit.dupRegion"), + rMan.getString("rsedit.badRegionTitle"), + JOptionPane.ERROR_MESSAGE); + + return (null); + } + + seenTags.add(tag); + } + + + boolean fail = false; + int numST = seenTags.size(); + Iterator arit = allRelations_.iterator(); + while (arit.hasNext()) { + FabricLink.AugRelation relation = (FabricLink.AugRelation)arit.next(); + boolean gotIt = false; + for (int i = 0; i < numST; i++) { + if (relation.relation.indexOf((String)seenTags.get(i)) != -1) { + gotIt = true; + break; + } + } + if (!gotIt) { + fail = true; + break; + } + } + + if (fail) { + JOptionPane.showMessageDialog(parent_, rMan.getString("rsedit.notCovering"), + rMan.getString("rsedit.badCoverageTitle"), + JOptionPane.ERROR_MESSAGE); + + return (null); + } + return (seenTags); + } + } + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Stash our results for later interrogation. If they have an error, pop + ** up a warning dialog and return false, else return true. + ** + */ + + private boolean stashResults(boolean ok) { + if (ok) { + linkGroupResult_ = ((LinkGroupingTableModel)est_.getModel()).applyValues(); + if (linkGroupResult_ == null) { + haveResult_ = false; + return (false); + } + haveResult_ = true; + return (true); + } else { + haveResult_ = false; + return (true); + } + } +} diff --git a/src/org/systemsbiology/biofabric/ui/render/PaintCache.java b/src/org/systemsbiology/biotapestry/biofabric/PaintCache.java similarity index 64% rename from src/org/systemsbiology/biofabric/ui/render/PaintCache.java rename to src/org/systemsbiology/biotapestry/biofabric/PaintCache.java index f9cef4b..c068568 100644 --- a/src/org/systemsbiology/biofabric/ui/render/PaintCache.java +++ b/src/org/systemsbiology/biotapestry/biofabric/PaintCache.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2017 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.render; +package org.systemsbiology.biotapestry.biofabric; import java.awt.BasicStroke; import java.awt.Color; @@ -35,12 +35,9 @@ import java.util.List; import java.util.Map; -import org.systemsbiology.biofabric.model.BioFabricNetwork; -import org.systemsbiology.biofabric.ui.FabricColorGenerator; -import org.systemsbiology.biofabric.ui.display.BioFabricPanel; -import org.systemsbiology.biofabric.util.MinMax; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.MinMax; +import org.systemsbiology.biotapestry.util.UiUtil; + /**************************************************************************** ** @@ -82,8 +79,9 @@ public class PaintCache { private Font medSmall_; private Font small_; - private List paintPaths_; + private List paintPaths_; private FabricColorGenerator colGen_; + private Color superLightGrey_; private Color superLightPink_; private Color superLightBlue_; @@ -104,8 +102,9 @@ public PaintCache(FabricColorGenerator colGen) { med_ = new Font("SansSerif", Font.PLAIN, 100); medSmall_ = new Font("SansSerif", Font.PLAIN, 70); small_ = new Font("SansSerif", Font.PLAIN, 30); - paintPaths_ = new ArrayList(); + paintPaths_ = new ArrayList(); colGen_ = colGen; + superLightGrey_ = new Color(224, 224, 224); superLightPink_ = new Color(255, 244, 244); superLightBlue_ = new Color(244, 244, 255); } @@ -134,7 +133,7 @@ public boolean paintIt(Graphics2D g2, boolean doBoxes, Rectangle clip, boolean f boolean retval = false; int numpp = paintPaths_.size(); for (int i = 0; i < numpp; i++) { - PaintedPath pp = paintPaths_.get(i); + PaintedPath pp = (PaintedPath)paintPaths_.get(i); int result = pp.paint(g2, true, clip, forSelection); retval = retval || (result > 0); } @@ -172,43 +171,38 @@ public void drawFloater(Graphics2D g2, FloaterSet floaters) { ** Build objcache */ - public void buildObjCache(List targets, List links, - boolean shadeNodes, boolean showShadows, Map nameMap, - Map> drainMap) { + public void buildObjCache(List targets, List links, boolean shadeNodes, boolean showShadows, Map nameMap, Map drainMap) { paintPaths_.clear(); FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true); int numLinks = links.size(); - HashMap linkExtents = new HashMap(); + HashMap linkExtents = new HashMap(); for (int i = 0; i < numLinks; i++) { - BioFabricNetwork.LinkInfo link = links.get(i); + BioFabricNetwork.LinkInfo link = (BioFabricNetwork.LinkInfo)links.get(i); int num = link.getUseColumn(showShadows); int sRow = link.topRow(); int eRow = link.bottomRow(); - linkExtents.put(Integer.valueOf(num), new MinMax(sRow, eRow)); - } - - ArrayList postPaths = new ArrayList(); - ArrayList postPostPaths = new ArrayList(); - Iterator trit = targets.iterator(); + linkExtents.put(new Integer(num), new MinMax(sRow, eRow)); + } + + ArrayList postPaths = new ArrayList(); + ArrayList postPostPaths = new ArrayList(); + Iterator trit = targets.iterator(); while (trit.hasNext()) { - BioFabricNetwork.NodeInfo target = trit.next(); + BioFabricNetwork.NodeInfo target = (BioFabricNetwork.NodeInfo)trit.next(); buildALineHorz(target, paintPaths_, postPaths, postPostPaths, frc, colGen_, linkExtents, shadeNodes, showShadows, nameMap, drainMap); } paintPaths_.addAll(postPaths); for (int i = 0; i < numLinks; i++) { - BioFabricNetwork.LinkInfo link = links.get(i); + BioFabricNetwork.LinkInfo link = (BioFabricNetwork.LinkInfo)links.get(i); buildALineVert(link, paintPaths_, colGen_, showShadows); } paintPaths_.addAll(postPostPaths); - - - return; } - + /*************************************************************************** ** ** Get detail panel @@ -232,7 +226,7 @@ public Color getColorForNode(BioFabricNetwork.NodeInfo node, FabricColorGenerato ** Build a line */ - private void buildALineVert(BioFabricNetwork.LinkInfo link, List objCache, FabricColorGenerator colGen, boolean showShadows) { + private void buildALineVert(BioFabricNetwork.LinkInfo link, List objCache, FabricColorGenerator colGen, boolean showShadows) { int num = link.getUseColumn(showShadows); int sRow = link.topRow(); @@ -279,13 +273,13 @@ private PaintedPath buildAnArrow(Color color, int x, int yStrt, int yEnd) { GeneralPath gp = new GeneralPath(); float yoff = (yStrt < yEnd) ? -BB_RADIUS_ : BB_RADIUS_; gp.moveTo(x - BB_RADIUS_, yEnd + 2.0F * yoff); - gp.lineTo(x, (yEnd + yoff)); - gp.lineTo((x - BB_RADIUS_), (yEnd + yoff)); - gp.lineTo((x - BB_RADIUS_), (yEnd - yoff)); - gp.lineTo((x + BB_RADIUS_), (yEnd - yoff)); - gp.lineTo((x + BB_RADIUS_), (yEnd + yoff)); - gp.lineTo(x, (yEnd + yoff)); - gp.lineTo((x + BB_RADIUS_), (yEnd + 2.0F * yoff)); + gp.lineTo((float)x, (float)(yEnd + yoff)); + gp.lineTo((float)(x - BB_RADIUS_), (float)(yEnd + yoff)); + gp.lineTo((float)(x - BB_RADIUS_), (float)(yEnd - yoff)); + gp.lineTo((float)(x + BB_RADIUS_), (float)(yEnd - yoff)); + gp.lineTo((float)(x + BB_RADIUS_), (float)(yEnd + yoff)); + gp.lineTo((float)x, (float)(yEnd + yoff)); + gp.lineTo((float)(x + BB_RADIUS_), (float)(yEnd + 2.0F * yoff)); gp.closePath(); return (new PaintedPath(color, circ, gp)); } @@ -295,62 +289,50 @@ private PaintedPath buildAnArrow(Color color, int x, int yStrt, int yEnd) { ** Build a line */ - private void buildALineHorz(BioFabricNetwork.NodeInfo target, List preCache, - List objCache, List postPostCache, FontRenderContext frc, - FabricColorGenerator colGen, Map linkExtents, - boolean shadeNodes, boolean showShadows, Map nameMap, - Map> drainMap) { + private void buildALineHorz(BioFabricNetwork.NodeInfo target, List preCache, + List objCache, List postPostCache, FontRenderContext frc, + FabricColorGenerator colGen, Map linkExtents, + boolean shadeNodes, boolean showShadows, Map nameMap, Map drainMap) { // // Drain zone sizing / rotation: // - List zones = target.getDrainZones(showShadows); - - DrainZoneInfo[] dzis = new DrainZoneInfo[zones.size()]; - for (int i = 0; i < dzis.length; i++) { // initialize each entry in array - dzis[i] = new DrainZoneInfo(zones.get(i)); - } - - for (int i = 0; i < zones.size(); i++) { - - DrainZoneInfo curr = dzis[i]; - curr.doRotateName = false; - - if (curr.dzmm == null) { - continue; - } - - curr.diff = curr.dzmm.max - curr.dzmm.min; - - Rectangle2D bounds = huge_.getStringBounds(target.getNodeName(), frc); - if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * curr.diff)) { - curr.font = 0; - curr.dumpRect = bounds; + int diff = 0; + int useFont = 0; + Rectangle2D dumpRect = null; + boolean doRotateName = false; + MinMax dzmm = (MinMax)target.getDrainZone(showShadows); + if (dzmm != null) { + diff = dzmm.max - dzmm.min; + Rectangle2D bounds = huge_.getStringBounds(target.nodeName, frc); + if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * diff)) { + useFont = 0; + dumpRect = bounds; } else { - bounds = med_.getStringBounds(target.getNodeName(), frc); - if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * curr.diff)) { - curr.font = 1; - curr.dumpRect = bounds; + bounds = med_.getStringBounds(target.nodeName, frc); + if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * diff)) { + useFont = 1; + dumpRect = bounds; } else { - bounds = medSmall_.getStringBounds(target.getNodeName(), frc); - if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * curr.diff)) { - curr.font = 2; - curr.dumpRect = bounds; + bounds = medSmall_.getStringBounds(target.nodeName, frc); + if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * diff)) { + useFont = 2; + dumpRect = bounds; } else { - bounds = small_.getStringBounds(target.getNodeName(), frc); - if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * curr.diff)) { - curr.font = 3; - curr.dumpRect = bounds; + bounds = small_.getStringBounds(target.nodeName, frc); + if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * diff)) { + useFont = 3; + dumpRect = bounds; } else { - bounds = tiny_.getStringBounds(target.getNodeName(), frc); - if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * curr.diff)) { - curr.font = 4; - curr.dumpRect = bounds; + bounds = tiny_.getStringBounds(target.nodeName, frc); + if (bounds.getWidth() <= (BioFabricPanel.GRID_SIZE * diff)) { + useFont = 4; + dumpRect = bounds; } else { - curr.font = 4; - curr.dumpRect = bounds; - curr.doRotateName = true; + useFont = 4; + doRotateName = true; + dumpRect = bounds; } } } @@ -360,19 +342,19 @@ private void buildALineHorz(BioFabricNetwork.NodeInfo target, List // Drain zone Y: Lifted slightly above node line and link boxes: - float tnamey = (target.nodeRow - DRAIN_ZONE_ROW_OFFSET_) * BioFabricPanel.GRID_SIZE; + float tnamey = ((float)target.nodeRow - DRAIN_ZONE_ROW_OFFSET_) * (float)BioFabricPanel.GRID_SIZE; - MinMax colmm = target.getColRange(showShadows); + MinMax colmm = (MinMax)target.getColRange(showShadows); // // Node label sizing and Y: // - Rectangle2D labelBounds = tiny_.getStringBounds(target.getNodeName(), frc); + Rectangle2D labelBounds = tiny_.getStringBounds(target.nodeName, frc); // Easiest font height hack is to scale it by ~.67: double scaleHeight = labelBounds.getHeight() * LABEL_FONT_HEIGHT_SCALE_; - float namey = (target.nodeRow * BioFabricPanel.GRID_SIZE) + (float)(scaleHeight / 2.0); - float namex = (colmm.min * BioFabricPanel.GRID_SIZE) - (float)labelBounds.getWidth() - BB_RADIUS_ - NODE_LABEL_X_SHIM_; + float namey = (float)(target.nodeRow * BioFabricPanel.GRID_SIZE) + (float)(scaleHeight / 2.0); + float namex = (float)(colmm.min * BioFabricPanel.GRID_SIZE) - (float)labelBounds.getWidth() - BB_RADIUS_ - NODE_LABEL_X_SHIM_; labelBounds.setRect(namex, namey - scaleHeight, labelBounds.getWidth(), scaleHeight); // @@ -380,133 +362,86 @@ private void buildALineHorz(BioFabricNetwork.NodeInfo target, List // if ((colmm.max == Integer.MIN_VALUE) || (colmm.min == Integer.MAX_VALUE)) { - UiUtil.fixMePrintout("Does this still need to exist??"); - // objCache.add(new PaintedPath(Color.BLACK, target.getNodeName(), 100.0F, namey, 100.0F, tnamey, - // doRotateName, useFont, labelBounds, dumpRect)); - // nameMap.put(target.getNodeIDWithName(), (Rectangle2D)labelBounds.clone()); + objCache.add(new PaintedPath(Color.BLACK, target.nodeName, 100.0F, namey, 100.0F, tnamey, + doRotateName, useFont, labelBounds, dumpRect)); + nameMap.put(target.nodeName, (Rectangle2D)labelBounds.clone()); return; } - + // - // Create the horizontal line and process it + // Print out drain zone text _if_ there is a drain zone: // - - int yval = (target.nodeRow * BioFabricPanel.GRID_SIZE); - int xStrt = (colmm.min * BioFabricPanel.GRID_SIZE); - int xEnd = (colmm.max * BioFabricPanel.GRID_SIZE); - Line2D line = new Line2D.Double(xStrt, yval, xEnd, yval); - Color paintCol = getColorForNode(target, colGen); - objCache.add(new PaintedPath(paintCol, line, Integer.MIN_VALUE, yval, new MinMax(xStrt, xEnd))); - nameMap.put(target.getNodeIDWithName(), (Rectangle2D) labelBounds.clone()); - - objCache.add(new PaintedPath(Color.BLACK, target.getNodeName(), namex, namey, labelBounds)); - - List rectList = new ArrayList(); - - - for (int i = 0; i < zones.size(); i++) { - - DrainZoneInfo curr = dzis[i]; - - if (curr.dzmm == null) { - continue; - } - // - // Print out drain zone text _if_ there is a drain zone: - // - - float tnamex = 0; - if (curr.dumpRect != null) { - // Easiest font height hack is to scale it by ~.67: - double dumpScaleHeight = curr.dumpRect.getHeight() * LABEL_FONT_HEIGHT_SCALE_; - if (curr.doRotateName) { - tnamex = (curr.dzmm.min * BioFabricPanel.GRID_SIZE) + - ((curr.diff * BioFabricPanel.GRID_SIZE) / 2.0F) + - (float)(dumpScaleHeight / 2.0); - curr.dumpRect.setRect(tnamex - dumpScaleHeight, tnamey - curr.dumpRect.getWidth(), - dumpScaleHeight, curr.dumpRect.getWidth()); - } else { - tnamex = (curr.dzmm.min * BioFabricPanel.GRID_SIZE) + - ((curr.diff * BioFabricPanel.GRID_SIZE) / 2.0F) - ((int) curr.dumpRect.getWidth() / 2); - curr.dumpRect.setRect(tnamex, tnamey - dumpScaleHeight, curr.dumpRect.getWidth(), dumpScaleHeight); - } - if (shadeNodes) { - Color col = ((target.nodeRow % 2) == 0) ? superLightBlue_ : superLightPink_; - buildABackRect(curr.dzmm, linkExtents, curr.dumpRect, preCache, col); - } - } + float tnamex = 0; + if (dumpRect != null) { + // Easiest font height hack is to scale it by ~.67: + double dumpScaleHeight = dumpRect.getHeight() * LABEL_FONT_HEIGHT_SCALE_; + if (doRotateName) { + tnamex = (float)(dzmm.min * BioFabricPanel.GRID_SIZE) + + ((float)(diff * BioFabricPanel.GRID_SIZE) / 2.0F) + + (float)(dumpScaleHeight / 2.0); + dumpRect.setRect(tnamex - dumpScaleHeight, tnamey - dumpRect.getWidth(), + dumpScaleHeight, dumpRect.getWidth()); + } else { + tnamex = (dzmm.min * BioFabricPanel.GRID_SIZE) + ((float)(diff * BioFabricPanel.GRID_SIZE) / 2.0F) - ((int)dumpRect.getWidth() / 2); + dumpRect.setRect(tnamex, tnamey - dumpScaleHeight, dumpRect.getWidth(), dumpScaleHeight); + } + if (shadeNodes) { + int minRow = Integer.MAX_VALUE; + int maxRow = Integer.MIN_VALUE; + for (int i = dzmm.min; i <= dzmm.max; i++) { + MinMax range = (MinMax)linkExtents.get(new Integer(i)); + if (range != null) { + if (minRow > range.min) { + minRow = range.min; + } + if (maxRow < range.max) { + maxRow = range.max; + } + } + } + int rectLeft = (int)Math.floor((double)(dzmm.min * BioFabricPanel.GRID_SIZE) - BB_RADIUS_ - (STROKE_SIZE / 2.0)); + int topRow = (int)Math.floor((double)(minRow * BioFabricPanel.GRID_SIZE) - BB_RADIUS_ - (STROKE_SIZE / 2.0)); + int rectTop = Math.min((int)dumpRect.getMinY(), topRow); + int rectRight = (int)Math.ceil((double)(dzmm.max * BioFabricPanel.GRID_SIZE) + BB_RADIUS_ + (STROKE_SIZE / 2.0)); + int rectWidth = rectRight - rectLeft; + int rectBot = (int)Math.floor((double)(maxRow * BioFabricPanel.GRID_SIZE) + BB_RADIUS_ + (STROKE_SIZE / 2.0)); + int rectHeight = rectBot - rectTop; + Rectangle rect = new Rectangle(rectLeft, rectTop, rectWidth, rectHeight); + Color col = ((target.nodeRow % 2) == 0) ? superLightBlue_ : superLightPink_; + preCache.add(new PaintedPath(col, rect)); + } + } // // Output the node label and (optional) drain zone label. If we are using a tiny font for the drain // zone, it goes out last to get drawn above the links. // - if (curr.font == 4) { + if (useFont == 4) { - postPostCache.add(new PaintedPath(Color.BLACK, target.getNodeName(), namex, namey, tnamex, tnamey, - curr.doRotateName, curr.font, labelBounds, curr.dumpRect)); - } else { - objCache.add(new PaintedPath(Color.BLACK, target.getNodeName(), namex, namey, tnamex, tnamey, - curr.doRotateName, curr.font, labelBounds, curr.dumpRect)); - } + postPostCache.add(new PaintedPath(Color.BLACK, target.nodeName, namex, namey, tnamex, tnamey, + doRotateName, useFont, labelBounds, dumpRect)); + } else { + objCache.add(new PaintedPath(Color.BLACK, target.nodeName, namex, namey, tnamex, tnamey, + doRotateName, useFont, labelBounds, dumpRect)); - if (curr.dumpRect != null) { - rectList.add((Rectangle2D) curr.dumpRect.clone()); - } - } - drainMap.put(target.getNodeIDWithName(), rectList); - - return; - } - - /*************************************************************************** - ** Contains the properties required to draw a drain zone - */ - - private static class DrainZoneInfo { - - private int diff, font; - private boolean doRotateName; - private Rectangle2D dumpRect; - private MinMax dzmm; - - DrainZoneInfo(MinMax dzmm) { - this.dzmm = dzmm.clone(); - } - - } - - /*************************************************************************** - ** - ** Build a backRect - */ - - private void buildABackRect(MinMax dzmm, Map linkExtents, Rectangle2D dumpRect, List preCache, Color col) { - int minRow = Integer.MAX_VALUE; - int maxRow = Integer.MIN_VALUE; - for (int i = dzmm.min; i <= dzmm.max; i++) { - MinMax range = linkExtents.get(Integer.valueOf(i)); - if (range != null) { - if (minRow > range.min) { - minRow = range.min; - } - if (maxRow < range.max) { - maxRow = range.max; - } - } } - int rectLeft = (int)Math.floor((double)(dzmm.min * BioFabricPanel.GRID_SIZE) - BB_RADIUS_ - (STROKE_SIZE / 2.0)); - int topRow = (int)Math.floor((double)(minRow * BioFabricPanel.GRID_SIZE) - BB_RADIUS_ - (STROKE_SIZE / 2.0)); - int rectTop = (dumpRect == null) ? topRow : Math.min((int)dumpRect.getMinY(), topRow); - int rectRight = (int)Math.ceil((double)(dzmm.max * BioFabricPanel.GRID_SIZE) + BB_RADIUS_ + (STROKE_SIZE / 2.0)); - int rectWidth = rectRight - rectLeft; - int rectBot = (int)Math.floor((double)(maxRow * BioFabricPanel.GRID_SIZE) + BB_RADIUS_ + (STROKE_SIZE / 2.0)); - int rectHeight = rectBot - rectTop; - Rectangle rect = new Rectangle(rectLeft, rectTop, rectWidth, rectHeight); - preCache.add(new PaintedPath(col, rect)); + // + // Output the node line: + // + int yval = (target.nodeRow * BioFabricPanel.GRID_SIZE); + int xStrt = (colmm.min * BioFabricPanel.GRID_SIZE); + int xEnd = (colmm.max * BioFabricPanel.GRID_SIZE); + Line2D line = new Line2D.Double(xStrt, yval, xEnd, yval); + Color paintCol = getColorForNode(target, colGen); + objCache.add(new PaintedPath(paintCol, line, Integer.MIN_VALUE, yval, new MinMax(xStrt, xEnd))); + nameMap.put(target.nodeName, (Rectangle2D)labelBounds.clone()); + if (dumpRect != null) { + drainMap.put(target.nodeName, (Rectangle2D)dumpRect.clone()); + } return; - } + } /*************************************************************************** ** @@ -533,18 +468,6 @@ private class PaintedPath { int font; Rectangle rect; - // - // Used for node labels for nodes without drain zones - // - - PaintedPath(Color col, String name, float x, float y, Rectangle2D nameRect) { - this.col = col; - this.name = name; - nameX = x; - nameY = y; - this.nameRect = nameRect; - } - // // Used for line drawing: // @@ -615,15 +538,15 @@ int paint(Graphics2D g2, boolean doBoxes, Rectangle bounds, boolean forSelection int didPaint = 0; g2.setPaint(forSelection ? Color.black : col); if ((name != null) && (path == null)) { - // NODE LABELS: only PaintedPaths that use the "node labels only" constructor can draw node labels - if (((nameRect == null) && (dumpRect == null)) || (bounds == null) || + // NODE LABELS: + if ((bounds == null) || ((nameRect.getMaxX() > bounds.getMinX()) && (nameRect.getMinX() < bounds.getMaxX()) && (nameRect.getMaxY() > bounds.getMinY()) && (nameRect.getMinY() < bounds.getMaxY()))) { //g2.drawLine((int)nameRect.getMinX(), (int)nameRect.getMinY(), (int)nameRect.getMaxX(), (int)nameRect.getMaxY()); g2.setFont(tiny_); - g2.drawString(name, nameX, nameY); // name next to horiz line + g2.drawString(name, nameX, nameY); didPaint++; } // DRAIN ZONES: @@ -660,7 +583,7 @@ int paint(Graphics2D g2, boolean doBoxes, Rectangle bounds, boolean forSelection throw new IllegalArgumentException(); } g2.setFont(useit); - g2.drawString(name, tnameX, tnameY); // zone node names + g2.drawString(name, tnameX, tnameY); didPaint++; } } @@ -708,28 +631,16 @@ int paint(Graphics2D g2, boolean doBoxes, Rectangle bounds, boolean forSelection g2.fill(rect); } else { if (px == Integer.MIN_VALUE) { // Horiz line - if ((bounds == null) || ((py >= bounds.y) && (py <= (bounds.y + bounds.height)))) { + if ((bounds == null) || ((py > bounds.y) && (py < (bounds.y + bounds.height)))) { if ((bounds != null) && ((range.max < bounds.x) || (range.min > (bounds.x + bounds.width)))) { // do nothing } else { - double x1 = path.getX1(); - double x2 = path.getX2(); - double y1 = path.getY1(); - double y2 = path.getY2(); - boolean replace = false; - if ((x2 - x1) > 100000) { - path.setLine(bounds.x - 1000, y1, bounds.x + bounds.width + 1000, y2); - replace = true; - } g2.draw(path); - if (replace) { - path.setLine(x1, y1, x2, y2); - } didPaint++; } } } else if (py == Integer.MIN_VALUE) { // Vert line - if ((bounds == null) || ((px >= bounds.x) && (px <= (bounds.x + bounds.width)))) { + if ((bounds == null) || ((px > bounds.x) && (px < (bounds.x + bounds.width)))) { if ((bounds != null) && ((range.max < bounds.y) || (range.min > (bounds.y + bounds.height)))) { // do nothing } else { @@ -756,9 +667,9 @@ int paint(Graphics2D g2, boolean doBoxes, Rectangle bounds, boolean forSelection */ public static class FloaterSet { - public Rectangle floater; - public Rectangle tourRect; - public Rectangle currSelRect; + Rectangle floater; + Rectangle tourRect; + Rectangle currSelRect; public FloaterSet(Rectangle floater, Rectangle tourRect, Rectangle currSelRect) { this.floater = floater; diff --git a/src/org/systemsbiology/biofabric/ui/PopupMenuControl.java b/src/org/systemsbiology/biotapestry/biofabric/PopupMenuControl.java similarity index 83% rename from src/org/systemsbiology/biofabric/ui/PopupMenuControl.java rename to src/org/systemsbiology/biotapestry/biofabric/PopupMenuControl.java index f580cdb..69831e4 100644 --- a/src/org/systemsbiology/biofabric/ui/PopupMenuControl.java +++ b/src/org/systemsbiology/biotapestry/biofabric/PopupMenuControl.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.biofabric; import java.awt.Point; import java.awt.event.ActionEvent; @@ -28,10 +28,8 @@ import javax.swing.Action; import javax.swing.JPanel; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.NID; -import org.systemsbiology.biofabric.util.ResourceManager; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.ExceptionHandler; /*************************************************************************** ** @@ -54,7 +52,7 @@ public class PopupMenuControl { private NodePopup popupGuts_; private LinkPopup popupGutsLink_; - private NID.WithName currNode_; + private String currNode_; private FabricLink currLink_; private JPanel parent_; @@ -101,7 +99,7 @@ public boolean isVisible() { ** Launch popup menu */ - public void showNodePopup(NID.WithName nodeName, Point pt) { + public void showNodePopup(String nodeName, Point pt) { currNode_ = nodeName; popupGuts_.showPopup(pt); return; @@ -189,10 +187,8 @@ void showPopup(Point pt) { */ void prepareMenu() { - FabricDisplayOptions fdo = FabricDisplayOptionsManager.getMgr().getDisplayOptions(); - String browserURL = fdo.getBrowserURL(); - boolean canShow = fdo.getOfferNodeBrowser(); - lbn_.setEnabled(canShow && !browserURL.equals("")); + String browserURL = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getBrowserURL(); + lbn_.setEnabled(!browserURL.equals("")); return; } } @@ -252,14 +248,12 @@ void showPopup(Point pt) { /*************************************************************************** ** - ** Prepare the link menu for display + ** Prepare the node menu for display */ void prepareMenu() { - FabricDisplayOptions fdo = FabricDisplayOptionsManager.getMgr().getDisplayOptions(); - boolean canShow = fdo.getOfferLinkBrowser(); - String browserURL = fdo.getBrowserLinkURL(); - lbl_.setEnabled(canShow && !browserURL.equals("")); + String browserURL = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getBrowserLinkURL(); + lbl_.setEnabled(!browserURL.equals("")); return; } } @@ -288,24 +282,18 @@ public void popupMenuWillBecomeVisible(PopupMenuEvent e) { public class LaunchBrowserForNode extends AbstractAction { - private static final long serialVersionUID = 1L; - public LaunchBrowserForNode(String text, char mnem) { super(text); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); } public void actionPerformed(ActionEvent e) { try { - FabricDisplayOptions fdo = FabricDisplayOptionsManager.getMgr().getDisplayOptions(); - if (!fdo.getOfferNodeBrowser()) { - return; - } - String browserURL = fdo.getBrowserURL(); + String browserURL = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getBrowserURL(); if (browserURL.indexOf(FabricDisplayOptions.NODE_NAME_PLACEHOLDER) == -1) { return; } - browserURL = browserURL.replaceFirst(FabricDisplayOptions.NODE_NAME_PLACEHOLDER, currNode_.getName()); + browserURL = browserURL.replaceFirst(FabricDisplayOptions.NODE_NAME_PLACEHOLDER, currNode_); (new BrowserLauncher()).openBBURL(browserURL); } catch (Exception ex) { ExceptionHandler.getHandler().displayException(ex); @@ -321,30 +309,24 @@ public void actionPerformed(ActionEvent e) { public class LaunchBrowserForLink extends AbstractAction { - private static final long serialVersionUID = 1L; - public LaunchBrowserForLink(String text, char mnem) { super(text); - putValue(Action.MNEMONIC_KEY, Integer.valueOf(mnem)); + putValue(Action.MNEMONIC_KEY, new Integer(mnem)); } public void actionPerformed(ActionEvent e) { try { - FabricDisplayOptions fdo = FabricDisplayOptionsManager.getMgr().getDisplayOptions(); - if (!fdo.getOfferLinkBrowser()) { - return; - } - String browserURL = fdo.getBrowserLinkURL(); + String browserURL = FabricDisplayOptionsManager.getMgr().getDisplayOptions().getBrowserLinkURL(); if ((browserURL.indexOf(FabricDisplayOptions.LINK_SRC_PLACEHOLDER) == -1) || (browserURL.indexOf(FabricDisplayOptions.LINK_TRG_PLACEHOLDER) == -1) || (browserURL.indexOf(FabricDisplayOptions.LINK_REL_PLACEHOLDER) == -1)) { return; } else { - NID.WithName src = currLink_.getSrcID(); - NID.WithName trg = currLink_.getTrgID(); + String src = currLink_.getSrc(); + String trg = currLink_.getTrg(); String rel = currLink_.getAugRelation().relation; - browserURL = browserURL.replaceFirst(FabricDisplayOptions.LINK_SRC_PLACEHOLDER, src.getName()); - browserURL = browserURL.replaceFirst(FabricDisplayOptions.LINK_TRG_PLACEHOLDER, trg.getName()); + browserURL = browserURL.replaceFirst(FabricDisplayOptions.LINK_SRC_PLACEHOLDER, src); + browserURL = browserURL.replaceFirst(FabricDisplayOptions.LINK_TRG_PLACEHOLDER, trg); browserURL = browserURL.replaceFirst(FabricDisplayOptions.LINK_REL_PLACEHOLDER, rel); } (new BrowserLauncher()).openBBURL(browserURL); diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/RelationDirectionDialog.java b/src/org/systemsbiology/biotapestry/biofabric/RelationDirectionDialog.java similarity index 64% rename from src/org/systemsbiology/biofabric/ui/dialogs/RelationDirectionDialog.java rename to src/org/systemsbiology/biotapestry/biofabric/RelationDirectionDialog.java index 4ba6390..7f262da 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/RelationDirectionDialog.java +++ b/src/org/systemsbiology/biotapestry/biofabric/RelationDirectionDialog.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2017 Institute for Systems Biology +** Copyright (C) 2003-2011 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,16 +17,14 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.dialogs; + +package org.systemsbiology.biotapestry.biofabric; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - -import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; - import java.util.Iterator; import java.util.ArrayList; import java.util.HashSet; @@ -34,11 +32,10 @@ import java.util.SortedMap; import java.util.TreeMap; -import org.systemsbiology.biofabric.model.FabricLink; -import org.systemsbiology.biofabric.ui.dialogs.utils.BTStashResultsDialog; -import org.systemsbiology.biofabric.ui.dialogs.utils.EditableTable; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; +import org.systemsbiology.biotapestry.ui.dialogs.utils.EditableTable; +import org.systemsbiology.biotapestry.ui.dialogs.utils.BTStashResultsDialog; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.FixedJButton; /**************************************************************************** ** @@ -53,12 +50,11 @@ public class RelationDirectionDialog extends BTStashResultsDialog { // //////////////////////////////////////////////////////////////////////////// - private EditableTable est_; - private SortedMap returnMap_; + private EditableTable est_; + private SortedMap returnMap_; private boolean getFromFile_; - private HashSet returnKeys_; - private SortedMap reducedMap_; - private static final long serialVersionUID = 1L; + private HashSet returnKeys_; + private SortedMap reducedMap_; //////////////////////////////////////////////////////////////////////////// // @@ -71,41 +67,40 @@ public class RelationDirectionDialog extends BTStashResultsDialog { ** Constructor */ - public RelationDirectionDialog(JFrame parent, SortedMap relationMap) { + public RelationDirectionDialog(JFrame parent, SortedMap relationMap) { super(parent, "relDir.title", new Dimension(800, 400), 1); getFromFile_ = false; returnMap_ = null; - returnKeys_ = new HashSet(relationMap.keySet()); - reducedMap_ = new TreeMap(); - HashSet seenRels = new HashSet(); - Iterator ceit = relationMap.keySet().iterator(); + returnKeys_ = new HashSet(relationMap.keySet()); + reducedMap_ = new TreeMap(); + HashSet seenRels = new HashSet(); + Iterator ceit = relationMap.keySet().iterator(); while (ceit.hasNext()) { - FabricLink.AugRelation aug = ceit.next(); + FabricLink.AugRelation aug = (FabricLink.AugRelation)ceit.next(); if (seenRels.contains(aug.relation)) { continue; } seenRels.add(aug.relation); - Boolean isDir = relationMap.get(aug); + Boolean isDir = (Boolean)relationMap.get(aug); reducedMap_.put(new FabricLink.AugRelation(aug.relation, false), isDir); } - est_ = new EditableTable(new RelationDirTableModel(), parent_); + est_ = new EditableTable(new RelationDirTableModel(), parent_); EditableTable.TableParams etp = new EditableTable.TableParams(); etp.addAlwaysAtEnd = true; etp.singleSelectOnly = true; etp.cancelEditOnDisable = true; etp.tableIsUnselectable = true; etp.perColumnEnums = null; - etp.colWidths = new ArrayList(); + etp.colWidths = new ArrayList(); etp.colWidths.add(new EditableTable.ColumnWidths(RelationDirTableModel.RELATION, 50, 300, 5000)); etp.colWidths.add(new EditableTable.ColumnWidths(RelationDirTableModel.DIRECTION, 50, 100, 200)); JPanel tablePan = est_.buildEditableTable(etp); - addTable(tablePan, 8); - returnKeys_ = new HashSet(relationMap.keySet()); + addTable(tablePan, 8); returnKeys_ = new HashSet(relationMap.keySet()); - ArrayList xtraButtonList = new ArrayList(); + ArrayList xtraButtonList = new ArrayList(); FixedJButton buttonSA = new FixedJButton(rMan_.getString("dialogs.selectAll")); buttonSA.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { @@ -155,13 +150,13 @@ public void actionPerformed(ActionEvent ev) { void doMassUpdate(boolean select) { Boolean isDir = new Boolean(select); - EditableTable.TableModel ecdtm = est_.getModel(); - List vals = ecdtm.getValuesFromTable(); + RelationDirTableModel ecdtm = (RelationDirTableModel)est_.getModel(); + List vals = ecdtm.getValuesFromTable(); int numVals = vals.size(); - ArrayList upVals = new ArrayList(); + ArrayList upVals = new ArrayList(); for (int i = 0; i < numVals; i++) { - RelationDirTableModel.TableRow tr = vals.get(i); - RelationDirTableModel.TableRow trc = ecdtm.constructARow(); + RelationDirTableModel.TableRow tr = (RelationDirTableModel.TableRow)vals.get(i); + RelationDirTableModel.TableRow trc = ecdtm.new TableRow(); trc.relation = tr.relation; trc.isDir = isDir; upVals.add(trc); @@ -186,15 +181,15 @@ public boolean getFromFile() { ** */ - public SortedMap getRelationMap() { + public SortedMap getRelationMap() { if (getFromFile_) { return (null); } - returnMap_ = new TreeMap(); - Iterator ceit = returnKeys_.iterator(); + returnMap_ = new TreeMap(); + Iterator ceit = returnKeys_.iterator(); while (ceit.hasNext()) { - FabricLink.AugRelation aug = ceit.next(); - Boolean isDir = reducedMap_.get(new FabricLink.AugRelation(aug.relation, false)); + FabricLink.AugRelation aug = (FabricLink.AugRelation)ceit.next(); + Boolean isDir = (Boolean)reducedMap_.get(new FabricLink.AugRelation(aug.relation, false)); returnMap_.put(aug, isDir); } return (returnMap_); @@ -211,35 +206,33 @@ public SortedMap getRelationMap() { ** Used for the data table */ - class RelationDirTableModel extends EditableTable.TableModel { - - private static final long serialVersionUID = 1L; + class RelationDirTableModel extends EditableTable.TableModel { final static int RELATION = 0; final static int DIRECTION = 1; private final static int NUM_COL_ = 2; - class TableRow implements EditableTable.ATableRow { + class TableRow { String relation; Boolean isDir; - - TableRow() { - } + TableRow() { + } + TableRow(int i) { - relation = (String)columns_.get(RELATION).get(i); - isDir = (Boolean)columns_.get(DIRECTION).get(i); + relation = (String)columns_[RELATION].get(i); + isDir = (Boolean)columns_[DIRECTION].get(i); } - public void toCols() { - columns_.get(RELATION).add(relation); - columns_.get(DIRECTION).add(isDir); + void toCols() { + columns_[RELATION].add(relation); + columns_[DIRECTION].add(isDir); return; } void replaceCols(int row) { - columns_.get(RELATION).set(row, relation); - columns_.get(DIRECTION).set(row, isDir); + columns_[RELATION].set(row, relation); + columns_[DIRECTION].set(row, isDir); return; } } @@ -254,12 +247,24 @@ void replaceCols(int row) { true}; } - protected TableRow constructARow(int i) { - return (new TableRow(i)); + public List getValuesFromTable() { + ArrayList retval = new ArrayList(); + for (int i = 0; i < rowCount_; i++) { + TableRow ent = new TableRow(i); + retval.add(ent); + } + return (retval); + } + + public void extractValues(List prsList) { + super.extractValues(prsList); + Iterator rit = prsList.iterator(); + while (rit.hasNext()) { + TableRow ent = (TableRow)rit.next(); + ent.toCols(); + } + return; } - public TableRow constructARow() { - return (new TableRow()); - } } //////////////////////////////////////////////////////////////////////////// @@ -275,8 +280,8 @@ public TableRow constructARow() { */ private void displayProperties() { - List tableRows = initTableRows(); - est_.getModel().extractValues(tableRows); + List tableRows = initTableRows(); + ((RelationDirTableModel)est_.getModel()).extractValues(tableRows); return; } @@ -286,15 +291,15 @@ private void displayProperties() { ** */ - private List initTableRows() { - ArrayList retval = new ArrayList(); - EditableTable.TableModel ecdtm = est_.getModel(); - Iterator ceit = reducedMap_.keySet().iterator(); + private List initTableRows() { + ArrayList retval = new ArrayList(); + RelationDirTableModel ecdtm = (RelationDirTableModel)est_.getModel(); + Iterator ceit = reducedMap_.keySet().iterator(); while (ceit.hasNext()) { - FabricLink.AugRelation aug = ceit.next(); - RelationDirTableModel.TableRow tr = ecdtm.constructARow(); + FabricLink.AugRelation aug = (FabricLink.AugRelation)ceit.next(); + RelationDirTableModel.TableRow tr = ecdtm.new TableRow(); tr.relation = aug.relation; - tr.isDir = reducedMap_.get(aug); + tr.isDir = (Boolean)reducedMap_.get(aug); retval.add(tr); } return (retval); @@ -311,11 +316,11 @@ protected boolean stashForOK() { reducedMap_.clear(); return (true); } - EditableTable.TableModel ecdtm = est_.getModel(); - List vals = ecdtm.getValuesFromTable(); + RelationDirTableModel ecdtm = (RelationDirTableModel)est_.getModel(); + List vals = ecdtm.getValuesFromTable(); int numVals = vals.size(); for (int i = 0; i < numVals; i++) { - RelationDirTableModel.TableRow tr = vals.get(i); + RelationDirTableModel.TableRow tr = (RelationDirTableModel.TableRow)vals.get(i); reducedMap_.put(new FabricLink.AugRelation(tr.relation, false), tr.isDir); } return (true); diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/ReorderLayoutParamsDialog.java b/src/org/systemsbiology/biotapestry/biofabric/ReorderLayoutParamsDialog.java similarity index 88% rename from src/org/systemsbiology/biofabric/ui/dialogs/ReorderLayoutParamsDialog.java rename to src/org/systemsbiology/biotapestry/biofabric/ReorderLayoutParamsDialog.java index 87c90ce..b056720 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/ReorderLayoutParamsDialog.java +++ b/src/org/systemsbiology/biotapestry/biofabric/ReorderLayoutParamsDialog.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.ui.dialogs; +package org.systemsbiology.biotapestry.biofabric; import java.awt.Dimension; import java.awt.event.ActionListener; @@ -29,11 +29,10 @@ import javax.swing.JLabel; import javax.swing.JOptionPane; -import org.systemsbiology.biofabric.layouts.NodeSimilarityLayout; -import org.systemsbiology.biofabric.ui.dialogs.utils.BTStashResultsDialog; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; +import org.systemsbiology.biotapestry.ui.dialogs.utils.BTStashResultsDialog; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ExceptionHandler; /**************************************************************************** ** @@ -56,7 +55,7 @@ public class ReorderLayoutParamsDialog extends BTStashResultsDialog { private JTextField numPassesField_; private JCheckBox termAtIncreaseBox_; - private NodeSimilarityLayout.ResortParams results_; + private ClusteredLayout.ResortParams results_; //////////////////////////////////////////////////////////////////////////// // @@ -69,7 +68,7 @@ public class ReorderLayoutParamsDialog extends BTStashResultsDialog { ** Constructor */ - public ReorderLayoutParamsDialog(JFrame parent, NodeSimilarityLayout.ResortParams params) { + public ReorderLayoutParamsDialog(JFrame parent, ClusteredLayout.ResortParams params) { super(parent, "clusteredLayout.reorderTitle", new Dimension(600, 300), 2); ResourceManager rMan = ResourceManager.getManager(); parent_ = parent; @@ -113,7 +112,7 @@ public void actionPerformed(ActionEvent ev) { ** Get results */ - public NodeSimilarityLayout.ResortParams getParams() { + public ClusteredLayout.ResortParams getParams() { return (results_); } @@ -131,7 +130,7 @@ public NodeSimilarityLayout.ResortParams getParams() { protected boolean stashForOK() { - results_ = new NodeSimilarityLayout.ResortParams(); + results_ = new ClusteredLayout.ResortParams(); String passStr = numPassesField_.getText(); Integer passes = parseInteger(passStr, "clusteredLayout.badPass"); @@ -185,7 +184,7 @@ private Integer parseInteger(String intVal, String badMsg) { */ private void resetDefaults() { - NodeSimilarityLayout.ResortParams defaults = new NodeSimilarityLayout.ResortParams(); + ClusteredLayout.ResortParams defaults = new ClusteredLayout.ResortParams(); numPassesField_.setText(Integer.toString(defaults.passCount)); termAtIncreaseBox_.setSelected(defaults.terminateAtIncrease); return; diff --git a/src/org/systemsbiology/biotapestry/biofabric/SelectionSupport.java b/src/org/systemsbiology/biotapestry/biofabric/SelectionSupport.java new file mode 100644 index 0000000..71bb9de --- /dev/null +++ b/src/org/systemsbiology/biotapestry/biofabric/SelectionSupport.java @@ -0,0 +1,381 @@ +/* +** Copyright (C) 2003-2011 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +package org.systemsbiology.biotapestry.biofabric; + +import java.util.Arrays; +import java.util.List; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import javax.swing.SwingUtilities; + + +/**************************************************************************** +** +** Used for gaggle selection support +*/ + +public class SelectionSupport { + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + private Set pendingSelections_; + private List inboundNetwork_; + private NetworkForSpecies outboundNetwork_; + private String species_; + private BioFabricWindow bfw_; + private ArrayList commands_; + private ArrayList gooseList_; + private boolean initGooseList_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Constructor + */ + + public SelectionSupport(BioFabricWindow bfw, String species) { + bfw_ = bfw; + species_ = species; + commands_ = new ArrayList(); + gooseList_ = new ArrayList(); + pendingSelections_ = new HashSet(); + initGooseList_ = true; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC METHODS + // + //////////////////////////////////////////////////////////////////////////// + + + /*************************************************************************** + ** + ** Set the species + */ + + public synchronized void setSpecies(String species) { + species_ = species; + return; + } + + /*************************************************************************** + ** + ** Get the species + */ + + public synchronized String getSpecies() { + return (species_); + } + + /*************************************************************************** + ** + ** Get the pending command list + */ + + public synchronized List getPendingCommands() { + ArrayList pending = commands_; + commands_ = new ArrayList(); + return (pending); + } + + /*************************************************************************** + ** + ** Let us know what the current goose list is + */ + + public synchronized void registerNewGooseList(List gooseList) { + gooseList_.clear(); + gooseList_.addAll(gooseList); + if (initGooseList_) { + initGooseList_ = false; + } else { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + bfw_.haveGaggleGooseChange(); + } + }); + } + return; + } + + /*************************************************************************** + ** + ** Get the current goose list + */ + + public synchronized List getGooseList() { + return (new ArrayList(gooseList_)); + } + + /*************************************************************************** + ** + ** Create a new network + */ + + public synchronized void createNewNetwork(String species, List links, List loneNodes) { + InboundNetworkOp op = new InboundNetworkOp(species, links, loneNodes); + commands_.add(op); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + bfw_.haveInboundGaggleCommands(); + } + }); + + return; + } + + /*************************************************************************** + ** + ** Register an unsupported command + */ + + public synchronized void addUnsupportedCommand() { + InboundGaggleOp op = new InboundGaggleOp(bfw_); + commands_.add(op); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + bfw_.haveInboundGaggleCommands(); + } + }); + return; + } + + /*************************************************************************** + ** + ** Register a selection command + */ + + public synchronized void addSelectionCommand(String species, String[] selections) { + HashSet newSelections = new HashSet(Arrays.asList(selections)); + SelectionSupport.SelectionsForSpecies sfs = new SelectionsForSpecies(species, newSelections); + InboundSelectionOp op = new InboundSelectionOp(bfw_, sfs); + commands_.add(op); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + bfw_.haveInboundGaggleCommands(); + } + }); + return; + } + + /*************************************************************************** + ** + ** Register a selection command + */ + + public synchronized void changeConnectionStatus(boolean connected) { + InboundConnectionOp op = new InboundConnectionOp(bfw_, connected); + commands_.add(op); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + bfw_.haveInboundGaggleCommands(); + } + }); + return; + } + + /*************************************************************************** + ** + ** Clear the selections + */ + + public synchronized void clearSelections() { + SelectionSupport.SelectionsForSpecies sfs = new SelectionsForSpecies(species_, new HashSet()); + InboundSelectionOp op = new InboundSelectionOp(bfw_, sfs); + commands_.add(op); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + bfw_.haveInboundGaggleCommands(); + } + }); + return; + } + + /*************************************************************************** + ** + ** Get the selections + */ + + public synchronized SelectionsForSpecies getSelections() { + return (new SelectionsForSpecies(species_, new HashSet(pendingSelections_))); + } + + /*************************************************************************** + ** + ** Set outbound network + */ + + public synchronized void setOutboundNetwork(NetworkForSpecies network) { + outboundNetwork_ = (network == null) ? null : (NetworkForSpecies)network.clone(); + if (outboundNetwork_ != null) { + outboundNetwork_.setSpecies(species_); + } + return; + } + + /*************************************************************************** + ** + ** Get the network + */ + + public synchronized NetworkForSpecies getOutboundNetwork() { + return ((outboundNetwork_ == null) ? null : (NetworkForSpecies)outboundNetwork_.clone()); + } + + /*************************************************************************** + ** + ** Set the selections + */ + + public synchronized void setSelections(List selections) { + pendingSelections_.clear(); + pendingSelections_.addAll(selections); + return; + } + + /*************************************************************************** + ** + ** Get the selection count + */ + + public synchronized int getSelectionCount() { + return (pendingSelections_.size()); + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CLASS METHODS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** returns info all at once for concurrency protection + */ + + public static class SelectionsForSpecies { + public String species; + public Set selections; + + SelectionsForSpecies(String species, Set selections) { + this.species = species; + this.selections = selections; + } + } + + /*************************************************************************** + ** + ** Returns a defined network + */ + + public static class NetworkForSpecies implements Cloneable { + private String species_; + private List links_; + private List singletons_; + + private NetworkForSpecies(String species, List reqLinks, List singletons) { + species_ = species; + links_ = reqLinks; + singletons_ = singletons; + } + + public NetworkForSpecies() { + this(null, new ArrayList(), new ArrayList()); + } + + public NetworkForSpecies(List reqLinks, List singletons) { + this(null, reqLinks, singletons); + } + + public Object clone() { + try { + NetworkForSpecies retval = (NetworkForSpecies)super.clone(); + retval.links_ = new ArrayList(); + int numLinks = this.links_.size(); + for (int i = 0; i < numLinks; i++) { + retval.links_.add(((FabricLink)this.links_.get(i)).clone()); + } + retval.singletons_ = new ArrayList(singletons_); + return (retval); + } catch (CloneNotSupportedException cnse) { + throw new IllegalStateException(); + } + + } + + void setSpecies(String species) { + species_ = species; + return; + } + + public String getSpecies() { + return (species_); + } + + public List getLinks() { + return (links_); + } + + public List getSingletons() { + return (singletons_); + } + } + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE INNER CLASSES + // + //////////////////////////////////////////////////////////////////////////// +} diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/UpdateJavaDialog.java b/src/org/systemsbiology/biotapestry/biofabric/UpdateJavaDialog.java similarity index 97% rename from src/org/systemsbiology/biofabric/ui/dialogs/UpdateJavaDialog.java rename to src/org/systemsbiology/biotapestry/biofabric/UpdateJavaDialog.java index fa055ea..fa1bbe7 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/UpdateJavaDialog.java +++ b/src/org/systemsbiology/biotapestry/biofabric/UpdateJavaDialog.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.ui.dialogs; +package org.systemsbiology.biotapestry.biofabric; import java.awt.Dimension; import java.awt.Frame; @@ -34,7 +34,7 @@ import javax.swing.JPanel; import javax.swing.border.EmptyBorder; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.UiUtil; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/images/About24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/About24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/About24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/About24.gif diff --git a/src/org/systemsbiology/biofabric/images/Back24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/Back24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/Back24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/Back24.gif diff --git a/src/org/systemsbiology/biofabric/images/BioFab16White.gif b/src/org/systemsbiology/biotapestry/biofabric/images/BioFab16White.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/BioFab16White.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/BioFab16White.gif diff --git a/src/org/systemsbiology/biofabric/images/C24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/C24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/C24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/C24.gif diff --git a/src/org/systemsbiology/biofabric/images/ClearFabricSelected24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/ClearFabricSelected24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/ClearFabricSelected24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/ClearFabricSelected24.gif diff --git a/src/org/systemsbiology/biofabric/images/D24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/D24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/D24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/D24.gif diff --git a/src/org/systemsbiology/biofabric/images/Find24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/Find24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/Find24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/Find24.gif diff --git a/src/org/systemsbiology/biofabric/images/Forward24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/Forward24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/Forward24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/Forward24.gif diff --git a/src/org/systemsbiology/biofabric/images/H24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/H24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/H24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/H24.gif diff --git a/src/org/systemsbiology/biofabric/images/L24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/L24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/L24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/L24.gif diff --git a/src/org/systemsbiology/biofabric/images/MacBlank.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacBlank.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacBlank.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacBlank.gif diff --git a/src/org/systemsbiology/biofabric/images/MacC.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacC.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacC.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacC.gif diff --git a/src/org/systemsbiology/biofabric/images/MacD.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacD.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacD.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacD.gif diff --git a/src/org/systemsbiology/biofabric/images/MacGT.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacGT.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacGT.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacGT.gif diff --git a/src/org/systemsbiology/biofabric/images/MacL.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacL.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacL.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacL.gif diff --git a/src/org/systemsbiology/biofabric/images/MacLT.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacLT.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacLT.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacLT.gif diff --git a/src/org/systemsbiology/biofabric/images/MacN.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacN.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacN.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacN.gif diff --git a/src/org/systemsbiology/biofabric/images/MacR.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacR.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacR.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacR.gif diff --git a/src/org/systemsbiology/biofabric/images/MacS.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacS.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacS.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacS.gif diff --git a/src/org/systemsbiology/biofabric/images/MacU.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacU.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacU.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacU.gif diff --git a/src/org/systemsbiology/biofabric/images/MacZ.gif b/src/org/systemsbiology/biotapestry/biofabric/images/MacZ.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/MacZ.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/MacZ.gif diff --git a/src/org/systemsbiology/biofabric/images/N24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/N24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/N24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/N24.gif diff --git a/src/org/systemsbiology/biofabric/images/P24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/P24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/P24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/P24.gif diff --git a/src/org/systemsbiology/biofabric/images/P24Selected.gif b/src/org/systemsbiology/biotapestry/biofabric/images/P24Selected.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/P24Selected.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/P24Selected.gif diff --git a/src/org/systemsbiology/biofabric/images/PlusOneDeg24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/PlusOneDeg24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/PlusOneDeg24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/PlusOneDeg24.gif diff --git a/src/org/systemsbiology/biofabric/images/Print24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/Print24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/Print24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/Print24.gif diff --git a/src/org/systemsbiology/biofabric/images/PropagateSelected24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/PropagateSelected24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/PropagateSelected24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/PropagateSelected24.gif diff --git a/src/org/systemsbiology/biofabric/images/S24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/S24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/S24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/S24.gif diff --git a/src/org/systemsbiology/biofabric/images/Save24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/Save24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/Save24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/Save24.gif diff --git a/src/org/systemsbiology/biofabric/images/SaveAs24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/SaveAs24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/SaveAs24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/SaveAs24.gif diff --git a/src/org/systemsbiology/biofabric/images/Stop24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/Stop24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/Stop24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/Stop24.gif diff --git a/src/org/systemsbiology/biofabric/images/U24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/U24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/U24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/U24.gif diff --git a/src/org/systemsbiology/biofabric/images/U24Selected.gif b/src/org/systemsbiology/biotapestry/biofabric/images/U24Selected.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/U24Selected.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/U24Selected.gif diff --git a/src/org/systemsbiology/biofabric/images/ZoomIn24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/ZoomIn24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/ZoomIn24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/ZoomIn24.gif diff --git a/src/org/systemsbiology/biofabric/images/ZoomOut24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/ZoomOut24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/ZoomOut24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/ZoomOut24.gif diff --git a/src/org/systemsbiology/biofabric/images/ZoomToAllFabric24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/ZoomToAllFabric24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/ZoomToAllFabric24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/ZoomToAllFabric24.gif diff --git a/src/org/systemsbiology/biofabric/images/ZoomToAllFabricSelected24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/ZoomToAllFabricSelected24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/ZoomToAllFabricSelected24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/ZoomToAllFabricSelected24.gif diff --git a/src/org/systemsbiology/biofabric/images/ZoomToFabricRect24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/ZoomToFabricRect24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/ZoomToFabricRect24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/ZoomToFabricRect24.gif diff --git a/src/org/systemsbiology/biofabric/images/ZoomToFabricSelected24.gif b/src/org/systemsbiology/biotapestry/biofabric/images/ZoomToFabricSelected24.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/ZoomToFabricSelected24.gif rename to src/org/systemsbiology/biotapestry/biofabric/images/ZoomToFabricSelected24.gif diff --git a/src/org/systemsbiology/biofabric/license/LICENSE b/src/org/systemsbiology/biotapestry/biofabric/license/LICENSE similarity index 100% rename from src/org/systemsbiology/biofabric/license/LICENSE rename to src/org/systemsbiology/biotapestry/biofabric/license/LICENSE diff --git a/src/org/systemsbiology/biofabric/license/LICENSE-SUN b/src/org/systemsbiology/biotapestry/biofabric/license/LICENSE-SUN similarity index 100% rename from src/org/systemsbiology/biofabric/license/LICENSE-SUN rename to src/org/systemsbiology/biotapestry/biofabric/license/LICENSE-SUN diff --git a/src/org/systemsbiology/biofabric/license/about.html b/src/org/systemsbiology/biotapestry/biofabric/license/about.html similarity index 100% rename from src/org/systemsbiology/biofabric/license/about.html rename to src/org/systemsbiology/biotapestry/biofabric/license/about.html diff --git a/src/org/systemsbiology/biofabric/cmd/BTUndoCmd.java b/src/org/systemsbiology/biotapestry/cmd/BTUndoCmd.java similarity index 94% rename from src/org/systemsbiology/biofabric/cmd/BTUndoCmd.java rename to src/org/systemsbiology/biotapestry/cmd/BTUndoCmd.java index 2ad7306..afc7c3a 100644 --- a/src/org/systemsbiology/biofabric/cmd/BTUndoCmd.java +++ b/src/org/systemsbiology/biotapestry/cmd/BTUndoCmd.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.cmd; +package org.systemsbiology.biotapestry.cmd; import javax.swing.undo.AbstractUndoableEdit; diff --git a/src/org/systemsbiology/biofabric/cmd/CompoundPostEventCmd2.java b/src/org/systemsbiology/biotapestry/cmd/CompoundPostEventCmd2.java similarity index 70% rename from src/org/systemsbiology/biofabric/cmd/CompoundPostEventCmd2.java rename to src/org/systemsbiology/biotapestry/cmd/CompoundPostEventCmd2.java index c8c56df..540346b 100644 --- a/src/org/systemsbiology/biofabric/cmd/CompoundPostEventCmd2.java +++ b/src/org/systemsbiology/biotapestry/cmd/CompoundPostEventCmd2.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2010 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -18,15 +18,17 @@ */ -package org.systemsbiology.biofabric.cmd; +package org.systemsbiology.biotapestry.cmd; import java.util.ArrayList; -import org.systemsbiology.biofabric.event.ChangeEvent; -import org.systemsbiology.biofabric.event.EventManager; -import org.systemsbiology.biofabric.event.LayoutChangeEvent; -import org.systemsbiology.biofabric.event.SelectionChangeEvent; - +import org.systemsbiology.biotapestry.event.GeneralChangeEvent; +import org.systemsbiology.biotapestry.event.ChangeEvent; +import org.systemsbiology.biotapestry.event.LayoutChangeEvent; +import org.systemsbiology.biotapestry.event.ModelChangeEvent; +import org.systemsbiology.biotapestry.event.SelectionChangeEvent; +import org.systemsbiology.biotapestry.event.EventManager; +import org.systemsbiology.biotapestry.event.OverlayDisplayChangeEvent; /**************************************************************************** ** ** Does eventing following Compound Editing redo @@ -119,13 +121,31 @@ public void redo() { public void execute() { EventManager mgr = EventManager.getManager(); int num = ev_.size(); + int numMCE = 0; + for (int i = 0; i < num; i++) { + ChangeEvent ce = (ChangeEvent)ev_.get(i); + if (ce instanceof ModelChangeEvent) { + numMCE++; + } + } + + // + // For better performance, some listeners who pay no attention to + // the contents of a model change only care about last event: + // for (int i = 0; i < num; i++) { ChangeEvent ce = (ChangeEvent)ev_.get(i); - if (ce instanceof LayoutChangeEvent) { + if (ce instanceof GeneralChangeEvent) { + mgr.sendGeneralChangeEvent((GeneralChangeEvent)ce); + } else if (ce instanceof LayoutChangeEvent) { mgr.sendLayoutChangeEvent((LayoutChangeEvent)ce); + } else if (ce instanceof ModelChangeEvent) { + mgr.sendModelChangeEvent((ModelChangeEvent)ce, --numMCE); } else if (ce instanceof SelectionChangeEvent) { mgr.sendSelectionChangeEvent((SelectionChangeEvent)ce); + } else if (ce instanceof OverlayDisplayChangeEvent) { + mgr.sendOverlayDisplayChangeEvent((OverlayDisplayChangeEvent)ce); } else { throw new IllegalArgumentException(); } diff --git a/src/org/systemsbiology/biofabric/cmd/CompoundPreEventCmd.java b/src/org/systemsbiology/biotapestry/cmd/CompoundPreEventCmd.java similarity index 73% rename from src/org/systemsbiology/biofabric/cmd/CompoundPreEventCmd.java rename to src/org/systemsbiology/biotapestry/cmd/CompoundPreEventCmd.java index c9708f3..8d72823 100644 --- a/src/org/systemsbiology/biofabric/cmd/CompoundPreEventCmd.java +++ b/src/org/systemsbiology/biotapestry/cmd/CompoundPreEventCmd.java @@ -18,14 +18,17 @@ */ -package org.systemsbiology.biofabric.cmd; +package org.systemsbiology.biotapestry.cmd; import java.util.ArrayList; -import org.systemsbiology.biofabric.event.ChangeEvent; -import org.systemsbiology.biofabric.event.EventManager; -import org.systemsbiology.biofabric.event.LayoutChangeEvent; -import org.systemsbiology.biofabric.event.SelectionChangeEvent; +import org.systemsbiology.biotapestry.event.ChangeEvent; +import org.systemsbiology.biotapestry.event.GeneralChangeEvent; +import org.systemsbiology.biotapestry.event.LayoutChangeEvent; +import org.systemsbiology.biotapestry.event.ModelChangeEvent; +import org.systemsbiology.biotapestry.event.SelectionChangeEvent; +import org.systemsbiology.biotapestry.event.EventManager; +import org.systemsbiology.biotapestry.event.OverlayDisplayChangeEvent; /**************************************************************************** ** @@ -97,6 +100,13 @@ public void undo() { super.undo(); EventManager mgr = EventManager.getManager(); int num = ev_.size(); + int numMCE = 0; + for (int i = 0; i < num; i++) { + ChangeEvent ce = (ChangeEvent)ev_.get(i); + if (ce instanceof ModelChangeEvent) { + numMCE++; + } + } // // For better performance, some listeners who pay no attention to @@ -105,10 +115,16 @@ public void undo() { for (int i = num - 1; i >= 0; i--) { ChangeEvent ce = (ChangeEvent)ev_.get(i); - if (ce instanceof LayoutChangeEvent) { + if (ce instanceof GeneralChangeEvent) { + mgr.sendGeneralChangeEvent((GeneralChangeEvent)ce); + } else if (ce instanceof LayoutChangeEvent) { mgr.sendLayoutChangeEvent((LayoutChangeEvent)ce); + } else if (ce instanceof ModelChangeEvent) { + mgr.sendModelChangeEvent((ModelChangeEvent)ce, --numMCE); } else if (ce instanceof SelectionChangeEvent) { mgr.sendSelectionChangeEvent((SelectionChangeEvent)ce); + } else if (ce instanceof OverlayDisplayChangeEvent) { + mgr.sendOverlayDisplayChangeEvent((OverlayDisplayChangeEvent)ce); } else { throw new IllegalArgumentException(); } diff --git a/src/org/systemsbiology/biofabric/cmd/ZoomChangeTracker.java b/src/org/systemsbiology/biotapestry/cmd/ZoomChangeTracker.java similarity index 94% rename from src/org/systemsbiology/biofabric/cmd/ZoomChangeTracker.java rename to src/org/systemsbiology/biotapestry/cmd/ZoomChangeTracker.java index 8a93bc8..1bfdacb 100644 --- a/src/org/systemsbiology/biofabric/cmd/ZoomChangeTracker.java +++ b/src/org/systemsbiology/biotapestry/cmd/ZoomChangeTracker.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.cmd; +package org.systemsbiology.biotapestry.cmd; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/cmd/ZoomCommandSupport.java b/src/org/systemsbiology/biotapestry/cmd/ZoomCommandSupport.java similarity index 90% rename from src/org/systemsbiology/biofabric/cmd/ZoomCommandSupport.java rename to src/org/systemsbiology/biotapestry/cmd/ZoomCommandSupport.java index 24f8de1..25f7e99 100644 --- a/src/org/systemsbiology/biofabric/cmd/ZoomCommandSupport.java +++ b/src/org/systemsbiology/biotapestry/cmd/ZoomCommandSupport.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,8 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.cmd; + +package org.systemsbiology.biotapestry.cmd; import java.awt.Point; import java.awt.Dimension; @@ -27,14 +28,12 @@ import java.awt.Rectangle; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; -import java.awt.event.HierarchyEvent; -import java.awt.event.HierarchyListener; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; -import org.systemsbiology.biofabric.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.ExceptionHandler; /**************************************************************************** ** @@ -121,7 +120,6 @@ public void registerScrollPaneAndZoomTarget(JScrollPane jsp, ZoomTarget sup) { // Need to make view adjustments when the scroll pane size changes: // jsp.addComponentListener(new ComponentAdapter() { - @Override public void componentResized(ComponentEvent e) { try { handlePanelResize(); @@ -143,31 +141,11 @@ public void stateChanged(ChangeEvent e) { } } }; - - // - // Having scroll bars come and go makes the actual view extent - // change without any window size change: this happens with - // zooming, causing bug #16. Track when it comes and goes: - - HierarchyListener hChange = new HierarchyListener() { - public void hierarchyChanged(HierarchyEvent e) { - try { - if ((e.getID() == HierarchyEvent.HIERARCHY_CHANGED) && - ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0x00)) { - checkBarVisible(); - } - } catch (Exception ex) { - ExceptionHandler.getHandler().displayException(ex); - } - } - }; JScrollBar vsb = jsp.getVerticalScrollBar(); - vsb.getModel().addChangeListener(barChange); - vsb.addHierarchyListener(hChange); + vsb.getModel().addChangeListener(barChange); JScrollBar hsb = jsp.getHorizontalScrollBar(); - hsb.getModel().addChangeListener(barChange); - hsb.addHierarchyListener(hChange); + hsb.getModel().addChangeListener(barChange); return; } @@ -181,7 +159,7 @@ private ZoomResult calcOptimalZoom(Rectangle chosen) { Dimension dim; if (chosen == null) { - dim = sup_.getBasicSize(); + dim = sup_.getBasicSize(true, false, ZoomTarget.VISIBLE_MODULES); } else { dim = new Dimension(chosen.width, chosen.height); } @@ -320,7 +298,7 @@ private void viewportUpdate(Point center, Dimension vDim) { view.setViewSize(sup_.getPreferredSize()); view.setViewPosition(boundedViewPos(center, vDim, view)); view.invalidate(); - jsp_.validate(); + jsp_.validate(); return; } @@ -460,11 +438,14 @@ public void setCurrentZoomForNewModel() { private void setCurrentZoom(ZoomResult zres) { /* int delay = 100; + System.out.println("Setting a timer"); Timer zoomTimer = new Timer(delay, new ActionListener() { public void actionPerformed(ActionEvent evt) { + System.out.println("action " + evt); } }); zoomTimer.start(); + System.out.println("Started a timer"); */ if (zres.doCustom) { @@ -738,7 +719,7 @@ private Rectangle centeredUnion(Rectangle union, Point2D center) { */ public void zoomToModel() { - Rectangle bounds = sup_.getCurrentBasicBounds(); + Rectangle bounds = sup_.getCurrentBasicBounds(true, false, ZoomTarget.VISIBLE_MODULES); Rectangle wsBounds = sup_.getWorkspaceBounds(); Rectangle union = wsBounds.union(bounds); if (!union.equals(wsBounds)) { // i.e. part of model outside of workspace: we will center on workspace @@ -801,8 +782,8 @@ public void handlePanelResize() { Dimension viewExtent = view.getExtentSize(); Dimension viewSize = view.getViewSize(); - int currX = (int)Math.round((currViewXFrac_ * viewSize.width) - (viewExtent.width / 2.0)); - int currY = (int)Math.round((currViewYFrac_ * viewSize.height) - (viewExtent.height / 2.0)); + int currX = (int)Math.round((currViewXFrac_ * (double)viewSize.width) - ((double)viewExtent.width / 2.0)); + int currY = (int)Math.round((currViewYFrac_ * (double)viewSize.height) - ((double)viewExtent.height / 2.0)); view.setViewPosition(doBounding(currX, currY, view)); // @@ -824,13 +805,11 @@ public void handlePanelResize() { */ public void trackScrollBars() { - JViewport view = jsp_.getViewport(); Dimension viewExtent = view.getExtentSize(); if (currViewSize_ == null) { currViewSize_ = viewExtent; } - if (viewExtent.equals(currViewSize_)) { Point viewPos = view.getViewPosition(); int currX = viewPos.x + (viewExtent.width / 2); @@ -843,18 +822,6 @@ public void trackScrollBars() { if (tracker_ != null) tracker_.zoomStateChanged(true); return; } - - /*************************************************************************** - ** - ** We need to know when scroll bar visibility changes, since we need to - ** always have an accurate read on extent size (Fixes issue #16) - */ - - public void checkBarVisible() { - JViewport view = jsp_.getViewport(); - currViewSize_ = view.getExtentSize(); - return; - } //////////////////////////////////////////////////////////////////////////// // diff --git a/src/org/systemsbiology/biofabric/cmd/ZoomTarget.java b/src/org/systemsbiology/biotapestry/cmd/ZoomTarget.java similarity index 80% rename from src/org/systemsbiology/biofabric/cmd/ZoomTarget.java rename to src/org/systemsbiology/biotapestry/cmd/ZoomTarget.java index b39214f..29682f3 100644 --- a/src/org/systemsbiology/biofabric/cmd/ZoomTarget.java +++ b/src/org/systemsbiology/biotapestry/cmd/ZoomTarget.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2016 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.cmd; +package org.systemsbiology.biotapestry.cmd; import java.awt.Dimension; import java.awt.Point; @@ -25,7 +25,7 @@ import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; -import org.systemsbiology.biofabric.util.UndoSupport; +import org.systemsbiology.biotapestry.util.UndoSupport; /**************************************************************************** ** @@ -39,7 +39,15 @@ public interface ZoomTarget { // PUBLIC CONSTANTS // //////////////////////////////////////////////////////////////////////////// + + // + // Handling options for bounding with modules: + // + public static final int NO_MODULES = 0; + public static final int VISIBLE_MODULES = 1; + public static final int ALL_MODULES = 2; + //////////////////////////////////////////////////////////////////////////// // // PUBLIC INSTANCE METHODS @@ -63,11 +71,11 @@ public interface ZoomTarget { public Dimension getPreferredSize(); public void fixCenterPoint(boolean doComplete, UndoSupport support, boolean closeIt); public void repaint(); - public Dimension getBasicSize(); + public Dimension getBasicSize(boolean doComplete, boolean doBuffer, int moduleHandling); public Point2D viewToWorld(Point vPt); public void setWideZoomFactor(double newZoomVal, Dimension vDim); public double getWorkspaceZoom(Dimension viewportDim, double percent); - public Rectangle getCurrentBasicBounds(); + public Rectangle getCurrentBasicBounds(boolean doComplete, boolean doBuffer, int moduleHandling); public Rectangle getAllModelBounds(); public void adjustWideZoomForSize(Dimension dims); public Point getCenterPoint(); diff --git a/src/org/systemsbiology/biofabric/db/ColorGenerator.java b/src/org/systemsbiology/biotapestry/db/ColorGenerator.java similarity index 92% rename from src/org/systemsbiology/biofabric/db/ColorGenerator.java rename to src/org/systemsbiology/biotapestry/db/ColorGenerator.java index f77353e..52371fc 100644 --- a/src/org/systemsbiology/biofabric/db/ColorGenerator.java +++ b/src/org/systemsbiology/biotapestry/db/ColorGenerator.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.db; +package org.systemsbiology.biotapestry.db; import java.util.HashMap; import java.util.HashSet; @@ -30,9 +30,9 @@ import java.io.PrintWriter; import java.util.Arrays; -import org.systemsbiology.biofabric.ui.NamedColor; -import org.systemsbiology.biofabric.util.Indenter; -import org.systemsbiology.biofabric.util.UniqueLabeller; +import org.systemsbiology.biotapestry.util.Indenter; +import org.systemsbiology.biotapestry.util.UniqueLabeller; +import org.systemsbiology.biotapestry.ui.NamedColor; /**************************************************************************** ** @@ -48,7 +48,7 @@ public class ColorGenerator { //////////////////////////////////////////////////////////////////////////// private UniqueLabeller colorLabels_; - private Map colors_; + private Map colors_; private String[] geneCol_ = new String[] { "EX-blue", @@ -142,7 +142,7 @@ public ColorGenerator() { colorLabels_.addExistingLabel("zz_newColor_0"); // Can't do this: SpEndomes has custom tags e.g. "forest" //colorLabels_.setFixedPrefix("zz_newColor_0") - colors_ = new HashMap(); + colors_ = new HashMap(); } //////////////////////////////////////////////////////////////////////////// @@ -182,7 +182,7 @@ public void dropColors() { */ public Color getColor(String colorKey) { - return (colors_.get(colorKey).color); + return (((NamedColor)colors_.get(colorKey)).color); } /*************************************************************************** @@ -191,7 +191,7 @@ public Color getColor(String colorKey) { */ public NamedColor getNamedColor(String colorKey) { - return (colors_.get(colorKey)); + return ((NamedColor)colors_.get(colorKey)); } /*************************************************************************** @@ -199,7 +199,7 @@ public NamedColor getNamedColor(String colorKey) { ** Update the color set */ - public GlobalChange updateColors(Map namedColors) { + public GlobalChange updateColors(Map namedColors) { GlobalChange retval = new GlobalChange(); retval.origColors = deepCopyColorMap(colors_); colors_ = deepCopyColorMap(namedColors); @@ -242,7 +242,7 @@ public void setColor(String itemId, NamedColor color) { ** Return an iterator over all the color keys */ - public Iterator getColorKeys() { + public Iterator getColorKeys() { return (colors_.keySet().iterator()); } @@ -251,7 +251,7 @@ public Iterator getColorKeys() { ** Return gene colors as list */ - public List getGeneColorsAsList() { + public List getGeneColorsAsList() { return (Arrays.asList(geneCol_)); } @@ -284,8 +284,8 @@ public void changeRedo(GlobalChange undo) { ** Return the colors you cannot delete */ - public Set cannotDeleteColors() { - HashSet retval = new HashSet(); + public Set cannotDeleteColors() { + HashSet retval = new HashSet(); retval.add("white"); //retval.add("red"); // This is handled now by EX-red retval.add("black"); @@ -396,7 +396,7 @@ public int getNumColors() { */ private void buildDefaultColors() { - colors_ = new HashMap(); + colors_ = new HashMap(); colors_.put("inactiveLightBlue", new NamedColor("inactiveLightBlue", new Color(235, 235, 250), "Very Light Blue")); colorLabels_.addExistingLegacyLabel("inactiveLightBlue"); colors_.put("white", new NamedColor("white", new Color(255, 255, 255), "White")); @@ -428,10 +428,10 @@ private void buildDefaultColors() { colors_.put("lightPurple", new NamedColor("lightPurple", new Color(235, 219, 229), "Light Purple")); colorLabels_.addExistingLegacyLabel("lightPurple"); - List geneColors = buildGeneColors(); + List geneColors = buildGeneColors(); int geneColSize = geneColors.size(); for (int i = 0; i < geneColSize; i++) { - NamedColor col = geneColors.get(i); + NamedColor col = (NamedColor)geneColors.get(i); colors_.put(col.key, col); colorLabels_.addExistingLegacyLabel(col.key); } @@ -454,10 +454,10 @@ private void writeColors(PrintWriter out, Indenter ind) { ind.indent(); out.println(""); ind.up(); - Iterator colors = colors_.keySet().iterator(); + Iterator colors = colors_.keySet().iterator(); while (colors.hasNext()) { - String key = colors.next(); - NamedColor nc = colors_.get(key); + String key = (String)colors.next(); + NamedColor nc = (NamedColor)colors_.get(key); Color c = nc.color; ind.indent(); out.print(" buildGeneColors() { + private List buildGeneColors() { - ArrayList colors = new ArrayList(); + ArrayList colors = new ArrayList(); colors.add(new NamedColor("EX-red", Color.getHSBColor(0.0F, 1.0F, 1.0F), "Bright Red")); colors.add(new NamedColor("EX-pale-red-orange", Color.getHSBColor(0.033F, 0.4F, 0.9F), "Dark Salmon")); colors.add(new NamedColor("EX-orange", Color.getHSBColor(0.067F, 1.0F, 1.0F), "Pumpkin Orange")); @@ -528,13 +528,13 @@ private List buildGeneColors() { ** Write the note properties to XML */ - private HashMap deepCopyColorMap(Map otherMap) { - HashMap retval = new HashMap(); - Set keys = otherMap.keySet(); - Iterator kit = keys.iterator(); + private HashMap deepCopyColorMap(Map otherMap) { + HashMap retval = new HashMap(); + Set keys = otherMap.keySet(); + Iterator kit = keys.iterator(); while (kit.hasNext()) { - String key = kit.next(); - NamedColor col = otherMap.get(key); + String key = (String)kit.next(); + NamedColor col = (NamedColor)otherMap.get(key); retval.put(new String(key), new NamedColor(col)); } return (retval); diff --git a/src/org/systemsbiology/biofabric/db/GlobalChange.java b/src/org/systemsbiology/biotapestry/db/GlobalChange.java similarity index 81% rename from src/org/systemsbiology/biofabric/db/GlobalChange.java rename to src/org/systemsbiology/biotapestry/db/GlobalChange.java index 3bbd3c8..8c7e1e0 100644 --- a/src/org/systemsbiology/biofabric/db/GlobalChange.java +++ b/src/org/systemsbiology/biotapestry/db/GlobalChange.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2016 Institute for Systems Biology +** Copyright (C) 2003-2004 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,18 +17,16 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.db; +package org.systemsbiology.biotapestry.db; import java.util.Map; -import org.systemsbiology.biofabric.ui.NamedColor; - /*************************************************************************** ** ** Info needed to undo a global change (e.g. color, fonts); */ public class GlobalChange { - public Map origColors; - public Map newColors; + public Map origColors; + public Map newColors; } diff --git a/src/org/systemsbiology/biofabric/db/SimpleWorkspaceSource.java b/src/org/systemsbiology/biotapestry/db/SimpleWorkspaceSource.java similarity index 97% rename from src/org/systemsbiology/biofabric/db/SimpleWorkspaceSource.java rename to src/org/systemsbiology/biotapestry/db/SimpleWorkspaceSource.java index be3c4ee..b7f0536 100644 --- a/src/org/systemsbiology/biofabric/db/SimpleWorkspaceSource.java +++ b/src/org/systemsbiology/biotapestry/db/SimpleWorkspaceSource.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.db; +package org.systemsbiology.biotapestry.db; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/db/Workspace.java b/src/org/systemsbiology/biotapestry/db/Workspace.java similarity index 97% rename from src/org/systemsbiology/biofabric/db/Workspace.java rename to src/org/systemsbiology/biotapestry/db/Workspace.java index 6d49c0d..9160274 100644 --- a/src/org/systemsbiology/biofabric/db/Workspace.java +++ b/src/org/systemsbiology/biotapestry/db/Workspace.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.db; +package org.systemsbiology.biotapestry.db; import java.awt.Dimension; import java.awt.Rectangle; @@ -27,11 +27,11 @@ import org.xml.sax.Attributes; -import org.systemsbiology.biofabric.parser.AbstractFactoryClient; -import org.systemsbiology.biofabric.util.AttributeExtractor; -import org.systemsbiology.biofabric.util.FactoryUtilWhiteboard; -import org.systemsbiology.biofabric.util.Indenter; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.Indenter; +import org.systemsbiology.biotapestry.util.UiUtil; +import org.systemsbiology.biotapestry.util.FactoryUtilWhiteboard; +import org.systemsbiology.biotapestry.parser.AbstractFactoryClient; +import org.systemsbiology.biotapestry.util.AttributeExtractor; /**************************************************************************** diff --git a/src/org/systemsbiology/biofabric/event/ChangeEvent.java b/src/org/systemsbiology/biotapestry/event/ChangeEvent.java similarity index 94% rename from src/org/systemsbiology/biofabric/event/ChangeEvent.java rename to src/org/systemsbiology/biotapestry/event/ChangeEvent.java index 006b0d9..2592501 100644 --- a/src/org/systemsbiology/biofabric/event/ChangeEvent.java +++ b/src/org/systemsbiology/biotapestry/event/ChangeEvent.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.event; +package org.systemsbiology.biotapestry.event; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/event/EventManager.java b/src/org/systemsbiology/biotapestry/event/EventManager.java similarity index 56% rename from src/org/systemsbiology/biofabric/event/EventManager.java rename to src/org/systemsbiology/biotapestry/event/EventManager.java index 840fc94..bbbf5cd 100644 --- a/src/org/systemsbiology/biofabric/event/EventManager.java +++ b/src/org/systemsbiology/biotapestry/event/EventManager.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2009 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.event; +package org.systemsbiology.biotapestry.event; import java.util.HashSet; import java.util.Iterator; @@ -37,7 +37,10 @@ public class EventManager { private static EventManager singleton_; private HashSet layoutListeners_; + private HashSet modelListeners_; private HashSet selectListeners_; + private HashSet generalListeners_; + private HashSet overlayListeners_; //////////////////////////////////////////////////////////////////////////// // @@ -84,6 +87,88 @@ public void sendLayoutChangeEvent(LayoutChangeEvent lcev) { ** Add an event listener */ + public void addGeneralChangeListener(GeneralChangeListener gcl) { + generalListeners_.add(gcl); + return; + } + + /*************************************************************************** + ** + ** Remove an event listener + */ + + public void removeGeneralChangeListener(GeneralChangeListener gcl) { + generalListeners_.remove(gcl); + return; + } + + /*************************************************************************** + ** + ** Ask for an event to be sent. + */ + + public void sendGeneralChangeEvent(GeneralChangeEvent gcev) { + Iterator gclit = generalListeners_.iterator(); + while (gclit.hasNext()) { + GeneralChangeListener gcl = (GeneralChangeListener)gclit.next(); + gcl.generalChangeOccurred(gcev); + } + return; + } + + /*************************************************************************** + ** + ** Add an event listener + */ + + public void addModelChangeListener(ModelChangeListener mcl) { + modelListeners_.add(mcl); + return; + } + + /*************************************************************************** + ** + ** Remove an event listener + */ + + public void removeModelChangeListener(ModelChangeListener mcl) { + modelListeners_.remove(mcl); + return; + } + + /*************************************************************************** + ** + ** Ask for an event to be sent. + */ + + public void sendModelChangeEvent(ModelChangeEvent mcev) { + Iterator mclit = modelListeners_.iterator(); + while (mclit.hasNext()) { + ModelChangeListener mcl = (ModelChangeListener)mclit.next(); + mcl.modelHasChanged(mcev); + } + return; + } + + /*************************************************************************** + ** + ** Ask for an event to be sent. + */ + + public void sendModelChangeEvent(ModelChangeEvent mcev, int remaining) { + Iterator mclit = modelListeners_.iterator(); + while (mclit.hasNext()) { + ModelChangeListener mcl = (ModelChangeListener)mclit.next(); + mcl.modelHasChanged(mcev, remaining); + } + return; + } + + /*************************************************************************** + ** + ** Add an event listener + */ + public void addSelectionChangeListener(SelectionChangeListener scl) { selectListeners_.add(scl); return; @@ -113,6 +198,42 @@ public void sendSelectionChangeEvent(SelectionChangeEvent scev) { return; } + /*************************************************************************** + ** + ** Add an event listener + */ + + public void addOverlayDisplayChangeListener(OverlayDisplayChangeListener odcl) { + overlayListeners_.add(odcl); + return; + } + + /*************************************************************************** + ** + ** Remove an event listener + */ + + public void removeOverlayDisplayChangeListener(OverlayDisplayChangeListener odcl) { + overlayListeners_.remove(odcl); + return; + } + + /*************************************************************************** + ** + ** Ask for an event to be sent. + */ + + public void sendOverlayDisplayChangeEvent(OverlayDisplayChangeEvent odcev) { + Iterator odclit = overlayListeners_.iterator(); + while (odclit.hasNext()) { + OverlayDisplayChangeListener odcl = (OverlayDisplayChangeListener)odclit.next(); + odcl.overlayDisplayChangeOccurred(odcev); + } + return; + } + + + //////////////////////////////////////////////////////////////////////////// // // PUBLIC STATIC METHODS @@ -144,7 +265,10 @@ public static synchronized EventManager getManager() { private EventManager() { layoutListeners_ = new HashSet(); + modelListeners_ = new HashSet(); selectListeners_ = new HashSet(); + generalListeners_ = new HashSet(); + overlayListeners_ = new HashSet(); } //////////////////////////////////////////////////////////////////////////// diff --git a/src/org/systemsbiology/biotapestry/event/GeneralChangeEvent.java b/src/org/systemsbiology/biotapestry/event/GeneralChangeEvent.java new file mode 100644 index 0000000..81c1aa5 --- /dev/null +++ b/src/org/systemsbiology/biotapestry/event/GeneralChangeEvent.java @@ -0,0 +1,97 @@ +/* +** Copyright (C) 2003-2008 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +package org.systemsbiology.biotapestry.event; + +/**************************************************************************** +** +** Used to signal general changes +*/ + +public class GeneralChangeEvent implements ChangeEvent { + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + public final static int NO_CHANGE = 0; + public final static int UNSPECIFIED_CHANGE = 1; + public final static int MODEL_DATA_CHANGE = 2; + public final static int PERTURB_DATA_CHANGE = 3; + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + private int changeType_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Build the event + */ + + public GeneralChangeEvent(int changeType) { + changeType_ = changeType; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Get the change type + */ + + public int getChangeType() { + return (changeType_); + } + + /*************************************************************************** + ** + ** Standard equals + */ + + public boolean equals(Object other) { + if (this == other) { + return (true); + } + if (other == null) { + return (false); + } + if (!(other instanceof GeneralChangeEvent)) { + return (false); + } + GeneralChangeEvent otherGCE = (GeneralChangeEvent)other; + return (this.changeType_ == otherGCE.changeType_); + } +} diff --git a/src/org/systemsbiology/biotapestry/event/GeneralChangeListener.java b/src/org/systemsbiology/biotapestry/event/GeneralChangeListener.java new file mode 100644 index 0000000..c134435 --- /dev/null +++ b/src/org/systemsbiology/biotapestry/event/GeneralChangeListener.java @@ -0,0 +1,43 @@ +/* +** Copyright (C) 2003-2004 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +package org.systemsbiology.biotapestry.event; + +/**************************************************************************** +** +** Used to listen to changes +*/ + +public interface GeneralChangeListener { + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Notify listener of model change + */ + + public void generalChangeOccurred(GeneralChangeEvent gcev); + +} diff --git a/src/org/systemsbiology/biofabric/event/LayoutChangeEvent.java b/src/org/systemsbiology/biotapestry/event/LayoutChangeEvent.java similarity index 95% rename from src/org/systemsbiology/biofabric/event/LayoutChangeEvent.java rename to src/org/systemsbiology/biotapestry/event/LayoutChangeEvent.java index 8634693..f52dad2 100644 --- a/src/org/systemsbiology/biofabric/event/LayoutChangeEvent.java +++ b/src/org/systemsbiology/biotapestry/event/LayoutChangeEvent.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.event; +package org.systemsbiology.biotapestry.event; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/event/LayoutChangeListener.java b/src/org/systemsbiology/biotapestry/event/LayoutChangeListener.java similarity index 95% rename from src/org/systemsbiology/biofabric/event/LayoutChangeListener.java rename to src/org/systemsbiology/biotapestry/event/LayoutChangeListener.java index 7d77ec5..eb7840f 100644 --- a/src/org/systemsbiology/biofabric/event/LayoutChangeListener.java +++ b/src/org/systemsbiology/biotapestry/event/LayoutChangeListener.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.event; +package org.systemsbiology.biotapestry.event; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biotapestry/event/ModelChangeEvent.java b/src/org/systemsbiology/biotapestry/event/ModelChangeEvent.java new file mode 100644 index 0000000..5a343f2 --- /dev/null +++ b/src/org/systemsbiology/biotapestry/event/ModelChangeEvent.java @@ -0,0 +1,204 @@ +/* +** Copyright (C) 2003-2009 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +package org.systemsbiology.biotapestry.event; + +/**************************************************************************** +** +** Used to signal changes in the current model +*/ + +public class ModelChangeEvent implements ChangeEvent { + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + public final static int NO_CHANGE = 0; + public final static int UNSPECIFIED_CHANGE = 1; + public final static int MODEL_DROPPED = 2; + public final static int PROPERTY_CHANGE = 3; + public final static int MODEL_ADDED = 4; + public final static int DYNAMIC_MODEL_ADDED = 5; + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + private String key_; + private int changeType_; + private boolean isProxy_; + private String oldKey_; + private boolean oldKeyIsProxy_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Build the event + */ + + public ModelChangeEvent(String genomeKey, int changeType) { + key_ = genomeKey; + changeType_ = changeType; + isProxy_ = false; + } + + /*************************************************************************** + ** + ** Build the event + */ + + public ModelChangeEvent(String key, int changeType, boolean isProxy) { + key_ = key; + changeType_ = changeType; + isProxy_ = isProxy; + } + + /*************************************************************************** + ** + ** Build the event + */ + + public ModelChangeEvent(String key, int changeType, boolean isProxy, + String oldKey, boolean oldKeyIsProxy) { + key_ = key; + changeType_ = changeType; + isProxy_ = isProxy; + oldKey_ = oldKey; + oldKeyIsProxy_ = oldKeyIsProxy; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Get the genome key + */ + + public String getGenomeKey() { + if (isProxy_) { + throw new IllegalStateException(); + } + return (key_); + } + + /*************************************************************************** + ** + ** Answer if we have a proxy key + */ + + public boolean isProxyKey() { + return (isProxy_); + } + + /*************************************************************************** + ** + ** Get the proxy key + */ + + public String getProxyKey() { + if (!isProxy_) { + throw new IllegalStateException(); + } + return (key_); + } + + /*************************************************************************** + ** + ** Get the change type + */ + + public int getChangeType() { + return (changeType_); + } + + /*************************************************************************** + ** + ** Get the old key (may be null) + */ + + public String getOldKey() { + return (oldKey_); + } + + /*************************************************************************** + ** + ** Answer if the old key is a proxy key (only valid if old key != null) + */ + + public boolean oldKeyIsProxy() { + return (oldKeyIsProxy_); + } + + /*************************************************************************** + ** + ** Standard equals + */ + + public boolean equals(Object other) { + if (this == other) { + return (true); + } + if (other == null) { + return (false); + } + if (!(other instanceof ModelChangeEvent)) { + return (false); + } + ModelChangeEvent otherMCE = (ModelChangeEvent)other; + + if (this.changeType_ != otherMCE.changeType_) { + return (false); + } + + if (this.isProxy_ != otherMCE.isProxy_) { + return (false); + } + + if (!this.key_.equals(otherMCE.key_)) { + return (false); + } + + if (this.oldKey_ == null) { + return (otherMCE.oldKey_ == null); + } else if (otherMCE.oldKey_ == null) { + return (this.oldKey_ == null); + } + + if (!this.oldKey_.equals(otherMCE.oldKey_)) { + return (false); + } + + return (this.oldKeyIsProxy_ == otherMCE.oldKeyIsProxy_); + } +} diff --git a/src/org/systemsbiology/biotapestry/event/ModelChangeListener.java b/src/org/systemsbiology/biotapestry/event/ModelChangeListener.java new file mode 100644 index 0000000..73695b5 --- /dev/null +++ b/src/org/systemsbiology/biotapestry/event/ModelChangeListener.java @@ -0,0 +1,50 @@ +/* +** Copyright (C) 2003-2004 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +package org.systemsbiology.biotapestry.event; + +/**************************************************************************** +** +** Used to listen to changes +*/ + +public interface ModelChangeListener { + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Notify listener of model change + */ + + public void modelHasChanged(ModelChangeEvent mcev); + + /*************************************************************************** + ** + ** Notify listener of model change + */ + + public void modelHasChanged(ModelChangeEvent mcev, int remaining); + +} diff --git a/src/org/systemsbiology/biotapestry/event/OverlayDisplayChangeEvent.java b/src/org/systemsbiology/biotapestry/event/OverlayDisplayChangeEvent.java new file mode 100644 index 0000000..06d03dc --- /dev/null +++ b/src/org/systemsbiology/biotapestry/event/OverlayDisplayChangeEvent.java @@ -0,0 +1,96 @@ +/* +** Copyright (C) 2003-2009 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +package org.systemsbiology.biotapestry.event; + +/**************************************************************************** +** +** Used to signal changes in overlay display +*/ + +public class OverlayDisplayChangeEvent implements ChangeEvent { + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTANTS + // + //////////////////////////////////////////////////////////////////////////// + + public final static int NO_CHANGE = 0; + public final static int MODULE_SELECTION_CHANGE = 1; + public final static int OVERLAY_TYPE_CHANGE = 2; + + //////////////////////////////////////////////////////////////////////////// + // + // PRIVATE VARIABLES + // + //////////////////////////////////////////////////////////////////////////// + + private int changeType_; + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC CONSTRUCTORS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Build the event + */ + + public OverlayDisplayChangeEvent(int changeType) { + changeType_ = changeType; + } + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Get the change type + */ + + public int getChangeType() { + return (changeType_); + } + + /*************************************************************************** + ** + ** Standard equals + */ + + public boolean equals(Object other) { + if (this == other) { + return (true); + } + if (other == null) { + return (false); + } + if (!(other instanceof OverlayDisplayChangeEvent)) { + return (false); + } + OverlayDisplayChangeEvent otherODCE = (OverlayDisplayChangeEvent)other; + return (this.changeType_ == otherODCE.changeType_); + } +} diff --git a/src/org/systemsbiology/biotapestry/event/OverlayDisplayChangeListener.java b/src/org/systemsbiology/biotapestry/event/OverlayDisplayChangeListener.java new file mode 100644 index 0000000..8c2260a --- /dev/null +++ b/src/org/systemsbiology/biotapestry/event/OverlayDisplayChangeListener.java @@ -0,0 +1,43 @@ +/* +** Copyright (C) 2003-2009 Institute for Systems Biology +** Seattle, Washington, USA. +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Lesser General Public +** License as published by the Free Software Foundation; either +** version 2.1 of the License, or (at your option) any later version. +** +** This library is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +** Lesser General Public License for more details. +** +** You should have received a copy of the GNU Lesser General Public +** License along with this library; if not, write to the Free Software +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + + +package org.systemsbiology.biotapestry.event; + +/**************************************************************************** +** +** Used to listen to changes +*/ + +public interface OverlayDisplayChangeListener { + + //////////////////////////////////////////////////////////////////////////// + // + // PUBLIC INSTANCE METHODS + // + //////////////////////////////////////////////////////////////////////////// + + /*************************************************************************** + ** + ** Notify listener of overlay display change + */ + + public void overlayDisplayChangeOccurred(OverlayDisplayChangeEvent odcev); + +} diff --git a/src/org/systemsbiology/biofabric/event/SelectionChangeEvent.java b/src/org/systemsbiology/biotapestry/event/SelectionChangeEvent.java similarity index 95% rename from src/org/systemsbiology/biofabric/event/SelectionChangeEvent.java rename to src/org/systemsbiology/biotapestry/event/SelectionChangeEvent.java index 3128755..01610c5 100644 --- a/src/org/systemsbiology/biofabric/event/SelectionChangeEvent.java +++ b/src/org/systemsbiology/biotapestry/event/SelectionChangeEvent.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.event; +package org.systemsbiology.biotapestry.event; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/event/SelectionChangeListener.java b/src/org/systemsbiology/biotapestry/event/SelectionChangeListener.java similarity index 95% rename from src/org/systemsbiology/biofabric/event/SelectionChangeListener.java rename to src/org/systemsbiology/biotapestry/event/SelectionChangeListener.java index ab17c36..fc32f59 100644 --- a/src/org/systemsbiology/biofabric/event/SelectionChangeListener.java +++ b/src/org/systemsbiology/biotapestry/event/SelectionChangeListener.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.event; +package org.systemsbiology.biotapestry.event; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/images/CrossCursor32.gif b/src/org/systemsbiology/biotapestry/images/CrossCursor32.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/CrossCursor32.gif rename to src/org/systemsbiology/biotapestry/images/CrossCursor32.gif diff --git a/src/org/systemsbiology/biofabric/images/ErrorCursor32.gif b/src/org/systemsbiology/biotapestry/images/ErrorCursor32.gif similarity index 100% rename from src/org/systemsbiology/biofabric/images/ErrorCursor32.gif rename to src/org/systemsbiology/biotapestry/images/ErrorCursor32.gif diff --git a/src/org/systemsbiology/biofabric/parser/AbstractFactoryClient.java b/src/org/systemsbiology/biotapestry/parser/AbstractFactoryClient.java similarity index 89% rename from src/org/systemsbiology/biofabric/parser/AbstractFactoryClient.java rename to src/org/systemsbiology/biotapestry/parser/AbstractFactoryClient.java index efbfac8..def7365 100644 --- a/src/org/systemsbiology/biofabric/parser/AbstractFactoryClient.java +++ b/src/org/systemsbiology/biotapestry/parser/AbstractFactoryClient.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2008 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.parser; +package org.systemsbiology.biotapestry.parser; import java.util.Set; import java.util.HashSet; @@ -48,13 +48,13 @@ public abstract class AbstractFactoryClient implements ParserClient { protected Object container_; - protected HashMap workerMap_; - protected HashMap glueStickMap_; + protected HashMap workerMap_; + protected HashMap glueStickMap_; protected AbstractFactoryClient currWorker_; protected String currElem_; protected Object sharedWhiteboard_; - protected HashSet myKeys_; + protected HashSet myKeys_; //////////////////////////////////////////////////////////////////////////// // @@ -68,9 +68,9 @@ public abstract class AbstractFactoryClient implements ParserClient { */ public AbstractFactoryClient(Object sharedWhiteboard) { - myKeys_ = new HashSet(); - workerMap_ = new HashMap(); - glueStickMap_ = new HashMap(); + myKeys_ = new HashSet(); + workerMap_ = new HashMap(); + glueStickMap_ = new HashMap(); sharedWhiteboard_ = sharedWhiteboard; } @@ -148,7 +148,7 @@ public void processCharacters(char[] chars, int start, int length) { ** route then when we get callled. */ - public Set keywordsOfInterest() { + public Set keywordsOfInterest() { return (myKeys_); } @@ -169,13 +169,13 @@ public Object processElement(String elemName, Attributes attrs) throws IOExcepti return (currWorker_.processElement(elemName, attrs)); } - AbstractFactoryClient assignedWorker = workerMap_.get(elemName); + AbstractFactoryClient assignedWorker = (AbstractFactoryClient)workerMap_.get(elemName); if (assignedWorker != null) { currElem_ = elemName; currWorker_ = assignedWorker; Object createdElement = currWorker_.processElement(elemName, attrs); if (createdElement != null) { - GlueStick glue = glueStickMap_.get(elemName); + GlueStick glue = (GlueStick)glueStickMap_.get(elemName); if (glue != null) { glue.glueKidToParent(createdElement, this, sharedWhiteboard_); } @@ -192,11 +192,11 @@ public Object processElement(String elemName, Attributes attrs) throws IOExcepti */ protected void installWorker(AbstractFactoryClient worker, GlueStick glue) { - Set uniqueKeys = worker.keywordsOfInterest(); + Set uniqueKeys = worker.keywordsOfInterest(); - Iterator ukit = uniqueKeys.iterator(); + Iterator ukit = uniqueKeys.iterator(); while (ukit.hasNext()) { - String key = ukit.next(); + String key = (String)ukit.next(); workerMap_.put(key, worker); if (glue != null) { glueStickMap_.put(key, glue); diff --git a/src/org/systemsbiology/biofabric/parser/GlueStick.java b/src/org/systemsbiology/biotapestry/parser/GlueStick.java similarity index 96% rename from src/org/systemsbiology/biofabric/parser/GlueStick.java rename to src/org/systemsbiology/biotapestry/parser/GlueStick.java index e062b63..cec83ab 100644 --- a/src/org/systemsbiology/biofabric/parser/GlueStick.java +++ b/src/org/systemsbiology/biotapestry/parser/GlueStick.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.parser; +package org.systemsbiology.biotapestry.parser; import java.io.IOException; diff --git a/src/org/systemsbiology/biofabric/parser/ParserClient.java b/src/org/systemsbiology/biotapestry/parser/ParserClient.java similarity index 96% rename from src/org/systemsbiology/biofabric/parser/ParserClient.java rename to src/org/systemsbiology/biotapestry/parser/ParserClient.java index d7422cf..96995ba 100644 --- a/src/org/systemsbiology/biofabric/parser/ParserClient.java +++ b/src/org/systemsbiology/biotapestry/parser/ParserClient.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.parser; +package org.systemsbiology.biotapestry.parser; import java.util.Set; import java.io.IOException; @@ -43,7 +43,7 @@ public interface ParserClient { ** Return the element keywords (Strings) that we are interested in */ - public Set keywordsOfInterest(); + public Set keywordsOfInterest(); /*************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/parser/SUParser.java b/src/org/systemsbiology/biotapestry/parser/SUParser.java similarity index 95% rename from src/org/systemsbiology/biofabric/parser/SUParser.java rename to src/org/systemsbiology/biotapestry/parser/SUParser.java index 5c7a676..f7319d7 100644 --- a/src/org/systemsbiology/biofabric/parser/SUParser.java +++ b/src/org/systemsbiology/biotapestry/parser/SUParser.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2009 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.parser; +package org.systemsbiology.biotapestry.parser; import java.io.IOException; import java.io.InputStream; @@ -25,9 +25,11 @@ import java.util.HashMap; import java.util.Set; import java.util.List; +import java.util.Stack; import java.io.File; import java.net.URL; import java.text.MessageFormat; +import java.util.HashSet; import org.xml.sax.EntityResolver; import org.xml.sax.Attributes; @@ -38,7 +40,7 @@ import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.helpers.DefaultHandler; -import org.systemsbiology.biofabric.util.ResourceManager; +import org.systemsbiology.biotapestry.util.ResourceManager; /**************************************************************************** ** @@ -56,7 +58,7 @@ public class SUParser extends DefaultHandler { //////////////////////////////////////////////////////////////////////////// private XMLReader parser_; - private HashMap clients_; + private HashMap clients_; private ParserClient currClient_; private String lastElement_; @@ -71,20 +73,20 @@ public class SUParser extends DefaultHandler { ** Parse the given file using the given factories: */ - public SUParser(List citList) { + public SUParser(List citList) { this(); // // Crank thru the clients and stash them in a HashMap // - Iterator cit = citList.iterator(); - clients_ = new HashMap(); + Iterator cit = citList.iterator(); + clients_ = new HashMap(); while (cit.hasNext()) { - ParserClient pc = cit.next(); - Set keys = pc.keywordsOfInterest(); - Iterator ki = keys.iterator(); + ParserClient pc = (ParserClient)cit.next(); + Set keys = pc.keywordsOfInterest(); + Iterator ki = keys.iterator(); while (ki.hasNext()) { - String key = ki.next(); + String key = (String)ki.next(); Object prev = clients_.put(key, pc); if (prev != null) { throw new IllegalArgumentException(); @@ -208,7 +210,7 @@ public void startElement(String uri, String local, String raw, // Find the client that wants it: // - ParserClient pc = clients_.get(local); + ParserClient pc = (ParserClient)clients_.get(local); if (pc != null) { currClient_ = pc; try { @@ -390,9 +392,9 @@ private void printError(String type, SAXParseException ex) { */ private void setTargets(Object target) { - Iterator ci = clients_.values().iterator(); + Iterator ci = clients_.values().iterator(); while (ci.hasNext()) { - ParserClient cli = ci.next(); + ParserClient cli = (ParserClient)ci.next(); cli.setContainer(target); } return; diff --git a/src/org/systemsbiology/biofabric/ui/BasicZoomTargetSupport.java b/src/org/systemsbiology/biotapestry/ui/BasicZoomTargetSupport.java similarity index 91% rename from src/org/systemsbiology/biofabric/ui/BasicZoomTargetSupport.java rename to src/org/systemsbiology/biotapestry/ui/BasicZoomTargetSupport.java index c0fa7c7..c95d68c 100644 --- a/src/org/systemsbiology/biofabric/ui/BasicZoomTargetSupport.java +++ b/src/org/systemsbiology/biotapestry/ui/BasicZoomTargetSupport.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.ui; import java.awt.Point; import java.awt.Dimension; @@ -29,10 +29,10 @@ import java.awt.geom.Rectangle2D; import javax.swing.JPanel; -import org.systemsbiology.biofabric.cmd.ZoomTarget; -import org.systemsbiology.biofabric.db.SimpleWorkspaceSource; -import org.systemsbiology.biofabric.db.Workspace; -import org.systemsbiology.biofabric.util.UndoSupport; +import org.systemsbiology.biotapestry.db.Workspace; +import org.systemsbiology.biotapestry.cmd.ZoomTarget; +import org.systemsbiology.biotapestry.db.SimpleWorkspaceSource; +import org.systemsbiology.biotapestry.util.UndoSupport; /*************************************************************************** ** @@ -162,8 +162,8 @@ public Dimension getPreferredSize() { // at the given zoom level. // Rectangle rect = workspaceSource_.getWorkspace().getWorkspace(); - int width = (int)(rect.width * zoom_); - int height = (int)(rect.height * zoom_); + int width = (int)((double)rect.width * zoom_); + int height = (int)((double)rect.height * zoom_); return (new Dimension(width, height)); } @@ -186,8 +186,8 @@ public Point getCenterPoint() { Point2D center = ws.getCenter(); Point2D centerPoint = (Point2D)center.clone(); transform_.transform(centerPoint, centerPoint); - int x = (int)Math.round(centerPoint.getX()); - int y = (int)Math.round(centerPoint.getY()); + int x = (int)((double)Math.round(centerPoint.getX())); + int y = (int)((double)Math.round(centerPoint.getY())); Point pt = new Point(x, y); return (pt); } @@ -217,8 +217,10 @@ public void fixCenterPoint(boolean doComplete, UndoSupport support, boolean clos ** Get the basic (unzoomed) image size: X Override for complex behavior */ - public Dimension getBasicSize() { - Rectangle origRect = myGenomePre_.getRequiredSize(genomeKey_, layout_); + public Dimension getBasicSize(boolean doComplete, boolean doBuffer, int moduleHandling) { + Rectangle origRect = myGenomePre_.getRequiredSize(genomeKey_, layout_, doComplete, + doBuffer, false, false, + null, null, null); return (new Dimension(origRect.width, origRect.height)); } @@ -227,8 +229,9 @@ public Dimension getBasicSize() { ** Get the basic model bounds X. Override for complex behavior */ - public Rectangle getCurrentBasicBounds() { - return (myGenomePre_.getRequiredSize(genomeKey_, layout_)); + public Rectangle getCurrentBasicBounds(boolean doComplete, boolean doBuffer, int moduleHandling) { + return (myGenomePre_.getRequiredSize(genomeKey_, layout_, doComplete, doBuffer, false, false, + null, null, null)); } /*************************************************************************** @@ -296,8 +299,8 @@ public Rectangle getAllModelBounds() { public Point pointToViewport(Point worldPoint) { Point2D newPoint = new Point2D.Double(worldPoint.getX(), worldPoint.getY()); transform_.transform(newPoint, newPoint); - int x = (int)Math.round(newPoint.getX()); - int y = (int)Math.round(newPoint.getY()); + int x = (int)((double)Math.round(newPoint.getX())); + int y = (int)((double)Math.round(newPoint.getY())); Point pt = new Point(x, y); return (pt); } @@ -451,14 +454,14 @@ public void transformPoint(Point pt) { */ public void transformClick(int x, int y, Point pt) { - Point2D clickPoint = new Point2D.Double(x, y); + Point2D clickPoint = new Point2D.Double((double)x, (double)y); try { transform_.inverseTransform(clickPoint, clickPoint); } catch (NoninvertibleTransformException nitex) { throw new IllegalStateException(); } - pt.x = (int)Math.round(clickPoint.getX()); - pt.y = (int)Math.round(clickPoint.getY()); + pt.x = (int)((double)Math.round(clickPoint.getX())); + pt.y = (int)((double)Math.round(clickPoint.getY())); } /*************************************************************************** @@ -507,7 +510,7 @@ public void transformClick(double x, double y, Point pt) { } catch (NoninvertibleTransformException nitex) { throw new IllegalStateException(); } - pt.x = (int)Math.round(clickPoint.getX()); - pt.y = (int)Math.round(clickPoint.getY()); + pt.x = (int)((double)Math.round(clickPoint.getX())); + pt.y = (int)((double)Math.round(clickPoint.getY())); } } diff --git a/src/org/systemsbiology/biofabric/ui/CursorManager.java b/src/org/systemsbiology/biotapestry/ui/CursorManager.java similarity index 96% rename from src/org/systemsbiology/biofabric/ui/CursorManager.java rename to src/org/systemsbiology/biotapestry/ui/CursorManager.java index a152398..fc6bcd3 100644 --- a/src/org/systemsbiology/biofabric/ui/CursorManager.java +++ b/src/org/systemsbiology/biotapestry/ui/CursorManager.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.ui; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; @@ -91,14 +91,14 @@ public synchronized void clearError() { private void buildCursors() { if (xCur_ == null) { Toolkit tkit = Toolkit.getDefaultToolkit(); - URL xCurGif = getClass().getResource("/org/systemsbiology/biofabric/images/CrossCursor32.gif"); + URL xCurGif = getClass().getResource("/org/systemsbiology/biotapestry/images/CrossCursor32.gif"); Point hot = new Point(15, 15); Image img = tkit.createImage(xCurGif); xCur_ = tkit.createCustomCursor(img, hot, "btCustomCross"); } if (errCur_ == null) { Toolkit tkit = Toolkit.getDefaultToolkit(); - URL errCurGif = getClass().getResource("/org/systemsbiology/biofabric/images/ErrorCursor32.gif"); + URL errCurGif = getClass().getResource("/org/systemsbiology/biotapestry/images/ErrorCursor32.gif"); Point hot = new Point(15, 15); Image img = tkit.createImage(errCurGif); errCur_ = tkit.createCustomCursor(img, hot, "btCustomError"); diff --git a/src/org/systemsbiology/biofabric/ui/ImageExporter.java b/src/org/systemsbiology/biotapestry/ui/ImageExporter.java similarity index 97% rename from src/org/systemsbiology/biofabric/ui/ImageExporter.java rename to src/org/systemsbiology/biotapestry/ui/ImageExporter.java index 3f564c8..d7ae67c 100644 --- a/src/org/systemsbiology/biofabric/ui/ImageExporter.java +++ b/src/org/systemsbiology/biotapestry/ui/ImageExporter.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.ui; import java.util.Iterator; import java.util.List; @@ -360,11 +360,11 @@ private void writeJPGImage(BufferedImage bi, Object outObj, ResolutionSettings r ** Get supported export formats */ - public static List getSupportedExports() { + public static List getSupportedExports() { String[] names = ImageIO.getWriterFormatNames(); // This is a little contorted, to insure presentation order: - HashSet present = new HashSet(); + HashSet present = new HashSet(); for (int i = 0; i < names.length; i++) { if (names[i].equalsIgnoreCase("TIF")) { present.add("TIFF"); @@ -374,7 +374,7 @@ public static List getSupportedExports() { present.add("JPEG"); } } - ArrayList retval = new ArrayList(); + ArrayList retval = new ArrayList(); if (present.contains("TIFF")) { retval.add("TIFF"); } @@ -392,9 +392,9 @@ public static List getSupportedExports() { ** Get supported export file suffixes */ - public static List getSupportedFileSuffixes() { - List exps = getSupportedExports(); - ArrayList retval = new ArrayList(); + public static List getSupportedFileSuffixes() { + List exps = getSupportedExports(); + ArrayList retval = new ArrayList(); if (exps.contains("TIFF")) { retval.add("tif"); retval.add("tiff"); @@ -414,8 +414,8 @@ public static List getSupportedFileSuffixes() { ** Map type to suffixes */ - public static List getFileSuffixesForType(String type) { - ArrayList retval = new ArrayList(); + public static List getFileSuffixesForType(String type) { + ArrayList retval = new ArrayList(); if (type.equals("TIFF")) { retval.add("tif"); retval.add("tiff"); diff --git a/src/org/systemsbiology/biofabric/ui/NamedColor.java b/src/org/systemsbiology/biotapestry/ui/NamedColor.java similarity index 97% rename from src/org/systemsbiology/biofabric/ui/NamedColor.java rename to src/org/systemsbiology/biotapestry/ui/NamedColor.java index aef3bb7..71e7f17 100644 --- a/src/org/systemsbiology/biofabric/ui/NamedColor.java +++ b/src/org/systemsbiology/biotapestry/ui/NamedColor.java @@ -17,11 +17,11 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.ui; import java.awt.Color; -import org.systemsbiology.biofabric.util.ColorListRenderer; +import org.systemsbiology.biotapestry.util.ColorListRenderer; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/ui/ZoomPresentation.java b/src/org/systemsbiology/biotapestry/ui/ZoomPresentation.java similarity index 90% rename from src/org/systemsbiology/biofabric/ui/ZoomPresentation.java rename to src/org/systemsbiology/biotapestry/ui/ZoomPresentation.java index cf6ca8a..51dfb32 100644 --- a/src/org/systemsbiology/biofabric/ui/ZoomPresentation.java +++ b/src/org/systemsbiology/biotapestry/ui/ZoomPresentation.java @@ -17,12 +17,12 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui; +package org.systemsbiology.biotapestry.ui; import java.awt.Rectangle; import java.util.Map; -import org.systemsbiology.biofabric.util.TaggedSet; +import org.systemsbiology.biotapestry.util.TaggedSet; /**************************************************************************** ** @@ -47,7 +47,10 @@ public interface ZoomPresentation { ** Return the required size of the layout */ - public Rectangle getRequiredSize(String genomeKey, String layoutKey); + public Rectangle getRequiredSize(String genomeKey, String layoutKey, + boolean doComplete, boolean useBuffer, + boolean doModules, boolean doModuleLinks, + String ovrKey, TaggedSet modSet, Map allKeys); /*************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/ExceptionDialog.java b/src/org/systemsbiology/biotapestry/ui/dialogs/ExceptionDialog.java similarity index 89% rename from src/org/systemsbiology/biofabric/ui/dialogs/ExceptionDialog.java rename to src/org/systemsbiology/biotapestry/ui/dialogs/ExceptionDialog.java index 5e874d3..5716518 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/ExceptionDialog.java +++ b/src/org/systemsbiology/biotapestry/ui/dialogs/ExceptionDialog.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2004 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,8 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.dialogs; + +package org.systemsbiology.biotapestry.ui.dialogs; import java.awt.GridBagLayout; @@ -36,10 +37,10 @@ import java.io.StringWriter; import java.io.PrintWriter; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.UiUtil; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ExceptionHandler; /**************************************************************************** ** @@ -52,16 +53,14 @@ public class ExceptionDialog extends JDialog { // // PRIVATE CONSTANTS // - //////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // // PRIVATE INSTANCE MEMBERS // - //////////////////////////////////////////////////////////////////////////// - - private static final long serialVersionUID = 1L; - + //////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////// // // PUBLIC CONSTRUCTORS diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/ExportSettingsDialog.java b/src/org/systemsbiology/biotapestry/ui/dialogs/ExportSettingsDialog.java similarity index 90% rename from src/org/systemsbiology/biofabric/ui/dialogs/ExportSettingsDialog.java rename to src/org/systemsbiology/biotapestry/ui/dialogs/ExportSettingsDialog.java index 10c2a44..a23b9bd 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/ExportSettingsDialog.java +++ b/src/org/systemsbiology/biotapestry/ui/dialogs/ExportSettingsDialog.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2005 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,8 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.dialogs; + +package org.systemsbiology.biotapestry.ui.dialogs; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; @@ -34,19 +35,23 @@ import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JPanel; +import javax.swing.JTabbedPane; import javax.swing.JComboBox; +import javax.swing.JCheckBox; import javax.swing.JOptionPane; import javax.swing.Box; import javax.swing.border.EmptyBorder; +import javax.swing.JRadioButton; +import javax.swing.ButtonGroup; import java.util.prefs.Preferences; import java.util.List; import java.text.MessageFormat; -import org.systemsbiology.biofabric.ui.ImageExporter; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.UiUtil; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.ui.ImageExporter; /**************************************************************************** ** @@ -93,8 +98,7 @@ public class ExportSettingsDialog extends JDialog { private int baseWidth_; private int baseHeight_; private ExportSettings finishedSettings_; - private Preferences prefs_; - private static final long serialVersionUID = 1L; + private Preferences prefs_; //////////////////////////////////////////////////////////////////////////// // @@ -120,12 +124,12 @@ public ExportSettingsDialog(JFrame parent, int baseWidth, int baseHeight) { finishedSettings_ = null; prefs_ = Preferences.userNodeForPackage(this.getClass()); currentZoomVal_ = prefs_.getDouble("ExportZoom", 1.0); - List types = ImageExporter.getSupportedExports(); + List types = ImageExporter.getSupportedExports(); String maybeFormat = prefs_.get("ExportFormat", "PNG"); if (types.contains(maybeFormat)) { currentFormat_ = maybeFormat; } else { - currentFormat_ = types.get(0); + currentFormat_ = (String)types.get(0); } JPanel zoomPanel = buildZoomPanel(baseWidth, baseHeight, types); @@ -329,8 +333,8 @@ private void processZoomVal(boolean force, int whichVal) { case ZOOM_: if (currentZoomVal_ != newZoom) { currentZoomVal_ = newZoom; - currentZoomHeight_ = Math.round(baseHeight_ * currentZoomVal_); - currentZoomWidth_ = Math.round(baseWidth_ * currentZoomVal_); + currentZoomHeight_ = Math.round((double)baseHeight_ * currentZoomVal_); + currentZoomWidth_ = Math.round((double)baseWidth_ * currentZoomVal_); widthField_.setText(Long.toString(currentZoomWidth_)); heightField_.setText(Long.toString(currentZoomHeight_)); } @@ -342,7 +346,7 @@ private void processZoomVal(boolean force, int whichVal) { if (currentZoomHeight_ != newHeight) { currentZoomHeight_ = newHeight; currentZoomVal_ = currentZoomHeight_ /(double)baseHeight_; - currentZoomWidth_ = Math.round(baseWidth_ * currentZoomVal_); + currentZoomWidth_ = Math.round((double)baseWidth_ * currentZoomVal_); zoomField_.setText(Double.toString(currentZoomVal_)); widthField_.setText(Long.toString(currentZoomWidth_)); } @@ -354,7 +358,7 @@ private void processZoomVal(boolean force, int whichVal) { if (currentZoomWidth_ != newWidth) { currentZoomWidth_ = newWidth; currentZoomVal_ = currentZoomWidth_ /(double)baseWidth_; - currentZoomHeight_ = Math.round(baseHeight_ * currentZoomVal_); + currentZoomHeight_ = Math.round((double)baseHeight_ * currentZoomVal_); zoomField_.setText(Double.toString(currentZoomVal_)); heightField_.setText(Long.toString(currentZoomHeight_)); } @@ -395,22 +399,22 @@ private void fixZoomVals() { private boolean tooSmall(double newZoom, long newDim, int whichVal) { switch (whichVal) { case ZOOM_: - long newZoomHeight = Math.round(baseHeight_ * newZoom); - long newZoomWidth = Math.round(baseWidth_ * newZoom); + long newZoomHeight = Math.round((double)baseHeight_ * newZoom); + long newZoomWidth = Math.round((double)baseWidth_ * newZoom); if ((newZoomHeight == 0) || (newZoomWidth == 0)) { return (true); } break; case HEIGHT_: double newZoomVal = newDim /(double)baseHeight_; - newZoomWidth = Math.round(baseWidth_ * newZoomVal); + newZoomWidth = Math.round((double)baseWidth_ * newZoomVal); if ((newZoomVal == 0) || (newZoomWidth == 0)) { return (true); } break; case WIDTH_: newZoomVal = newDim /(double)baseWidth_; - newZoomHeight = Math.round(baseHeight_ * newZoomVal); + newZoomHeight = Math.round((double)baseHeight_ * newZoomVal); if ((newZoomVal == 0) || (newZoomHeight == 0)) { return (true); } @@ -508,8 +512,8 @@ private JPanel buildZoomPanel(int baseWidth, int baseHeight, List types) { */ private void initZoomDims() { - currentZoomHeight_ = Math.round(baseHeight_ * currentZoomVal_); - currentZoomWidth_ = Math.round(baseWidth_ * currentZoomVal_); + currentZoomHeight_ = Math.round((double)baseHeight_ * currentZoomVal_); + currentZoomWidth_ = Math.round((double)baseWidth_ * currentZoomVal_); widthField_.setText(Long.toString(currentZoomWidth_)); heightField_.setText(Long.toString(currentZoomHeight_)); return; diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/ExportSettingsPublishDialog.java b/src/org/systemsbiology/biotapestry/ui/dialogs/ExportSettingsPublishDialog.java similarity index 96% rename from src/org/systemsbiology/biofabric/ui/dialogs/ExportSettingsPublishDialog.java rename to src/org/systemsbiology/biotapestry/ui/dialogs/ExportSettingsPublishDialog.java index b619a87..6906115 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/ExportSettingsPublishDialog.java +++ b/src/org/systemsbiology/biotapestry/ui/dialogs/ExportSettingsPublishDialog.java @@ -18,7 +18,7 @@ */ -package org.systemsbiology.biofabric.ui.dialogs; +package org.systemsbiology.biotapestry.ui.dialogs; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; @@ -47,11 +47,11 @@ import java.text.MessageFormat; -import org.systemsbiology.biofabric.ui.ImageExporter; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.UiUtil; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.ui.ImageExporter; /**************************************************************************** ** diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/utils/BTStashResultsDialog.java b/src/org/systemsbiology/biotapestry/ui/dialogs/utils/BTStashResultsDialog.java similarity index 96% rename from src/org/systemsbiology/biofabric/ui/dialogs/utils/BTStashResultsDialog.java rename to src/org/systemsbiology/biotapestry/ui/dialogs/utils/BTStashResultsDialog.java index 6698b69..797ca11 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/utils/BTStashResultsDialog.java +++ b/src/org/systemsbiology/biotapestry/ui/dialogs/utils/BTStashResultsDialog.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2012 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,8 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.dialogs.utils; + +package org.systemsbiology.biotapestry.ui.dialogs.utils; import java.awt.Dimension; import java.awt.GridBagLayout; @@ -31,7 +32,7 @@ import javax.swing.JPanel; import javax.swing.border.EmptyBorder; -import org.systemsbiology.biofabric.util.ResourceManager; +import org.systemsbiology.biotapestry.util.ResourceManager; /**************************************************************************** ** @@ -46,6 +47,7 @@ public abstract class BTStashResultsDialog extends JDialog implements DialogSupp // //////////////////////////////////////////////////////////////////////////// + private boolean haveResult_; protected JPanel cp_; protected ResourceManager rMan_; @@ -54,7 +56,6 @@ public abstract class BTStashResultsDialog extends JDialog implements DialogSupp protected GridBagConstraints gbc_; protected int rowNum_; protected int columns_; - private static final long serialVersionUID = 1L; //////////////////////////////////////////////////////////////////////////// // @@ -239,12 +240,15 @@ protected void finishConstructionWithExtraLeftButton(JButton xtraButton) { ** Finish building */ - protected void finishConstructionWithMultiExtraLeftButtons(List xtraButtonList) { + protected void finishConstructionWithMultiExtraLeftButtons(List xtraButtonList) { ds_.buildAndInstallButtonBoxWithMultiExtra(cp_, rowNum_, columns_, false, xtraButtonList, true); setLocationRelativeTo(parent_); return; } - + + + + /*************************************************************************** ** ** Stash our results for later interrogation. diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/utils/DialogSupport.java b/src/org/systemsbiology/biotapestry/ui/dialogs/utils/DialogSupport.java similarity index 96% rename from src/org/systemsbiology/biofabric/ui/dialogs/utils/DialogSupport.java rename to src/org/systemsbiology/biotapestry/ui/dialogs/utils/DialogSupport.java index 0160401..48ffad1 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/utils/DialogSupport.java +++ b/src/org/systemsbiology/biotapestry/ui/dialogs/utils/DialogSupport.java @@ -17,7 +17,7 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.dialogs.utils; +package org.systemsbiology.biotapestry.ui.dialogs.utils; import java.awt.GridBagConstraints; import java.awt.event.ActionListener; @@ -32,10 +32,10 @@ import javax.swing.JLabel; import javax.swing.border.Border; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.UiUtil; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.ExceptionHandler; /**************************************************************************** ** @@ -234,7 +234,7 @@ public void buildAndInstallButtonBox(JPanel cp, int rowNum, int colWidth, boolea */ public Box buildButtonBoxWithExtra(boolean doApply, JButton xtraButton, boolean showAsCancel) { - ArrayList xtraButtonList = new ArrayList(); + ArrayList xtraButtonList = new ArrayList(); xtraButtonList.add(xtraButton); return (buildButtonBoxWithMultiExtra(doApply, xtraButtonList, showAsCancel)); } @@ -244,7 +244,7 @@ public Box buildButtonBoxWithExtra(boolean doApply, JButton xtraButton, boolean ** Build a button panel with many left extras */ - public Box buildButtonBoxWithMultiExtra(boolean doApply, List xtraButtonList, boolean showAsCancel) { + public Box buildButtonBoxWithMultiExtra(boolean doApply, List xtraButtonList, boolean showAsCancel) { FixedJButton buttonA = null; if (doApply) { @@ -290,7 +290,7 @@ public void actionPerformed(ActionEvent ev) { buttonPanel.add(Box.createHorizontalStrut(10)); int numBut = xtraButtonList.size(); for (int i = 0; i < numBut; i++) { - buttonPanel.add(xtraButtonList.get(i)); + buttonPanel.add((JButton)xtraButtonList.get(i)); if (i != (numBut - 1)) { buttonPanel.add(Box.createHorizontalStrut(10)); } @@ -325,7 +325,7 @@ public void buildAndInstallButtonBoxWithExtra(JPanel cp, int rowNum, int colWidt */ public void buildAndInstallButtonBoxWithMultiExtra(JPanel cp, int rowNum, int colWidth, boolean doApply, - List xtraButtonList, boolean showAsCancel) { + List xtraButtonList, boolean showAsCancel) { Box bBox = buildButtonBoxWithMultiExtra(doApply, xtraButtonList, showAsCancel); UiUtil.gbcSet(gbc_, 0, rowNum, colWidth, 1, UiUtil.HOR, 0, 0, 5, 5, 5, 5, UiUtil.SE, 1.0, 0.0); cp.add(bBox, gbc_); diff --git a/src/org/systemsbiology/biofabric/ui/dialogs/utils/EditableTable.java b/src/org/systemsbiology/biotapestry/ui/dialogs/utils/EditableTable.java similarity index 80% rename from src/org/systemsbiology/biofabric/ui/dialogs/utils/EditableTable.java rename to src/org/systemsbiology/biotapestry/ui/dialogs/utils/EditableTable.java index c665218..734be8e 100644 --- a/src/org/systemsbiology/biofabric/ui/dialogs/utils/EditableTable.java +++ b/src/org/systemsbiology/biotapestry/ui/dialogs/utils/EditableTable.java @@ -1,5 +1,5 @@ /* -** Copyright (C) 2003-2014 Institute for Systems Biology +** Copyright (C) 2003-2010 Institute for Systems Biology ** Seattle, Washington, USA. ** ** This library is free software; you can redistribute it and/or @@ -17,7 +17,8 @@ ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -package org.systemsbiology.biofabric.ui.dialogs.utils; + +package org.systemsbiology.biotapestry.ui.dialogs.utils; import java.awt.BorderLayout; import java.awt.GridBagConstraints; @@ -49,51 +50,32 @@ import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; -import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; -import org.systemsbiology.biofabric.util.ComboBoxEditorTracker; -import org.systemsbiology.biofabric.util.ComboFinishedTracker; -import org.systemsbiology.biofabric.util.DoubleEditor; -import org.systemsbiology.biofabric.util.EditableComboBoxEditorTracker; -import org.systemsbiology.biofabric.util.EnumCell; -import org.systemsbiology.biofabric.util.ExceptionHandler; -import org.systemsbiology.biofabric.util.FixedJButton; -import org.systemsbiology.biofabric.util.IntegerEditor; -import org.systemsbiology.biofabric.util.NumberEditorTracker; -import org.systemsbiology.biofabric.util.ProtoDouble; -import org.systemsbiology.biofabric.util.ProtoInteger; -import org.systemsbiology.biofabric.util.ResourceManager; -import org.systemsbiology.biofabric.util.TextEditor; -import org.systemsbiology.biofabric.util.TextEditorTracker; -import org.systemsbiology.biofabric.util.TextFinishedTracker; -import org.systemsbiology.biofabric.util.TrackingUnit; -import org.systemsbiology.biofabric.util.UiUtil; +import org.systemsbiology.biotapestry.util.ComboBoxEditorTracker; +import org.systemsbiology.biotapestry.util.ComboFinishedTracker; +import org.systemsbiology.biotapestry.util.DoubleEditor; +import org.systemsbiology.biotapestry.util.EditableComboBoxEditorTracker; +import org.systemsbiology.biotapestry.util.EnumCell; +import org.systemsbiology.biotapestry.util.ResourceManager; +import org.systemsbiology.biotapestry.util.UiUtil; +import org.systemsbiology.biotapestry.util.FixedJButton; +import org.systemsbiology.biotapestry.util.TextEditor; +import org.systemsbiology.biotapestry.util.TextEditorTracker; +import org.systemsbiology.biotapestry.util.ExceptionHandler; +import org.systemsbiology.biotapestry.util.IntegerEditor; +import org.systemsbiology.biotapestry.util.NumberEditorTracker; +import org.systemsbiology.biotapestry.util.ProtoDouble; +import org.systemsbiology.biotapestry.util.ProtoInteger; +import org.systemsbiology.biotapestry.util.TextFinishedTracker; /**************************************************************************** ** -** This is an editable table. Rows are not sortable. The generic class is -** parameterized on the table row type. +** This is an editable table. Rows are not sortable */ -public class EditableTable { - - //////////////////////////////////////////////////////////////////////////// - // - // PUBLIC INTERFACE - // - //////////////////////////////////////////////////////////////////////////// - - /*************************************************************************** - ** - ** Used for TableRows - */ - - public interface ATableRow { - // Should also implement constructors for () and (int i) - void toCols(); - } +public class EditableTable { //////////////////////////////////////////////////////////////////////////// // @@ -117,7 +99,7 @@ public interface ATableRow { // //////////////////////////////////////////////////////////////////////////// - private TableModel estm_; + private TableModel estm_; private int[] selectedRows_; private boolean trueButtonDEnable_; private boolean trueButtonAEnable_; @@ -133,13 +115,14 @@ public interface ATableRow { private SelectionTracker tracker_; private boolean addAlwaysAtEnd_; private TextEditor textEdit_; - private Set> usedClasses_; - private HashMap editors_; - private HashMap renderers_; - private HashSet editableEnums_; + private Set usedClasses_; + private HashMap editors_; + private HashMap renderers_; + private HashSet editableEnums_; private JFrame parent_; private boolean cancelEditOnDisable_; private EditButtonHandler ebh_; + //////////////////////////////////////////////////////////////////////////// // @@ -148,7 +131,7 @@ public interface ATableRow { //////////////////////////////////////////////////////////////////////////// - public EditableTable(TableModel atm, JFrame parent) { + public EditableTable(TableModel atm, JFrame parent) { estm_ = atm; parent_ = parent; } @@ -164,7 +147,7 @@ public JTable getTable() { return (qt_); } - public TableModel getModel() { + public TableModel getModel() { return (estm_); } @@ -267,7 +250,7 @@ private void syncButtons() { ** Update the table */ - public void updateTable(boolean fireChange, List elements) { + public void updateTable(boolean fireChange, List elements) { estm_.extractValues(elements); // estm_.modifyMap(estm_.buildFullClickList()); if (fireChange) { @@ -292,7 +275,7 @@ public void updateTable(boolean fireChange, List elements) { ** Get stuff out of the table */ - public List getValuesFromTable() { + public List getValuesFromTable() { return (estm_.getValuesFromTable()); } @@ -372,7 +355,7 @@ public JPanel buildEditableTable(TableParams etp) { int numC = etp.colWidths.size(); TableColumnModel tcm = qt_.getColumnModel(); for (int i = 0; i < numC; i++) { - ColumnWidths cw = etp.colWidths.get(i); + ColumnWidths cw = (ColumnWidths)etp.colWidths.get(i); int viewColumn = qt_.convertColumnIndexToView(cw.colNum); TableColumn tfCol = tcm.getColumn(viewColumn); tfCol.setMinWidth(cw.min); @@ -385,9 +368,9 @@ public JPanel buildEditableTable(TableParams etp) { UiUtil.installDefaultCellRendererForPlatform(qt_, ProtoInteger.class, true); UiUtil.installDefaultCellRendererForPlatform(qt_, Integer.class, true); // For non-edit number columns! - editors_ = new HashMap(); - renderers_ = new HashMap(); - editableEnums_ = new HashSet(); + editors_ = new HashMap(); + renderers_ = new HashMap(); + editableEnums_ = new HashSet(); setDefaultEditors(); if (etp.perColumnEnums != null) { setColumnEditorsAndRenderers(etp.perColumnEnums, renderers_, editors_, editableEnums_); @@ -405,7 +388,7 @@ public JPanel buildEditableTable(TableParams etp) { ** Refresh editors and renderers */ - public void refreshEditorsAndRenderers(Map perColumnEnums) { + public void refreshEditorsAndRenderers(Map perColumnEnums) { editors_.clear(); renderers_.clear(); editableEnums_.clear(); @@ -670,9 +653,9 @@ private JPanel addButtonsOnSide(TableParams etp) { */ private void setDefaultEditors() { - Iterator> cit = usedClasses_.iterator(); + Iterator cit = usedClasses_.iterator(); while (cit.hasNext()) { - Class used = cit.next(); + Class used = (Class)cit.next(); if (used.equals(ProtoDouble.class)) { DoubleEditor dEdit = new DoubleEditor(parent_); new NumberEditorTracker(dEdit, estm_); @@ -703,9 +686,9 @@ private void setDefaultEditors() { */ private void enableDefaultEditorsAndRenderers(boolean enable) { - Iterator> cit = usedClasses_.iterator(); + Iterator cit = usedClasses_.iterator(); while (cit.hasNext()) { - Class used = cit.next(); + Class used = (Class)cit.next(); if (used.equals(ProtoDouble.class)) { DoubleEditor dt = (DoubleEditor)qt_.getDefaultEditor(ProtoDouble.class); dt.setEnabled(enable); @@ -743,9 +726,9 @@ private void enableDefaultEditorsAndRenderers(boolean enable) { */ private void enableColumnEditorsAndRenderers(boolean enable) { - Iterator rkit = renderers_.keySet().iterator(); + Iterator rkit = renderers_.keySet().iterator(); while (rkit.hasNext()) { - Integer key = rkit.next(); + Integer key = (Integer)rkit.next(); if (editableEnums_.contains(key)) { EnumCell.EditableComboBoxRenderer ecbr = (EnumCell.EditableComboBoxRenderer)renderers_.get(key); ecbr.setEnabled(enable); @@ -754,9 +737,9 @@ private void enableColumnEditorsAndRenderers(boolean enable) { rocbr.setEnabled(enable); } } - Iterator ekit = editors_.keySet().iterator(); + Iterator ekit = editors_.keySet().iterator(); while (ekit.hasNext()) { - Integer key = ekit.next(); + Integer key = (Integer)ekit.next(); if (editableEnums_.contains(key)) { EnumCell.EditableEnumCellEditor eece = (EnumCell.EditableEnumCellEditor)editors_.get(key); eece.setEnabled(enable); @@ -775,12 +758,11 @@ private void enableColumnEditorsAndRenderers(boolean enable) { ** */ - private void setColumnEditorsAndRenderers(Map contents, Map renderers, - Map editors, Set editableEnums) { - Iterator cit = contents.keySet().iterator(); + private void setColumnEditorsAndRenderers(Map contents, Map renderers, Map editors, Set editableEnums) { + Iterator cit = contents.keySet().iterator(); while (cit.hasNext()) { - Integer intObj = cit.next(); - EnumCellInfo eci = contents.get(intObj); + Integer intObj = (Integer)cit.next(); + EnumCellInfo eci = (EnumCellInfo)contents.get(intObj); TableColumn tc = qt_.getColumnModel().getColumn(intObj.intValue()); if (eci.editable) { EnumCell.EditableComboBoxRenderer ecbr = new EnumCell.EditableComboBoxRenderer(eci.values); @@ -818,13 +800,13 @@ private void setColumnEditorsAndRenderers(Map contents, M */ public void stopTheEditing(boolean doCancel) { - Iterator> cit = usedClasses_.iterator(); + Iterator cit = usedClasses_.iterator(); while (cit.hasNext()) { - Class used = cit.next(); + Class used = (Class)cit.next(); if (!used.equals(EnumCell.class)) { // Ignore default editors: if (!used.equals(Integer.class) && !used.equals(Boolean.class)) { - TableCellEditor tce = qt_.getDefaultEditor(used); + TableCellEditor tce = (TableCellEditor)qt_.getDefaultEditor(used); if (doCancel) { tce.cancelCellEditing(); } else { @@ -833,10 +815,10 @@ public void stopTheEditing(boolean doCancel) { } } } - Iterator ekit = editors_.keySet().iterator(); + Iterator ekit = editors_.keySet().iterator(); while (ekit.hasNext()) { - Integer key = ekit.next(); - TableCellEditor tce = editors_.get(key); + Integer key = (Integer)ekit.next(); + TableCellEditor tce = (TableCellEditor)editors_.get(key); if (doCancel) { tce.cancelCellEditing(); } else { @@ -872,8 +854,8 @@ public static class TableParams { public boolean cancelEditOnDisable; public boolean tableIsUnselectable; public int buttons; - public Map perColumnEnums; - public List colWidths; + public Map perColumnEnums; + public List colWidths; public boolean buttonsOnSide; public boolean noScroll; } @@ -907,14 +889,14 @@ public ColumnWidths(int colNum, int min, int pref, int max) { public static class EnumCellInfo { public boolean editable; - public List values; - public Map trackingUnits; + public List values; + public Map trackingUnits; - public EnumCellInfo(boolean editable, List values) { + public EnumCellInfo(boolean editable, List values) { this(editable, values, null); } - public EnumCellInfo(boolean editable, List values, Map trackingUnits) { + public EnumCellInfo(boolean editable, List values, Map trackingUnits) { this.editable = editable; this.values = values; this.trackingUnits = trackingUnits; @@ -930,37 +912,36 @@ public EnumCellInfo(boolean editable, List values, Map extends AbstractTableModel implements ComboFinishedTracker, TextFinishedTracker { + public static abstract class TableModel extends AbstractTableModel implements ComboFinishedTracker, TextFinishedTracker { protected JTable tmqt_; - protected ArrayList> columns_; - protected ArrayList origIndex_; - protected ArrayList> hiddenColumns_; + protected ArrayList[] columns_; + protected ArrayList origIndex_; + protected ArrayList[] hiddenColumns_; protected int rowCount_; protected String[] colNames_; - protected Class[] colClasses_; + protected Class[] colClasses_; protected boolean[] canEdit_; protected boolean[] colUseDirect_; - protected Set myEditableEnums_; - protected HashMap myRenderers_; - protected HashMap myEditors_; + protected Set myEditableEnums_; + protected HashMap myRenderers_; + protected HashMap myEditors_; protected int collapseCount_; protected boolean isCollapsed_; - private static final long serialVersionUID = 1L; protected TableModel(int colNum) { - columns_ = new ArrayList>(); - for (int i = 0; i < colNum; i++) { - columns_.add(new ArrayList()); + columns_ = new ArrayList[colNum]; + for (int i = 0; i < columns_.length; i++) { + columns_[i] = new ArrayList(); } - origIndex_ = new ArrayList(); - hiddenColumns_ = new ArrayList>(); + origIndex_ = new ArrayList(); + hiddenColumns_ = new ArrayList[0]; canEdit_ = null; colUseDirect_ = null; collapseCount_ = -1; isCollapsed_ = false; - myRenderers_ = new HashMap(); - myEditors_ = new HashMap(); + myRenderers_ = new HashMap(); + myEditors_ = new HashMap(); } @@ -969,22 +950,22 @@ protected TableModel(int colNum) { // protected void resetColumnCount(int colNum) { - columns_ = new ArrayList>(); - for (int i = 0; i < colNum; i++) { - columns_.add(new ArrayList()); + columns_ = new ArrayList[colNum]; + for (int i = 0; i < columns_.length; i++) { + columns_[i] = new ArrayList(); } } protected void addHiddenColumns(int colNum) { - hiddenColumns_ = new ArrayList>(); - for (int i = 0; i < colNum; i++) { - hiddenColumns_.add(new ArrayList()); + hiddenColumns_ = new ArrayList[colNum]; + for (int i = 0; i < hiddenColumns_.length; i++) { + hiddenColumns_[i] = new ArrayList(); } return; } - Set> usedClasses() { - HashSet> retval = new HashSet>(); + Set usedClasses() { + HashSet retval = new HashSet(); for (int i = 0; i < colClasses_.length; i++) { retval.add(colClasses_[i]); } @@ -996,7 +977,7 @@ void setJTable(JTable tab) { tmqt_ = tab; } - void setEnums(Map renderers, Map editors, Set editableEnums) { + void setEnums(Map renderers, Map editors, Set editableEnums) { myRenderers_.clear(); myEditors_.clear(); myRenderers_.putAll(renderers); @@ -1007,13 +988,11 @@ void setEnums(Map renderers, Map getListAt(int c) { + protected List getListAt(int c) { try { - if (c >= columns_.size()) { + if (c >= columns_.length) { throw new IllegalArgumentException(); } - return (columns_.get(c)); + return (columns_[c]); } catch (Exception ex) { ExceptionHandler.getHandler().displayException(ex); } @@ -1121,7 +1094,6 @@ protected int mapSelectionIndex(int r) { return (r); } - @Override public String getColumnName(int c) { try { if (c >= colNames_.length) { @@ -1139,8 +1111,7 @@ public String getColumnName(int c) { return (null); } - @Override - public Class getColumnClass(int c) { + public Class getColumnClass(int c) { try { if (c >= colClasses_.length) { throw new IllegalArgumentException(); @@ -1154,7 +1125,7 @@ public Class getColumnClass(int c) { public Object getValueAt(int r, int c) { try { - List list = getListAt(c); + List list = getListAt(c); if (list.isEmpty()) { return (null); } @@ -1165,15 +1136,14 @@ public Object getValueAt(int r, int c) { return (null); } - @Override public void setValueAt(Object value, int r, int c) { try { - List list = getListAt(c); + List list = getListAt(c); if (list.isEmpty()) { return; } Object currVal = list.get(r); - Class colClass = getColumnClass(c); + Class colClass = getColumnClass(c); if (colClass.equals(ProtoInteger.class)) { ProtoInteger currNum = (ProtoInteger)currVal; if ((currNum != null) && currNum.textValue.equals(((ProtoInteger)value).textValue)) { @@ -1216,7 +1186,6 @@ public void setValueAt(Object value, int r, int c) { return; } - @Override public boolean isCellEditable(int r, int c) { try { if (canEdit_ == null) { @@ -1230,41 +1199,24 @@ public boolean isCellEditable(int r, int c) { return (false); } - public void extractValues(List rowElements) { - origIndex_.clear(); - int clen = columns_.size(); - for (int i = 0; i < clen; i++) { - columns_.get(i).clear(); + public void extractValues(List rowElements) { + origIndex_.clear(); + for (int i = 0; i < columns_.length; i++) { + columns_[i].clear(); } - int hlen = hiddenColumns_.size(); - for (int i = 0; i < hlen; i++) { - hiddenColumns_.get(i).clear(); + for (int i = 0; i < hiddenColumns_.length; i++) { + hiddenColumns_[i].clear(); } rowCount_ = 0; - Iterator iit = rowElements.iterator(); + Iterator iit = rowElements.iterator(); while (iit.hasNext()) { - iit.next(); + Object dc = iit.next(); origIndex_.add(new Integer(rowCount_++)); } - Iterator rit = rowElements.iterator(); - while (rit.hasNext()) { - T ent = rit.next(); - ent.toCols(); - } return; } - - public abstract T constructARow(); - protected abstract T constructARow(int i); - - public List getValuesFromTable() { - ArrayList retval = new ArrayList(); - for (int i = 0; i < rowCount_; i++) { - T ent = constructARow(i); - retval.add(ent); - } - return (retval); - } + + public abstract List getValuesFromTable(); public void collapseView(boolean doCollapse) { if (collapseCount_ == -1) { @@ -1295,9 +1247,9 @@ private void refreshColumnEditorsAndRenderers() { int currColumns = getColumnCount(); TableColumnModel tcm = tmqt_.getColumnModel(); - Iterator rkit = myRenderers_.keySet().iterator(); + Iterator rkit = myRenderers_.keySet().iterator(); while (rkit.hasNext()) { - Integer key = rkit.next(); + Integer key = (Integer)rkit.next(); if (key.intValue() >= currColumns) { continue; } @@ -1311,9 +1263,9 @@ private void refreshColumnEditorsAndRenderers() { } } - Iterator ekit = myEditors_.keySet().iterator(); + Iterator ekit = myEditors_.keySet().iterator(); while (ekit.hasNext()) { - Integer key = ekit.next(); + Integer key = (Integer)ekit.next(); if (key.intValue() >= currColumns) { continue; } @@ -1414,12 +1366,10 @@ public void setIgnore(boolean ignore) { class TrackingJTable extends JTable { - private static final long serialVersionUID = 1L; - private int lastCol_ = -1; private Object lastOrig_; - TrackingJTable(TableModel estm) { + TrackingJTable(TableModel estm) { super(estm); } @@ -1435,8 +1385,7 @@ void clearLastOrig() { int getLastColumn() { return (lastCol_); } - - @Override + public TableCellEditor getCellEditor(int row, int column) { lastOrig_ = null; if ((lastCol_ == column) && editableEnums_.contains(new Integer(column))) { @@ -1455,25 +1404,23 @@ public TableCellEditor getCellEditor(int row, int column) { ** A Concrete instantiation of the TableModel that supports a single value. */ - public static class OneValueModel extends EditableTable.TableModel { + public static class OneValueModel extends TableModel { private final static int VALUE = 0; private final static int NUM_COL_ = 1; - private static final long serialVersionUID = 1L; - - public class TableRow implements ATableRow { + public class TableRow { public String value; - - public TableRow() { - } - TableRow(int i) { - value = (String)columns_.get(VALUE).get(i); + public TableRow() { + } + + private TableRow(int i) { + value = (String)columns_[VALUE].get(i); } - public void toCols() { - columns_.get(VALUE).add(value); + private void toCols() { + columns_[VALUE].add(value); return; } } @@ -1485,14 +1432,24 @@ public OneValueModel(String title, boolean edit) { canEdit_ = new boolean[] {edit}; } - protected TableRow constructARow(int i) { - return (new TableRow(i)); + public List getValuesFromTable() { + ArrayList retval = new ArrayList(); + for (int i = 0; i < rowCount_; i++) { + TableRow ent = new TableRow(i); + retval.add(ent); + } + return (retval); } - - public TableRow constructARow() { - return (new TableRow()); + + public void extractValues(List prsList) { + super.extractValues(prsList); + Iterator rit = prsList.iterator(); + while (rit.hasNext()) { + TableRow ent = (TableRow)rit.next(); + ent.toCols(); + } + return; } - } /*************************************************************************** @@ -1500,7 +1457,7 @@ public TableRow constructARow() { ** Useful for single tagged values */ - public static class TaggedValueModel extends EditableTable.TableModel { + public static class TaggedValueModel extends EditableTable.TableModel { private final static int VALUE = 0; private final static int NUM_COL_ = 1; @@ -1508,23 +1465,22 @@ public static class TaggedValueModel extends EditableTable.TableModel