diff --git a/debug_log4j2.xml b/debug_log4j2.xml
index 4bd5910c55..eb49757805 100644
--- a/debug_log4j2.xml
+++ b/debug_log4j2.xml
@@ -10,13 +10,13 @@
-
+
-
+
-
+
@@ -28,7 +28,7 @@
-
+
diff --git a/vcell-admin/src/test/java/cbit/vcell/client/ClientTaskDispatcherTest.java b/vcell-admin/src/test/java/cbit/vcell/client/ClientTaskDispatcherTest.java
index 2da574253d..75c8e0c72d 100644
--- a/vcell-admin/src/test/java/cbit/vcell/client/ClientTaskDispatcherTest.java
+++ b/vcell-admin/src/test/java/cbit/vcell/client/ClientTaskDispatcherTest.java
@@ -10,6 +10,9 @@
import java.awt.*;
import java.util.Hashtable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
import static cbit.vcell.client.task.AsynchClientTask.*;
@@ -40,6 +43,37 @@ public void sbNotLast( ) {
test(TASKTYPE_NONSWING_BLOCKING,TASKTYPE_NONSWING_BLOCKING, TASKTYPE_SWING_NONBLOCKING, TASKTYPE_NONSWING_BLOCKING);
});
}
+
+ @Test void blockingCheck(){
+ AsynchClientTask collatzConjecture = new AsynchClientTask(
+ "Collatz Conjecture", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ for (long startingNum = 1; startingNum < Long.MAX_VALUE; startingNum++) {
+ long currentNum = startingNum;
+ long counter = 0;
+ while(true){
+ if (currentNum == 1 || currentNum == 2 || currentNum == 4) {
+ // We won't waste storage space
+ System.out.print(counter + ", ");
+ break;
+ }
+ counter++;
+ if (currentNum % 2 == 0) currentNum /= 2; // Even case
+ if (currentNum %2 == 1) currentNum = (3 * currentNum) + 1;
+ }
+ }
+ }
+ } ;
+ Assertions.assertThrows(TimeoutException.class, () -> {
+ Hashtable hashTable = new Hashtable<>();
+ Future> terribleFuture = ClientTaskDispatcher.dispatchWithFuture(null, hashTable,
+ new AsynchClientTask[]{collatzConjecture});
+ terribleFuture.get(2, TimeUnit.SECONDS); // Not expensive but significant timeout
+ });
+
+ }
private AsynchClientTask[] create(int ... types) {
AsynchClientTask[] rval = new AsynchClientTask[types.length];
diff --git a/vcell-apiclient/src/main/java/org/vcell/api/client/VCellApiClient.java b/vcell-apiclient/src/main/java/org/vcell/api/client/VCellApiClient.java
index 1c7b284458..cf666ee6e2 100644
--- a/vcell-apiclient/src/main/java/org/vcell/api/client/VCellApiClient.java
+++ b/vcell-apiclient/src/main/java/org/vcell/api/client/VCellApiClient.java
@@ -61,6 +61,12 @@
public class VCellApiClient implements AutoCloseable {
private static final Logger lg = LogManager.getLogger(VCellApiClient.class);
+ private static final boolean activeLogLevelIsSensitiveEnough;
+
+ static {
+ activeLogLevelIsSensitiveEnough = lg.isTraceEnabled();
+ }
+
private final HttpHost httpHost;
private final String pathPrefix_v0;
private final String clientID;
@@ -202,13 +208,13 @@ public SimulationTaskRepresentation[] getSimTasks(SimTasksQuerySpec simTasksQuer
HttpGet httpget = new HttpGet(getApiUrlPrefix() + "/simtask?" + simTasksQuerySpec.getQueryString());
httpget.addHeader("Authorization","Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve simulation tasks " + httpget.getRequestLine());
}
String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("getSimTasks()", httpget), httpClientContext);
String simTasksJson = responseBody;
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("returned: "+toStringTruncated(simTasksJson));
}
@@ -231,13 +237,13 @@ public BiomodelRepresentation[] getBioModels(BioModelsQuerySpec bioModelsQuerySp
HttpGet httpget = new HttpGet(getApiUrlPrefix()+"/biomodel?"+bioModelsQuerySpec.getQueryString());
httpget.addHeader("Authorization","Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve biomodels " + httpget.getRequestLine());
}
String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("getBioModels()", httpget), httpClientContext);
String bimodelsJson = responseBody;
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("returned: "+toStringTruncated(bimodelsJson));
}
@@ -251,13 +257,13 @@ public EventWrapper[] getEvents(long beginTimestamp) throws IOException {
HttpGet httpget = new HttpGet(getApiUrlPrefix()+"/events?beginTimestamp="+beginTimestamp);
httpget.addHeader("Authorization","Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (lg.isTraceEnabled()) {
lg.info("Executing request to retrieve user events " + httpget.getRequestLine());
}
String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("getEvents()", httpget), httpClientContext);
String eventWrappersJson = responseBody;
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("returned: "+toStringTruncated(eventWrappersJson));
}
@@ -271,13 +277,13 @@ public BiomodelRepresentation getBioModel(String bmId) throws IOException {
HttpGet httpget = new HttpGet(getApiUrlPrefix()+"/biomodel/"+bmId);
httpget.addHeader("Authorization","Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve biomodel " + httpget.getRequestLine());
}
String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("getBioModel()", httpget), httpClientContext);
String bimodelsJson = responseBody;
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("returned: "+toStringTruncated(bimodelsJson));
}
@@ -291,7 +297,7 @@ public String getBioModelVCML(String bmId) throws IOException {
HttpGet httpget = new HttpGet(getApiUrlPrefix()+"/biomodel/"+bmId+"/biomodel.vcml");
httpget.addHeader("Authorization","Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve biomodel " + httpget.getRequestLine());
}
@@ -306,13 +312,13 @@ public SimulationRepresentation getSimulation(String bmId, String simKey) throws
HttpGet httpget = new HttpGet(getApiUrlPrefix()+"/biomodel/"+bmId+"/simulation/"+simKey);
httpget.addHeader("Authorization","Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve simulation " + httpget.getRequestLine());
}
String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("getSimulation()", httpget), httpClientContext);
String simulationJson = responseBody;
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("returned: "+toStringTruncated(simulationJson));
}
@@ -326,12 +332,12 @@ public String getOptRunJson(String optimizationId,boolean bStop) throws IOExcept
HttpGet httpget = new HttpGet(getApiUrlPrefix()+"/optimization/"+optimizationId+"?bStop="+bStop);
httpget.addHeader("Authorization","Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve optimization run " + httpget.getRequestLine());
}
String responseBody = httpclient.execute(httpget, new VCellStringResponseHandler("getOptRunJson()", httpget), httpClientContext);
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("returned: "+toStringTruncated(responseBody));
}
return responseBody;
@@ -429,7 +435,7 @@ public SimulationTaskRepresentation[] startSimulation(String bmId, String simKey
HttpPost httppost = new HttpPost(getApiUrlPrefix()+"/biomodel/"+bmId+"/simulation/"+simKey+"/startSimulation");
httppost.addHeader("Authorization", "Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve simulation " + httppost.getRequestLine());
}
@@ -453,13 +459,13 @@ public SimulationTaskRepresentation[] stopSimulation(String bmId, String simKey)
HttpPost httppost = new HttpPost(getApiUrlPrefix()+"/biomodel/"+bmId+"/simulation/"+simKey+"/stopSimulation");
httppost.addHeader("Authorization", "Bearer "+httpClientContext.getUserToken(String.class));
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve simulation " + httppost.getRequestLine());
}
String responseBody = httpclient.execute(httppost, new VCellStringResponseHandler("stopSimulation()", httppost), httpClientContext);
String simTaskReps = responseBody;
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("returned: "+toStringTruncated(simTaskReps));
}
@@ -826,7 +832,7 @@ public String getServerSoftwareVersion() throws ClientProtocolException, IOExcep
HttpGet httpget = new HttpGet(getApiUrlPrefix()+"/swversion");
- if (lg.isInfoEnabled()) {
+ if (activeLogLevelIsSensitiveEnough) {
lg.info("Executing request to retrieve server software version " + httpget.getRequestLine());
}
diff --git a/vcell-client/src/main/java/cbit/gui/graph/gui/CartoonTool.java b/vcell-client/src/main/java/cbit/gui/graph/gui/CartoonTool.java
index 9a617e89ea..e725e35d15 100644
--- a/vcell-client/src/main/java/cbit/gui/graph/gui/CartoonTool.java
+++ b/vcell-client/src/main/java/cbit/gui/graph/gui/CartoonTool.java
@@ -48,11 +48,13 @@
import cbit.gui.graph.actions.CartoonToolSaveAsImageActions;
import cbit.gui.graph.actions.GraphViewAction;
import cbit.gui.graph.groups.VCGroupManager;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
import org.vcell.util.gui.GeneralGuiUtils;
public abstract class CartoonTool implements GraphView, MouseListener,
MouseMotionListener, ActionListener, KeyListener {
-
+ private static final Logger lg = LogManager.getLogger(CartoonTool.class);
public static final boolean GROUPS_ARE_ENABLED = false;
private GraphPane graphPane = null;
@@ -359,7 +361,7 @@ public final void updateButtonGroup(ButtonGroup buttonGroup,
return;
}
}
- System.out.println("ERROR: button with actionCommand " + actionCommand + " not found");
+ lg.warn("ERROR: button with actionCommand {} not found", actionCommand);
return;
}
diff --git a/vcell-client/src/main/java/cbit/vcell/client/ClientRequestManager.java b/vcell-client/src/main/java/cbit/vcell/client/ClientRequestManager.java
index 44af99645f..8afaf469ae 100644
--- a/vcell-client/src/main/java/cbit/vcell/client/ClientRequestManager.java
+++ b/vcell-client/src/main/java/cbit/vcell/client/ClientRequestManager.java
@@ -130,877 +130,886 @@
import java.util.zip.GZIPInputStream;
public class ClientRequestManager
- implements RequestManager, PropertyChangeListener, ExportListener, VCellMessageEventListener {
- private VCellClient vcellClient = null;
-
- private boolean bOpening = false;
- private boolean bExiting = false;
-
- private static final Logger lg = LogManager.getLogger(ClientRequestManager.class);
-
- public ClientRequestManager(VCellClient vcellClient) {
- setVcellClient(vcellClient);
- // listen to connectionStatus events
- getClientServerManager().addPropertyChangeListener(this);
- getClientServerManager().getAsynchMessageManager().addExportListener(this);
- getClientServerManager().getAsynchMessageManager().addVCellMessageEventListener(this);
-
- }
-
- private static final String GEOMETRY_KEY = "geometry";
- private static final String VERSIONINFO_KEY = "VERSIONINFO_KEY";
-
- private AsynchClientTask createSelectDocTask(final TopLevelWindowManager requester) {
- AsynchClientTask selectDocumentTypeTask = new AsynchClientTask("Select/Load geometry",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- String[][] docTypeoptions = new String[][] { { "BioModel names" }, { "MathModel names" } };
- VCDocumentType[] sourceDocumentTypes = new VCDocumentType[] { VCDocumentType.BIOMODEL_DOC,
- VCDocumentType.MATHMODEL_DOC };
- VCAssert.assertTrue(docTypeoptions.length == sourceDocumentTypes.length, "Label and types mismatch");
- int[] geomType = DialogUtils.showComponentOKCancelTableList(
- JOptionPane.getFrameForComponent(requester.getComponent()), "Select different Geometry",
- new String[] { "Search by" }, docTypeoptions, ListSelectionModel.SINGLE_SELECTION);
- final int selectedType = geomType[0];
- VCDocumentType sourceDocumentType = sourceDocumentTypes[selectedType];
- VersionInfo vcVersionInfo = null;
- if (geomType[0] == 3) {
- ImageDbTreePanel imageDbTreePanel = new ImageDbTreePanel();
- imageDbTreePanel.setDocumentManager(getDocumentManager());
- imageDbTreePanel.setPreferredSize(new java.awt.Dimension(200, 400));
- vcVersionInfo = DialogUtils.getDBTreePanelSelection(requester.getComponent(), imageDbTreePanel,
- "OK", "Select Image:");
- } else {
- if(hashTable.get(BioModelWindowManager.SELECT_GEOM_POPUP) != null && ((Boolean)hashTable.get(BioModelWindowManager.SELECT_GEOM_POPUP)).booleanValue()) {
- if(getClientTaskStatusSupport() instanceof AsynchProgressPopup) {
- ((AsynchProgressPopup)getClientTaskStatusSupport()).setVisible(false);
- }
- try {
- Object obj = getMdiManager().getDatabaseWindowManager().selectDocument2(sourceDocumentType,
- requester);
- if (obj instanceof Geometry) {//user selected geometry directly using popup
- hashTable.put(GEOMETRY_KEY, ((Geometry) obj));
- return;
- }
- vcVersionInfo = (VersionInfo) obj;//user selected VCDocument, list will be shown to select from
- } finally {
- if(getClientTaskStatusSupport() instanceof AsynchProgressPopup) {
- ((AsynchProgressPopup)getClientTaskStatusSupport()).setVisible(true);
- }
- }
- }else {
- vcVersionInfo = selectDocumentFromType(sourceDocumentType, requester);
- }
- }
- hashTable.put(VERSIONINFO_KEY, vcVersionInfo);
- }
- };
- return selectDocumentTypeTask;
- }
-
- private AsynchClientTask createSelectLoadGeomTask(final TopLevelWindowManager requester) {
- AsynchClientTask selectLoadGeomTask = new AsynchClientTask("Select/Load geometry...",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- if(hashTable.get(GEOMETRY_KEY) != null) {//Already loaded from selection of BioModelDBTree from previous task
- ((Geometry)hashTable.get(GEOMETRY_KEY)).precomputeAll(new GeometryThumbnailImageFactoryAWT());
- return;
- }
- VersionInfo vcVersionInfo = (VersionInfo) hashTable.get(VERSIONINFO_KEY);
- Geometry geom = null;
- if (vcVersionInfo instanceof VCDocumentInfo) {
- geom = getGeometryFromDocumentSelection(requester.getComponent(), (VCDocumentInfo) vcVersionInfo,
- false);
- } else if (vcVersionInfo instanceof VCImageInfo) {
- VCImage img = getDocumentManager().getImage((VCImageInfo) vcVersionInfo);
- geom = new Geometry("createSelectLoadGeomTask", img);
- } else {
- throw new Exception("Unexpected versioninfo type.");
- }
- geom.precomputeAll(new GeometryThumbnailImageFactoryAWT());// pregenerate sampled image, cpu intensive
- hashTable.put(GEOMETRY_KEY, geom);
- }
- };
- return selectLoadGeomTask;
- }
-
- private void changeGeometry0(final TopLevelWindowManager requester, final SimulationContext simContext,Hashtable hashTable) {
-
- AsynchClientTask selectDocumentTypeTask = createSelectDocTask(requester);
-
- AsynchClientTask selectLoadGeomTask = createSelectLoadGeomTask(requester);
-
- AsynchClientTask processGeometryTask = new AsynchClientTask("Processing geometry...",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- Geometry newGeometry = (Geometry) hashTable.get(GEOMETRY_KEY);
- if (requester instanceof MathModelWindowManager) {
- // User can cancel here
- continueAfterMathModelGeomChangeWarning((MathModelWindowManager) requester, newGeometry);
- }
- if (newGeometry.getDimension() > 0
- && newGeometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
- newGeometry.getGeometrySurfaceDescription().updateAll();
- }
- }
- };
- AsynchClientTask setNewGeometryTask = new AsynchClientTask("Setting new Geometry...",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- Geometry newGeometry = (Geometry) hashTable.get(GEOMETRY_KEY);
- if (newGeometry != null) {
- if (requester instanceof BioModelWindowManager) {
- simContext.setGeometry(newGeometry);
- } else if (requester instanceof MathModelWindowManager) {
- MathModel mathModel = (MathModel) ((MathModelWindowManager) requester).getVCDocument();
- mathModel.getMathDescription().setGeometry(newGeometry);
- }
- }
- }
- };
-
- ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] {
- selectDocumentTypeTask, selectLoadGeomTask, processGeometryTask, setNewGeometryTask }, false);
-
- }
-
- public void changeGeometry(DocumentWindowManager requester, SimulationContext simContext,Hashtable hashTable) {
- changeGeometry0(requester, simContext,hashTable);
- }
-
- public static void continueAfterMathModelGeomChangeWarning(MathModelWindowManager mathModelWindowManager,
- Geometry newGeometry) throws UserCancelException {
-
- MathModel mathModel = mathModelWindowManager.getMathModel();
- if (mathModel != null && mathModel.getMathDescription() != null) {
- Geometry oldGeometry = mathModel.getMathDescription().getGeometry();
- if (oldGeometry != null && oldGeometry.getDimension() == 0) {
- return;
- }
- boolean bMeshResolutionChange = true;
- if (oldGeometry == null) {
- bMeshResolutionChange = false;
- }
- if (newGeometry != null && oldGeometry != null
- && oldGeometry.getDimension() == newGeometry.getDimension()) {
- bMeshResolutionChange = false;
- }
- boolean bHasSims = (mathModel.getSimulations() != null) && (mathModel.getSimulations().length > 0);
- StringBuffer meshResolutionChangeSB = new StringBuffer();
- if (bHasSims && bMeshResolutionChange) {
- ISize newGeomISize = MeshSpecification.calulateResetSamplingSize(newGeometry);
- for (int i = 0; i < mathModel.getSimulations().length; i++) {
- if (mathModel.getSimulations()[i].getMeshSpecification() != null) {
- String simName = mathModel.getSimulations()[i].getName();
- ISize simMeshSize = mathModel.getSimulations()[i].getMeshSpecification().getSamplingSize();
- meshResolutionChangeSB.append((i != 0 ? "\n" : "") + "'" + simName + "' Mesh" + simMeshSize
- + " will be reset to " + newGeomISize + "");
- }
- }
- }
-
- String result = DialogUtils.showWarningDialog(
- JOptionPane.getFrameForComponent(mathModelWindowManager.getComponent()),
- "After changing MathModel geometry please note:\n"
- + " 1. Check Geometry subvolume names match MathModel compartment names."
- + (bHasSims && bMeshResolutionChange ? "\n"
- + " 2. All existing simulations mesh sizes will be reset"
- + " because the new Geometry spatial dimension(" + newGeometry.getDimension() + "D)"
- + " does not equal the current Geometry spatial dimension("
- + oldGeometry.getDimension() + "D)" + "\n" + meshResolutionChangeSB.toString()
- : ""),
- new String[] { "Continue", "Cancel" }, "Continue");
- if (result != null && result.equals("Continue")) {
- return;
- }
- } else {
- return;
- }
-
- throw UserCancelException.CANCEL_GENERIC;
- }
-
- enum CloseOption {
- SAVE_AND_CLOSE, CLOSE_IN_ANY_CASE, CANCEL_CLOSE,
- }
-
- public enum CallAction {
- EXPORT, RUN, SAVE, SAVEASNEW,
- }
-
- private CloseOption checkBeforeClosing(DocumentWindowManager windowManager) {
- getMdiManager().showWindow(windowManager.getManagerID());
- // we need to check for changes and get user confirmation...
- VCDocument vcDocument = windowManager.getVCDocument();
- if (vcDocument.getVersion() == null && !isDifferentFromBlank(vcDocument.getDocumentType(), vcDocument)) {
- return CloseOption.CLOSE_IN_ANY_CASE;
- }
- boolean isChanged = true;
- try {
- isChanged = getDocumentManager().isChanged(vcDocument);
- } catch (Exception exc) {
- exc.printStackTrace();
- String choice = PopupGenerator.showWarningDialog(windowManager, getUserPreferences(),
- UserMessage.warn_UnableToCheckForChanges, null);
- if (choice.equals(UserMessage.OPTION_CANCEL)) {
- // user canceled
- return CloseOption.CANCEL_CLOSE;
- }
- }
- // warn if necessary
- if (isChanged) {
- JDialog dialog = new JDialog();
- dialog.setAlwaysOnTop(true);
- final String[] warnCloseArr = new String[] { UserMessage.OPTION_YES, "No", UserMessage.OPTION_CANCEL };
- int confirm = JOptionPane.showOptionDialog(dialog, UserMessage.warn_close.getMessage(null),
- "Save warning...", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, warnCloseArr,
- warnCloseArr[0]);
+ implements RequestManager, PropertyChangeListener, ExportListener, VCellMessageEventListener {
+ private VCellClient vcellClient = null;
+
+ private boolean bOpening = false;
+ private boolean bExiting = false;
+
+ private static final Logger lg = LogManager.getLogger(ClientRequestManager.class);
+
+ public ClientRequestManager(VCellClient vcellClient) {
+ this.setVcellClient(vcellClient);
+ // listen to connectionStatus events
+ this.getClientServerManager().addPropertyChangeListener(this);
+ this.getClientServerManager().getAsynchMessageManager().addExportListener(this);
+ this.getClientServerManager().getAsynchMessageManager().addVCellMessageEventListener(this);
+
+ }
+
+ private static final String GEOMETRY_KEY = "geometry";
+ private static final String VERSIONINFO_KEY = "VERSIONINFO_KEY";
+
+ private AsynchClientTask createSelectDocTask(final TopLevelWindowManager requester) {
+ AsynchClientTask selectDocumentTypeTask = new AsynchClientTask("Select/Load geometry",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ String[][] docTypeoptions = new String[][]{{"BioModel names"}, {"MathModel names"}};
+ VCDocumentType[] sourceDocumentTypes = new VCDocumentType[]{VCDocumentType.BIOMODEL_DOC,
+ VCDocumentType.MATHMODEL_DOC};
+ VCAssert.assertTrue(docTypeoptions.length == sourceDocumentTypes.length, "Label and types mismatch");
+ int[] geomType = DialogUtils.showComponentOKCancelTableList(
+ JOptionPane.getFrameForComponent(requester.getComponent()), "Select different Geometry",
+ new String[]{"Search by"}, docTypeoptions, ListSelectionModel.SINGLE_SELECTION);
+ final int selectedType = geomType[0];
+ VCDocumentType sourceDocumentType = sourceDocumentTypes[selectedType];
+ VersionInfo vcVersionInfo = null;
+ if (geomType[0] == 3) {
+ ImageDbTreePanel imageDbTreePanel = new ImageDbTreePanel();
+ imageDbTreePanel.setDocumentManager(ClientRequestManager.this.getDocumentManager());
+ imageDbTreePanel.setPreferredSize(new java.awt.Dimension(200, 400));
+ vcVersionInfo = DialogUtils.getDBTreePanelSelection(requester.getComponent(), imageDbTreePanel,
+ "OK", "Select Image:");
+ } else {
+ if (hashTable.get(BioModelWindowManager.SELECT_GEOM_POPUP) != null && ((Boolean) hashTable.get(BioModelWindowManager.SELECT_GEOM_POPUP)).booleanValue()) {
+ if (this.getClientTaskStatusSupport() instanceof AsynchProgressPopup) {
+ ((AsynchProgressPopup) this.getClientTaskStatusSupport()).setVisible(false);
+ }
+ try {
+ Object obj = ClientRequestManager.this.getMdiManager().getDatabaseWindowManager().selectDocument2(sourceDocumentType,
+ requester);
+ if (obj instanceof Geometry) {//user selected geometry directly using popup
+ hashTable.put(GEOMETRY_KEY, obj);
+ return;
+ }
+ vcVersionInfo = (VersionInfo) obj;//user selected VCDocument, list will be shown to select from
+ } finally {
+ if (this.getClientTaskStatusSupport() instanceof AsynchProgressPopup) {
+ ((AsynchProgressPopup) this.getClientTaskStatusSupport()).setVisible(true);
+ }
+ }
+ } else {
+ vcVersionInfo = ClientRequestManager.this.selectDocumentFromType(sourceDocumentType, requester);
+ }
+ }
+ hashTable.put(VERSIONINFO_KEY, vcVersionInfo);
+ }
+ };
+ return selectDocumentTypeTask;
+ }
+
+ private AsynchClientTask createSelectLoadGeomTask(final TopLevelWindowManager requester) {
+ AsynchClientTask selectLoadGeomTask = new AsynchClientTask("Select/Load geometry...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ if (hashTable.get(GEOMETRY_KEY) != null) {//Already loaded from selection of BioModelDBTree from previous task
+ ((Geometry) hashTable.get(GEOMETRY_KEY)).precomputeAll(new GeometryThumbnailImageFactoryAWT());
+ return;
+ }
+ VersionInfo vcVersionInfo = (VersionInfo) hashTable.get(VERSIONINFO_KEY);
+ Geometry geom = null;
+ if (vcVersionInfo instanceof VCDocumentInfo) {
+ geom = ClientRequestManager.this.getGeometryFromDocumentSelection(requester.getComponent(), (VCDocumentInfo) vcVersionInfo,
+ false);
+ } else if (vcVersionInfo instanceof VCImageInfo) {
+ VCImage img = ClientRequestManager.this.getDocumentManager().getImage((VCImageInfo) vcVersionInfo);
+ geom = new Geometry("createSelectLoadGeomTask", img);
+ } else {
+ throw new Exception("Unexpected versioninfo type.");
+ }
+ geom.precomputeAll(new GeometryThumbnailImageFactoryAWT());// pregenerate sampled image, cpu intensive
+ hashTable.put(GEOMETRY_KEY, geom);
+ }
+ };
+ return selectLoadGeomTask;
+ }
+
+ private void changeGeometry0(final TopLevelWindowManager requester, final SimulationContext simContext, Hashtable hashTable) {
+
+ AsynchClientTask selectDocumentTypeTask = this.createSelectDocTask(requester);
+
+ AsynchClientTask selectLoadGeomTask = this.createSelectLoadGeomTask(requester);
+
+ AsynchClientTask processGeometryTask = new AsynchClientTask("Processing geometry...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ Geometry newGeometry = (Geometry) hashTable.get(GEOMETRY_KEY);
+ if (requester instanceof MathModelWindowManager) {
+ // User can cancel here
+ continueAfterMathModelGeomChangeWarning((MathModelWindowManager) requester, newGeometry);
+ }
+ if (newGeometry.getDimension() > 0
+ && newGeometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
+ newGeometry.getGeometrySurfaceDescription().updateAll();
+ }
+ }
+ };
+ AsynchClientTask setNewGeometryTask = new AsynchClientTask("Setting new Geometry...",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ Geometry newGeometry = (Geometry) hashTable.get(GEOMETRY_KEY);
+ if (newGeometry != null) {
+ if (requester instanceof BioModelWindowManager) {
+ simContext.setGeometry(newGeometry);
+ } else if (requester instanceof MathModelWindowManager) {
+ MathModel mathModel = (MathModel) ((MathModelWindowManager) requester).getVCDocument();
+ mathModel.getMathDescription().setGeometry(newGeometry);
+ }
+ }
+ }
+ };
+
+ ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[]{
+ selectDocumentTypeTask, selectLoadGeomTask, processGeometryTask, setNewGeometryTask}, false);
+
+ }
+
+ public void changeGeometry(DocumentWindowManager requester, SimulationContext simContext, Hashtable hashTable) {
+ this.changeGeometry0(requester, simContext, hashTable);
+ }
+
+ public static void continueAfterMathModelGeomChangeWarning(MathModelWindowManager mathModelWindowManager,
+ Geometry newGeometry) throws UserCancelException {
+
+ MathModel mathModel = mathModelWindowManager.getMathModel();
+ if (mathModel != null && mathModel.getMathDescription() != null) {
+ Geometry oldGeometry = mathModel.getMathDescription().getGeometry();
+ if (oldGeometry != null && oldGeometry.getDimension() == 0) {
+ return;
+ }
+ boolean bMeshResolutionChange = oldGeometry != null;
+ if (newGeometry != null && oldGeometry != null
+ && oldGeometry.getDimension() == newGeometry.getDimension()) {
+ bMeshResolutionChange = false;
+ }
+ boolean bHasSims = (mathModel.getSimulations() != null) && (mathModel.getSimulations().length > 0);
+ StringBuffer meshResolutionChangeSB = new StringBuffer();
+ if (bHasSims && bMeshResolutionChange) {
+ ISize newGeomISize = MeshSpecification.calulateResetSamplingSize(newGeometry);
+ for (int i = 0; i < mathModel.getSimulations().length; i++) {
+ if (mathModel.getSimulations()[i].getMeshSpecification() != null) {
+ String simName = mathModel.getSimulations()[i].getName();
+ ISize simMeshSize = mathModel.getSimulations()[i].getMeshSpecification().getSamplingSize();
+ meshResolutionChangeSB.append((i != 0 ? "\n" : "") + "'" + simName + "' Mesh" + simMeshSize
+ + " will be reset to " + newGeomISize);
+ }
+ }
+ }
+
+ String result = DialogUtils.showWarningDialog(
+ JOptionPane.getFrameForComponent(mathModelWindowManager.getComponent()),
+ "After changing MathModel geometry please note:\n"
+ + " 1. Check Geometry subvolume names match MathModel compartment names."
+ + (bHasSims && bMeshResolutionChange ? "\n"
+ + " 2. All existing simulations mesh sizes will be reset"
+ + " because the new Geometry spatial dimension(" + newGeometry.getDimension() + "D)"
+ + " does not equal the current Geometry spatial dimension("
+ + oldGeometry.getDimension() + "D)" + "\n" + meshResolutionChangeSB
+ : ""),
+ new String[]{"Continue", "Cancel"}, "Continue");
+ if (result != null && result.equals("Continue")) {
+ return;
+ }
+ } else {
+ return;
+ }
+
+ throw UserCancelException.CANCEL_GENERIC;
+ }
+
+ enum CloseOption {
+ SAVE_AND_CLOSE, CLOSE_IN_ANY_CASE, CANCEL_CLOSE,
+ }
+
+ public enum CallAction {
+ EXPORT, RUN, SAVE, SAVEASNEW,
+ }
+
+ private CloseOption checkBeforeClosing(DocumentWindowManager windowManager) {
+ this.getMdiManager().showWindow(windowManager.getManagerID());
+ // we need to check for changes and get user confirmation...
+ VCDocument vcDocument = windowManager.getVCDocument();
+ if (vcDocument.getVersion() == null && !this.isDifferentFromBlank(vcDocument.getDocumentType(), vcDocument)) {
+ return CloseOption.CLOSE_IN_ANY_CASE;
+ }
+ boolean isChanged = true;
+ String IS_CHANGED_KEY = this.getClass().getName() + ".DocumentManager::isChanged";
+ Hashtable hashtable = new Hashtable<>();
+ try {
+ AsynchClientTask checkIfChanged = new AsynchClientTask(
+ "Checking if model has changed...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ boolean hasBeenChanged = ClientRequestManager.this.getDocumentManager().isChanged(vcDocument);
+ hashTable.put(IS_CHANGED_KEY, hasBeenChanged);
+ }
+ };
+ ClientTaskDispatcher.dispatchAndWait(null, hashtable, new AsynchClientTask[]{checkIfChanged},
+ false, false, null, true);
+ if (hashtable.containsKey(IS_CHANGED_KEY))
+ isChanged = (Boolean) hashtable.get(IS_CHANGED_KEY);
+ else if (hashtable.containsKey("clientTaskDispatcherStackTraceArray")) {
+ StringBuilder stackTrace = new StringBuilder();
+ for (StackTraceElement elem : (StackTraceElement[]) hashtable.get("clientTaskDispatcherStackTraceArray"))
+ stackTrace.append(" \tat ").append(elem.toString()).append("\n");
+ lg.error("Unknown error occurred during task 'Checking if model has changed'\n{}", stackTrace);
+ }
+ } catch (Exception exc) {
+ exc.printStackTrace();
+ String choice = PopupGenerator.showWarningDialog(windowManager, this.getUserPreferences(),
+ UserMessage.warn_UnableToCheckForChanges, null);
+ if (choice.equals(UserMessage.OPTION_CANCEL)) {
+ // user canceled
+ return CloseOption.CANCEL_CLOSE;
+ }
+ }
+ // warn if necessary
+ if (isChanged) {
+ JDialog dialog = new JDialog();
+ dialog.setAlwaysOnTop(true);
+ final String[] warnCloseArr = new String[]{UserMessage.OPTION_YES, "No", UserMessage.OPTION_CANCEL};
+ int confirm = JOptionPane.showOptionDialog(dialog, UserMessage.warn_close.getMessage(null),
+ "Save warning...", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, warnCloseArr,
+ warnCloseArr[0]);
// String choice = PopupGenerator.showWarningDialog(windowManager, getUserPreferences(), UserMessage.warn_close,null);
- if (confirm != 0 && confirm != 1/* choice.equals(UserMessage.OPTION_CANCEL) */) {
- // user canceled
- return CloseOption.CANCEL_CLOSE;
- }
- if (confirm == 0/* choice.equals(UserMessage.OPTION_YES) */) {
- return CloseOption.SAVE_AND_CLOSE;
- }
- }
- // nothing changed, or user confirmed, close it
- return CloseOption.CLOSE_IN_ANY_CASE;
- }
-
- public boolean isDifferentFromBlank(VCDocumentType documentType, VCDocument vcDocument) {
- // Handle Bio/Math models different from Geometry since createDefaultDoc for
- // Geometry
- // will bring up the NewGeometryEditor which is unnecessary.
- // figure out if we come from a blank new document; if so, replace it inside
- // same window
-
- if (documentType != vcDocument.getDocumentType()) {
- // If the docType we are trying to open is not the same as the requesting
- // windowmanager's docType
- // we have to open the doc in a new window, hence return true;
- return true;
- }
- VCDocument blank = null;
- if (vcDocument.getDocumentType() != VCDocumentType.GEOMETRY_DOC) {
- // BioModel/MathModel
- blank = createDefaultDocument(vcDocument.getDocumentType());
- try {
- blank.setName(vcDocument.getName());
- } catch (PropertyVetoException e) {
- } // ignore. doesn't happen
- return !blank.compareEqual(vcDocument);
- } else {
- // Geometry
- blank = new Geometry(vcDocument.getName(), 1);
- if (blank.compareEqual(vcDocument)) {
- return false;
- }
-
- blank = new Geometry(vcDocument.getName(), 2);
- if (blank.compareEqual(vcDocument)) {
- return false;
- }
-
- blank = new Geometry(vcDocument.getName(), 3);
- if (blank.compareEqual(vcDocument)) {
- return false;
- }
- return true;
- }
- }
-
- @Override
- public ClientServerInfo getClientServerInfo() {
- return getVcellClient().getClientServerManager().getClientServerInfo();
- }
-
- private boolean closeAllWindows(boolean duringExit) {
- // create copy to avoid ConcurrentModification exception caused by closing
- // window
- ArrayList modificationSafeCopy = new ArrayList<>(getMdiManager().getWindowManagers());
- for (TopLevelWindowManager windowManager : modificationSafeCopy) {
- boolean closed = closeWindow(windowManager.getManagerID(), duringExit);
- if (!closed) {
- // user canceled, don't keep going...
- return false;
- }
- }
- return true;
- }
-
- public boolean closeWindow(final java.lang.String windowID, final boolean exitIfLast) {
- // called from DocumentWindow or from DatabaseWindow
- final TopLevelWindowManager windowManager = getMdiManager().getWindowManager(windowID);
- if (windowManager instanceof DocumentWindowManager) {
- // we'll need to run some checks first
- getMdiManager().showWindow(windowID);
- getMdiManager().blockWindow(windowID);
- CloseOption closeOption = checkBeforeClosing((DocumentWindowManager) windowManager);
- if (closeOption.equals(CloseOption.CANCEL_CLOSE)) {
- // user canceled
- getMdiManager().unBlockWindow(windowID);
- return false;
- } else if (closeOption.equals(CloseOption.SAVE_AND_CLOSE)) {
- AsynchClientTask closeTask = new AsynchClientTask("closing document",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- // if there is error saving the document, try to unblock the window
- if (hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR) != null) {
- getMdiManager().unBlockWindow(windowID);
- getMdiManager().showWindow(windowID);
- } else {
- long openWindows = getMdiManager().closeWindow(windowManager.getManagerID());
- if (exitIfLast && (openWindows == 0)) {
- setBExiting(true);
- exitApplication();
- }
- }
- }
-
- @Override
- public boolean skipIfCancel(UserCancelException exc) {
- // if save as new edition, don't skip
- if (exc == UserCancelException.CANCEL_DELETE_OLD
- || exc == UserCancelException.CANCEL_NEW_NAME) {
- return false;
- } else {
- return true;
- }
- }
- };
-
- if (((DocumentWindowManager) windowManager).getUser() == null
- || User.isGuest(((DocumentWindowManager) windowManager).getUser().getName())) {
- JDialog dialog = new JDialog();
- dialog.setAlwaysOnTop(true);
- JOptionPane.showMessageDialog(dialog, User.createGuestErrorMessage("saveDocument"), "Error...",
- JOptionPane.ERROR_MESSAGE, null);
- return false;
- }
-
- saveDocument((DocumentWindowManager) windowManager, true, closeTask);
- return true;
- } else {
- long openWindows = getMdiManager().closeWindow(windowID);
- if (exitIfLast && (openWindows == 0)) {
- setBExiting(true);
- exitApplication();
- }
- return true;
- }
- } else if (windowManager instanceof DatabaseWindowManager) {
- // nothing to check here, just close it
- long openWindows = getMdiManager().closeWindow(windowID);
- if (exitIfLast && (openWindows == 0)) {
- setBExiting(true);
- exitApplication();
- }
- return true;
- } else if (windowManager instanceof TestingFrameworkWindowManager) {
- // nothing to check here, just close it
- long openWindows = getMdiManager().closeWindow(windowID);
- if (exitIfLast && (openWindows == 0)) {
- setBExiting(true);
- exitApplication();
- }
- return true;
- } else if (windowManager instanceof BNGWindowManager) {
- // nothing to check here, just close it
- long openWindows = getMdiManager().closeWindow(windowID);
- if (exitIfLast && (openWindows == 0)) {
- setBExiting(true);
- exitApplication();
- }
- return true;
- } else if (windowManager instanceof FieldDataWindowManager) {
- // nothing to check here, just close it
- long openWindows = getMdiManager().closeWindow(windowID);
- if (exitIfLast && (openWindows == 0)) {
- setBExiting(true);
- exitApplication();
- }
- return true;
- } else {
- return false;
- }
- }
-
- private XmlTreeDiff compareDocuments(final VCDocument doc1, final VCDocument doc2,
- DiffConfiguration comparisonSetting) throws Exception {
-
- VCellThreadChecker.checkCpuIntensiveInvocation();
-
- if ((DiffConfiguration.COMPARE_DOCS_SAVED != comparisonSetting)
- && (DiffConfiguration.COMPARE_DOCS_OTHER != comparisonSetting)) {
- throw new RuntimeException("Unsupported comparison setting: " + comparisonSetting);
- }
- if (doc1.getDocumentType() != doc2.getDocumentType()) {
- throw new RuntimeException("Only comparison of documents of the same type is currently supported");
- }
- String doc1XML = null;
- String doc2XML = null;
- switch (doc1.getDocumentType()) {
- case BIOMODEL_DOC: {
- doc1XML = XmlHelper.bioModelToXML((BioModel) doc1);
- doc2XML = XmlHelper.bioModelToXML((BioModel) doc2);
- break;
- }
- case MATHMODEL_DOC: {
- doc1XML = XmlHelper.mathModelToXML((MathModel) doc1);
- doc2XML = XmlHelper.mathModelToXML((MathModel) doc2);
- break;
- }
- case GEOMETRY_DOC: {
- doc1XML = XmlHelper.geometryToXML((Geometry) doc1);
- doc2XML = XmlHelper.geometryToXML((Geometry) doc2);
- break;
- }
- }
- final XmlTreeDiff diffTree = XmlHelper.compareMerge(doc1XML, doc2XML, comparisonSetting, true);
- return diffTree;
- }
-
- public XmlTreeDiff compareWithOther(final VCDocumentInfo docInfo1, final VCDocumentInfo docInfo2) {
-
- VCDocument document1, document2;
-
- try {
- // get the VCDocument versions from documentManager
- if (docInfo1 instanceof BioModelInfo && docInfo2 instanceof BioModelInfo) {
- document1 = getDocumentManager().getBioModel((BioModelInfo) docInfo1);
- document2 = getDocumentManager().getBioModel((BioModelInfo) docInfo2);
- } else if (docInfo1 instanceof MathModelInfo && docInfo2 instanceof MathModelInfo) {
- document1 = getDocumentManager().getMathModel((MathModelInfo) docInfo1);
- document2 = getDocumentManager().getMathModel((MathModelInfo) docInfo2);
- } else if (docInfo1 instanceof GeometryInfo && docInfo2 instanceof GeometryInfo) {
- document1 = getDocumentManager().getGeometry((GeometryInfo) docInfo1);
- document2 = getDocumentManager().getGeometry((GeometryInfo) docInfo2);
- } else {
- throw new IllegalArgumentException("The two documents are invalid or of different types.");
- }
- return compareDocuments(document1, document2, DiffConfiguration.COMPARE_DOCS_OTHER);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e.getMessage());
- }
- }
-
- public XmlTreeDiff compareWithSaved(VCDocument document) {
-
- VCDocument savedVersion = null;
- try {
- if (document == null) {
- throw new IllegalArgumentException("Invalid VC document: " + document);
- }
- // make the info and get saved version
- switch (document.getDocumentType()) {
- case BIOMODEL_DOC: {
- BioModel bioModel = (BioModel) document;
- savedVersion = getDocumentManager().getBioModel(bioModel.getVersion().getVersionKey());
- break;
- }
- case MATHMODEL_DOC: {
- MathModel mathModel = (MathModel) document;
- savedVersion = getDocumentManager().getMathModel(mathModel.getVersion().getVersionKey());
- break;
- }
- case GEOMETRY_DOC: {
- Geometry geometry = (Geometry) document;
- savedVersion = getDocumentManager().getGeometry(geometry.getKey());
- break;
- }
- }
- return compareDocuments(savedVersion, document, DiffConfiguration.COMPARE_DOCS_SAVED);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e.getMessage());
- }
- }
-
- public XmlTreeDiff compareApplications(BioModel bioModel, String appName1, String appName2) throws Exception {
-
- // clone BioModel as bioModel1 and remove all but appName1
- BioModel bioModel1 = (BioModel) BeanUtils.cloneSerializable(bioModel);
- bioModel1.refreshDependencies();
- SimulationContext[] allSimContexts1 = bioModel1.getSimulationContexts();
- for (SimulationContext sc : allSimContexts1) {
- if (!sc.getName().equals(appName1)) {
- bioModel1.removeSimulationContext(sc);
- }
- }
-
- // clone BioModel as bioModel2 and remove all but appName2
- BioModel bioModel2 = (BioModel) BeanUtils.cloneSerializable(bioModel);
- bioModel2.refreshDependencies();
- SimulationContext[] allSimContexts2 = bioModel2.getSimulationContexts();
- for (SimulationContext sc : allSimContexts2) {
- if (!sc.getName().equals(appName2)) {
- bioModel2.removeSimulationContext(sc);
- }
- }
-
- return compareDocuments(bioModel1, bioModel2, DiffConfiguration.COMPARE_DOCS_SAVED);
- }
-
- public void connectToServer(TopLevelWindowManager requester, ClientServerInfo clientServerInfo) throws Exception {
- getClientServerManager().connectNewServer(new VCellGuiInteractiveContext(requester), clientServerInfo);
- }
-
-
- public void logOut(final TopLevelWindowManager requester){
- JDialog dialog = new JDialog();
- dialog.setAlwaysOnTop(true);
- StringBuilder dialogMessage = new StringBuilder();
- dialogMessage.append("You are about to log out of the VCell client.\n\n");
- if (requester instanceof DocumentWindowManager documentWindowManager){
- if(!User.isGuest(documentWindowManager.getUser().getName())){
- dialogMessage.append("""
+ if (confirm != 0 && confirm != 1/* choice.equals(UserMessage.OPTION_CANCEL) */) {
+ // user canceled
+ return CloseOption.CANCEL_CLOSE;
+ }
+ if (confirm == 0/* choice.equals(UserMessage.OPTION_YES) */) {
+ return CloseOption.SAVE_AND_CLOSE;
+ }
+ }
+ // nothing changed, or user confirmed, close it
+ return CloseOption.CLOSE_IN_ANY_CASE;
+ }
+
+ public boolean isDifferentFromBlank(VCDocumentType documentType, VCDocument vcDocument) {
+ // Handle Bio/Math models different from Geometry since createDefaultDoc for
+ // Geometry
+ // will bring up the NewGeometryEditor which is unnecessary.
+ // figure out if we come from a blank new document; if so, replace it inside
+ // same window
+
+ if (documentType != vcDocument.getDocumentType()) {
+ // If the docType we are trying to open is not the same as the requesting
+ // windowmanager's docType
+ // we have to open the doc in a new window, hence return true;
+ return true;
+ }
+ VCDocument blank = null;
+ if (vcDocument.getDocumentType() != VCDocumentType.GEOMETRY_DOC) {
+ // BioModel/MathModel
+ blank = this.createDefaultDocument(vcDocument.getDocumentType());
+ try {
+ blank.setName(vcDocument.getName());
+ } catch (PropertyVetoException e) {
+ } // ignore. doesn't happen
+ return !blank.compareEqual(vcDocument);
+ } else {
+ // Geometry
+ blank = new Geometry(vcDocument.getName(), 1);
+ if (blank.compareEqual(vcDocument)) {
+ return false;
+ }
+
+ blank = new Geometry(vcDocument.getName(), 2);
+ if (blank.compareEqual(vcDocument)) {
+ return false;
+ }
+
+ blank = new Geometry(vcDocument.getName(), 3);
+ return !blank.compareEqual(vcDocument);
+ }
+ }
+
+ @Override
+ public ClientServerInfo getClientServerInfo() {
+ return this.getVcellClient().getClientServerManager().getClientServerInfo();
+ }
+
+ private boolean closeAllWindows(boolean duringExit) {
+ // create copy to avoid ConcurrentModification exception caused by closing
+ // window
+ ArrayList modificationSafeCopy = new ArrayList<>(this.getMdiManager().getWindowManagers());
+ for (TopLevelWindowManager windowManager : modificationSafeCopy) {
+ boolean closed = this.closeWindow(windowManager.getManagerID(), duringExit);
+ if (!closed) {
+ // user canceled, don't keep going...
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public boolean closeWindow(final java.lang.String windowID, final boolean exitIfLast) {
+ // called from DocumentWindow or from DatabaseWindow
+ final TopLevelWindowManager windowManager = this.getMdiManager().getWindowManager(windowID);
+ if (windowManager instanceof DocumentWindowManager) {
+ // we'll need to run some checks first
+ this.getMdiManager().showWindow(windowID);
+ this.getMdiManager().blockWindow(windowID);
+ CloseOption closeOption = this.checkBeforeClosing((DocumentWindowManager) windowManager);
+ if (closeOption.equals(CloseOption.CANCEL_CLOSE)) {
+ // user canceled
+ this.getMdiManager().unBlockWindow(windowID);
+ return false;
+ } else if (closeOption.equals(CloseOption.SAVE_AND_CLOSE)) {
+ AsynchClientTask closeTask = new AsynchClientTask("closing document",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ // if there is error saving the document, try to unblock the window
+ if (hashTable.get(swingthreads.TaskEventKeys.TASK_ABORTED_BY_ERROR.toString()) != null) {
+ ClientRequestManager.this.getMdiManager().unBlockWindow(windowID);
+ ClientRequestManager.this.getMdiManager().showWindow(windowID);
+ } else {
+ long openWindows = ClientRequestManager.this.getMdiManager().closeWindow(windowManager.getManagerID());
+ if (exitIfLast && (openWindows == 0)) {
+ ClientRequestManager.this.setBExiting(true);
+ ClientRequestManager.this.exitApplication();
+ }
+ }
+ }
+
+ @Override
+ public boolean skipIfCancel(UserCancelException exc) {
+ // if save as new edition, don't skip
+ return exc != UserCancelException.CANCEL_DELETE_OLD
+ && exc != UserCancelException.CANCEL_NEW_NAME;
+ }
+ };
+
+ if (((DocumentWindowManager) windowManager).getUser() == null
+ || User.isGuest(((DocumentWindowManager) windowManager).getUser().getName())) {
+ JDialog dialog = new JDialog();
+ dialog.setAlwaysOnTop(true);
+ JOptionPane.showMessageDialog(dialog, User.createGuestErrorMessage("saveDocument"), "Error...",
+ JOptionPane.ERROR_MESSAGE, null);
+ return false;
+ }
+
+ this.saveDocument((DocumentWindowManager) windowManager, true, closeTask);
+ return true;
+ } else {
+ long openWindows = this.getMdiManager().closeWindow(windowID);
+ if (exitIfLast && (openWindows == 0)) {
+ this.setBExiting(true);
+ this.exitApplication();
+ }
+ return true;
+ }
+ } else if (windowManager instanceof DatabaseWindowManager) {
+ // nothing to check here, just close it
+ long openWindows = this.getMdiManager().closeWindow(windowID);
+ if (exitIfLast && (openWindows == 0)) {
+ this.setBExiting(true);
+ this.exitApplication();
+ }
+ return true;
+ } else if (windowManager instanceof TestingFrameworkWindowManager) {
+ // nothing to check here, just close it
+ long openWindows = this.getMdiManager().closeWindow(windowID);
+ if (exitIfLast && (openWindows == 0)) {
+ this.setBExiting(true);
+ this.exitApplication();
+ }
+ return true;
+ } else if (windowManager instanceof BNGWindowManager) {
+ // nothing to check here, just close it
+ long openWindows = this.getMdiManager().closeWindow(windowID);
+ if (exitIfLast && (openWindows == 0)) {
+ this.setBExiting(true);
+ this.exitApplication();
+ }
+ return true;
+ } else if (windowManager instanceof FieldDataWindowManager) {
+ // nothing to check here, just close it
+ long openWindows = this.getMdiManager().closeWindow(windowID);
+ if (exitIfLast && (openWindows == 0)) {
+ this.setBExiting(true);
+ this.exitApplication();
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private XmlTreeDiff compareDocuments(final VCDocument doc1, final VCDocument doc2,
+ DiffConfiguration comparisonSetting) throws Exception {
+
+ VCellThreadChecker.checkCpuIntensiveInvocation();
+
+ if ((DiffConfiguration.COMPARE_DOCS_SAVED != comparisonSetting)
+ && (DiffConfiguration.COMPARE_DOCS_OTHER != comparisonSetting)) {
+ throw new RuntimeException("Unsupported comparison setting: " + comparisonSetting);
+ }
+ if (doc1.getDocumentType() != doc2.getDocumentType()) {
+ throw new RuntimeException("Only comparison of documents of the same type is currently supported");
+ }
+ String doc1XML = null;
+ String doc2XML = null;
+ switch (doc1.getDocumentType()) {
+ case BIOMODEL_DOC: {
+ doc1XML = XmlHelper.bioModelToXML((BioModel) doc1);
+ doc2XML = XmlHelper.bioModelToXML((BioModel) doc2);
+ break;
+ }
+ case MATHMODEL_DOC: {
+ doc1XML = XmlHelper.mathModelToXML((MathModel) doc1);
+ doc2XML = XmlHelper.mathModelToXML((MathModel) doc2);
+ break;
+ }
+ case GEOMETRY_DOC: {
+ doc1XML = XmlHelper.geometryToXML((Geometry) doc1);
+ doc2XML = XmlHelper.geometryToXML((Geometry) doc2);
+ break;
+ }
+ }
+ final XmlTreeDiff diffTree = XmlHelper.compareMerge(doc1XML, doc2XML, comparisonSetting, true);
+ return diffTree;
+ }
+
+ public XmlTreeDiff compareWithOther(final VCDocumentInfo docInfo1, final VCDocumentInfo docInfo2) {
+
+ VCDocument document1, document2;
+
+ try {
+ // get the VCDocument versions from documentManager
+ if (docInfo1 instanceof BioModelInfo && docInfo2 instanceof BioModelInfo) {
+ document1 = this.getDocumentManager().getBioModel((BioModelInfo) docInfo1);
+ document2 = this.getDocumentManager().getBioModel((BioModelInfo) docInfo2);
+ } else if (docInfo1 instanceof MathModelInfo && docInfo2 instanceof MathModelInfo) {
+ document1 = this.getDocumentManager().getMathModel((MathModelInfo) docInfo1);
+ document2 = this.getDocumentManager().getMathModel((MathModelInfo) docInfo2);
+ } else if (docInfo1 instanceof GeometryInfo && docInfo2 instanceof GeometryInfo) {
+ document1 = this.getDocumentManager().getGeometry((GeometryInfo) docInfo1);
+ document2 = this.getDocumentManager().getGeometry((GeometryInfo) docInfo2);
+ } else {
+ throw new IllegalArgumentException("The two documents are invalid or of different types.");
+ }
+ return this.compareDocuments(document1, document2, DiffConfiguration.COMPARE_DOCS_OTHER);
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ public XmlTreeDiff compareWithSaved(VCDocument document) {
+
+ VCDocument savedVersion = null;
+ try {
+ if (document == null) {
+ throw new IllegalArgumentException("Invalid VC document: " + document);
+ }
+ // make the info and get saved version
+ switch (document.getDocumentType()) {
+ case BIOMODEL_DOC: {
+ BioModel bioModel = (BioModel) document;
+ savedVersion = this.getDocumentManager().getBioModel(bioModel.getVersion().getVersionKey());
+ break;
+ }
+ case MATHMODEL_DOC: {
+ MathModel mathModel = (MathModel) document;
+ savedVersion = this.getDocumentManager().getMathModel(mathModel.getVersion().getVersionKey());
+ break;
+ }
+ case GEOMETRY_DOC: {
+ Geometry geometry = (Geometry) document;
+ savedVersion = this.getDocumentManager().getGeometry(geometry.getKey());
+ break;
+ }
+ }
+ return this.compareDocuments(savedVersion, document, DiffConfiguration.COMPARE_DOCS_SAVED);
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ public XmlTreeDiff compareApplications(BioModel bioModel, String appName1, String appName2) throws Exception {
+
+ // clone BioModel as bioModel1 and remove all but appName1
+ BioModel bioModel1 = (BioModel) BeanUtils.cloneSerializable(bioModel);
+ bioModel1.refreshDependencies();
+ SimulationContext[] allSimContexts1 = bioModel1.getSimulationContexts();
+ for (SimulationContext sc : allSimContexts1) {
+ if (!sc.getName().equals(appName1)) {
+ bioModel1.removeSimulationContext(sc);
+ }
+ }
+
+ // clone BioModel as bioModel2 and remove all but appName2
+ BioModel bioModel2 = (BioModel) BeanUtils.cloneSerializable(bioModel);
+ bioModel2.refreshDependencies();
+ SimulationContext[] allSimContexts2 = bioModel2.getSimulationContexts();
+ for (SimulationContext sc : allSimContexts2) {
+ if (!sc.getName().equals(appName2)) {
+ bioModel2.removeSimulationContext(sc);
+ }
+ }
+
+ return this.compareDocuments(bioModel1, bioModel2, DiffConfiguration.COMPARE_DOCS_SAVED);
+ }
+
+ public void connectToServer(TopLevelWindowManager requester, ClientServerInfo clientServerInfo) throws Exception {
+ this.getClientServerManager().connectNewServer(new VCellGuiInteractiveContext(requester), clientServerInfo);
+ }
+
+
+ public void logOut(final TopLevelWindowManager requester) {
+ JDialog dialog = new JDialog();
+ dialog.setAlwaysOnTop(true);
+ StringBuilder dialogMessage = new StringBuilder();
+ dialogMessage.append("You are about to log out of the VCell client.\n\n");
+ if (requester instanceof DocumentWindowManager documentWindowManager) {
+ if (!User.isGuest(documentWindowManager.getUser().getName())) {
+ dialogMessage.append("""
Because VCell uses a browser-based login,
you'll be redirected to a logout page to
complete the logout process there.
-
+
""");
- }
- }
- dialogMessage.append("Do you wish to continue?");
-
- int confirm = JOptionPane.showOptionDialog(dialog, dialogMessage.toString(),
- "Logout", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
- new String[] { "Continue", "Cancel" }, "Continue");
- if (confirm == JOptionPane.OK_OPTION) {
- closeAllWindows(false);
- getClientServerManager().cleanup(); //set VCell connection to null
- getClientServerManager().getAsynchMessageManager().stopPolling();
-
- Hashtable hash = new Hashtable();
-
- Auth0ConnectionUtils auth0ConnectionUtils = getClientServerManager().getAuth0ConnectionUtils();
- if (!getClientServerInfo().getUsername().equals(User.VCELL_GUEST_NAME)){
- auth0ConnectionUtils.logOut();
- }
- Auth0ConnectionUtils.setShowLoginPopUp(true);
-
- AsynchClientTask waitTask = new AsynchClientTask("wait for window closing",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- // wait until all windows are closed.
- long startTime = System.currentTimeMillis();
- while (true) {
- long numOpenWindows = getMdiManager().closeWindow(ClientMDIManager.DATABASE_WINDOW_ID);
- if (numOpenWindows == 0) {
- break;
- }
- // if can't save all the documents, don't connect as thus throw exception.
- if (System.currentTimeMillis() - startTime > 60000) {
- throw UserCancelException.CANCEL_GENERIC;
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- };
-
-
- AsynchClientTask[] newTasks = newDocument(requester,
- new VCDocument.DocumentCreationInfo(VCDocumentType.BIOMODEL_DOC, 0));
- AsynchClientTask task0 = new AsynchClientTask("preparing", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get("windowManager");
- if (windowManager != null) {
- Frame frameParent = JOptionPane.getFrameForComponent(windowManager.getComponent());
- ClientMDIManager.blockWindow(frameParent);
- frameParent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
- }
- }
- };
-
- AsynchClientTask task1 = ClientLogin.popupLogin();
- AsynchClientTask task2 = ClientLogin.loginWithAuth0(auth0ConnectionUtils);
- AsynchClientTask task3 = ClientLogin.connectToServer(auth0ConnectionUtils, getClientServerInfo());
-
- AsynchClientTask refresh = new AsynchClientTask("Refresh", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false,
- false) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- getMdiManager().refreshRecyclableWindows();
- DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get("windowManager");
- if (windowManager != null) {
- Frame frameParent = JOptionPane.getFrameForComponent(windowManager.getComponent());
- ClientMDIManager.unBlockWindow(frameParent);
- frameParent.setCursor(Cursor.getDefaultCursor());
- }
- }
- };
+ }
+ }
+ dialogMessage.append("Do you wish to continue?");
+
+ int confirm = JOptionPane.showOptionDialog(dialog, dialogMessage.toString(),
+ "Logout", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
+ new String[]{"Continue", "Cancel"}, "Continue");
+ if (confirm == JOptionPane.OK_OPTION) {
+ this.closeAllWindows(false);
+ this.getClientServerManager().cleanup(); //set VCell connection to null
+ this.getClientServerManager().getAsynchMessageManager().stopPolling();
+
+ Hashtable hash = new Hashtable();
+
+ Auth0ConnectionUtils auth0ConnectionUtils = this.getClientServerManager().getAuth0ConnectionUtils();
+ if (!this.getClientServerInfo().getUsername().equals(User.VCELL_GUEST_NAME)) {
+ auth0ConnectionUtils.logOut();
+ }
+ Auth0ConnectionUtils.setShowLoginPopUp(true);
+
+ AsynchClientTask waitTask = new AsynchClientTask("wait for window closing",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ // wait until all windows are closed.
+ long startTime = System.currentTimeMillis();
+ while (true) {
+ long numOpenWindows = ClientRequestManager.this.getMdiManager().closeWindow(ClientMDIManager.DATABASE_WINDOW_ID);
+ if (numOpenWindows == 0) {
+ break;
+ }
+ // if can't save all the documents, don't connect as thus throw exception.
+ if (System.currentTimeMillis() - startTime > 60000) {
+ throw UserCancelException.CANCEL_GENERIC;
+ }
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ };
+
+
+ AsynchClientTask[] newTasks = this.newDocument(requester,
+ new VCDocument.DocumentCreationInfo(VCDocumentType.BIOMODEL_DOC, 0));
+ AsynchClientTask task0 = new AsynchClientTask("preparing", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get("windowManager");
+ if (windowManager != null) {
+ Frame frameParent = JOptionPane.getFrameForComponent(windowManager.getComponent());
+ ClientMDIManager.blockWindow(frameParent);
+ frameParent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ }
+ }
+ };
+
+ AsynchClientTask task1 = ClientLogin.popupLogin();
+ AsynchClientTask task2 = ClientLogin.loginWithAuth0(auth0ConnectionUtils);
+ AsynchClientTask task3 = ClientLogin.connectToServer(auth0ConnectionUtils, this.getClientServerInfo());
+
+ AsynchClientTask refresh = new AsynchClientTask("Refresh", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false,
+ false) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ ClientRequestManager.this.getMdiManager().refreshRecyclableWindows();
+ DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get("windowManager");
+ if (windowManager != null) {
+ Frame frameParent = JOptionPane.getFrameForComponent(windowManager.getComponent());
+ ClientMDIManager.unBlockWindow(frameParent);
+ frameParent.setCursor(Cursor.getDefaultCursor());
+ }
+ }
+ };
ArrayList tasks = new ArrayList<>(Arrays.stream(newTasks).toList());
- tasks.add(0, waitTask);
- tasks.add(task0);
- tasks.add(task1);
- tasks.add(task2);
- tasks.add(task3);
- tasks.add(refresh);
-
- ClientTaskDispatcher.dispatch(null, hash, tasks.toArray(new AsynchClientTask[0]));
- }
- }
-
- VCDocument createDefaultDocument(VCDocumentType docType) {
- VCDocument defaultDocument = null;
- try {
- switch (docType) {
- case BIOMODEL_DOC: {
- // blank
- return createDefaultBioModelDocument(null);
- }
- case MATHMODEL_DOC: {
- return createDefaultMathModelDocument();
- }
- default: {
- throw new RuntimeException("default document can only be BioModel or MathModel");
- }
- }
- } catch (Exception e) {
- e.printStackTrace(System.out);
- }
- return defaultDocument;
- }
-
- private MathModel createMathModel(String name, Geometry geometry) {
- MathModel mathModel = new MathModel(null);
- MathDescription mathDesc = mathModel.getMathDescription();
- try {
- mathDesc.setGeometry(geometry);
- if (geometry.getDimension() == 0) {
- mathDesc.addSubDomain(
- new CompartmentSubDomain("Compartment", CompartmentSubDomain.NON_SPATIAL_PRIORITY));
- } else {
- try {
- if (geometry.getDimension() > 0
- && geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
- geometry.getGeometrySurfaceDescription().updateAll();
- }
- } catch (ImageException e) {
- e.printStackTrace(System.out);
- throw new RuntimeException("Geometric surface generation error: \n" + e.getMessage());
- } catch (GeometryException e) {
- e.printStackTrace(System.out);
- throw new RuntimeException("Geometric surface generation error: \n" + e.getMessage());
- }
-
- SubVolume subVolumes[] = geometry.getGeometrySpec().getSubVolumes();
- for (int i = 0; i < subVolumes.length; i++) {
- mathDesc.addSubDomain(new CompartmentSubDomain(subVolumes[i].getName(), subVolumes[i].getHandle()));
- }
- //
- // add only those MembraneSubDomains corresponding to surfaces that acutally
- // exist in geometry.
- //
- GeometricRegion regions[] = geometry.getGeometrySurfaceDescription().getGeometricRegions();
- for (int i = 0; i < regions.length; i++) {
- if (regions[i] instanceof SurfaceGeometricRegion) {
- SurfaceGeometricRegion surfaceRegion = (SurfaceGeometricRegion) regions[i];
- SubVolume subVolume1 = ((VolumeGeometricRegion) surfaceRegion.getAdjacentGeometricRegions()[0])
- .getSubVolume();
- SubVolume subVolume2 = ((VolumeGeometricRegion) surfaceRegion.getAdjacentGeometricRegions()[1])
- .getSubVolume();
- CompartmentSubDomain compartment1 = mathDesc.getCompartmentSubDomain(subVolume1.getName());
- CompartmentSubDomain compartment2 = mathDesc.getCompartmentSubDomain(subVolume2.getName());
- MembraneSubDomain membraneSubDomain = mathDesc.getMembraneSubDomain(compartment1, compartment2);
- if (membraneSubDomain == null) {
- SurfaceClass surfaceClass = geometry.getGeometrySurfaceDescription()
- .getSurfaceClass(subVolume1, subVolume2);
- membraneSubDomain = new MembraneSubDomain(compartment1, compartment2,
- surfaceClass.getName());
- mathDesc.addSubDomain(membraneSubDomain);
- }
- }
- }
- }
- mathDesc.isValid();
- mathModel.setName(name);
- } catch (Exception e) {
- e.printStackTrace(System.out);
- }
- return mathModel;
- }
-
- public void createMathModelFromApplication(final BioModelWindowManager requester, final String name,
- final SimulationContext simContext) {
- if (simContext == null) {
- PopupGenerator.showErrorDialog(requester,
- "Selected Application is null, cannot generate corresponding math model");
- return;
- }
-
- switch (simContext.getApplicationType()) {
- case NETWORK_STOCHASTIC:
- break;
- case RULE_BASED_STOCHASTIC:
- case NETWORK_DETERMINISTIC:
- }
-
- AsynchClientTask task1 = new AsynchClientTask("Creating MathModel from BioModel Application",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- MathModel newMathModel = new MathModel(null);
- // Get corresponding mathDesc to create new mathModel.
- MathDescription mathDesc = simContext.getMathDescription();
- MathDescription newMathDesc = null;
- newMathDesc = new MathDescription(name + "_" + (new java.util.Random()).nextInt());
- try {
- if (mathDesc.getGeometry().getDimension() > 0
- && mathDesc.getGeometry().getGeometrySurfaceDescription().getGeometricRegions() == null) {
- mathDesc.getGeometry().getGeometrySurfaceDescription().updateAll();
- }
-
- } catch (ImageException e) {
- e.printStackTrace(System.out);
- throw new RuntimeException("Geometric surface generation error:\n" + e.getMessage());
- } catch (GeometryException e) {
- e.printStackTrace(System.out);
- throw new RuntimeException("Geometric surface generation error:\n" + e.getMessage());
- }
- newMathDesc.setGeometry(mathDesc.getGeometry());
- newMathDesc.read_database(new CommentStringTokenizer(mathDesc.getVCML_database()));
- newMathDesc.isValid();
-
- newMathModel.setName(name);
- newMathModel.setMathDescription(newMathDesc);
- hashTable.put("newMathModel", newMathModel);
- }
- };
-
- AsynchClientTask task2 = new AsynchClientTask("Creating MathModel from BioModel Application",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- MathModel newMathModel = (MathModel) hashTable.get("newMathModel");
- DocumentWindowManager windowManager = createDocumentWindowManager(newMathModel);
- if (simContext.getBioModel().getVersion() != null) {
- ((MathModelWindowManager) windowManager).setCopyFromBioModelAppVersionableTypeVersion(
- new VersionableTypeVersion(VersionableType.BioModelMetaData,
- simContext.getBioModel().getVersion()));
- }
- DocumentWindow dw = getMdiManager().createNewDocumentWindow(windowManager);
- setFinalWindow(hashTable, dw);
- }
- };
- ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
- new AsynchClientTask[] { task1, task2 }, false);
- }
-
- public void createBioModelFromApplication(final BioModelWindowManager requester, final String name,
- final SimulationContext simContext) {
- if (simContext == null) {
- PopupGenerator.showErrorDialog(requester,
- "Selected Application is null, cannot generate corresponding bio model");
- return;
- }
- if (simContext.isRuleBased()) {
- createRuleBasedBioModelFromApplication(requester, name, simContext);
- return;
- }
- AsynchClientTask task1 = new AsynchClientTask("Creating BioModel from BioModel Application",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
-
- MathMapping transformedMathMapping = simContext.createNewMathMapping();
-
- BioModel newBioModel = new BioModel(null);
- SimulationContext transformedSimContext = transformedMathMapping
- .getTransformation().transformedSimContext;
- Model newModel = transformedSimContext.getModel();
- newBioModel.setModel(newModel);
-
- RbmModelContainer rbmmc = newModel.getRbmModelContainer();
- for (RbmObservable o : rbmmc.getObservableList()) {
- rbmmc.removeObservable(o);
- }
- for (ReactionRule r : rbmmc.getReactionRuleList()) {
- rbmmc.removeReactionRule(r);
- }
- for (ReactionStep rs : newModel.getReactionSteps()) {
- String oldName = rs.getName();
- if (oldName.startsWith("_reverse_")) {
- String newName = newModel.getReactionName("rev", oldName.substring("_reverse_".length()));
- rs.setName(newName);
- }
- }
-
- hashTable.put("newBioModel", newBioModel);
- }
- };
- AsynchClientTask task2 = new AsynchClientTask("Creating BioModel from BioModel Application",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- BioModel newBioModel = (BioModel) hashTable.get("newBioModel");
- DocumentWindowManager windowManager = createDocumentWindowManager(newBioModel);
+ tasks.add(0, waitTask);
+ tasks.add(task0);
+ tasks.add(task1);
+ tasks.add(task2);
+ tasks.add(task3);
+ tasks.add(refresh);
+
+ ClientTaskDispatcher.dispatch(null, hash, tasks.toArray(new AsynchClientTask[0]));
+ }
+ }
+
+ VCDocument createDefaultDocument(VCDocumentType docType) {
+ VCDocument defaultDocument = null;
+ try {
+ switch (docType) {
+ case BIOMODEL_DOC: {
+ // blank
+ return this.createDefaultBioModelDocument(null);
+ }
+ case MATHMODEL_DOC: {
+ return this.createDefaultMathModelDocument();
+ }
+ default: {
+ throw new RuntimeException("default document can only be BioModel or MathModel");
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace(System.out);
+ }
+ return defaultDocument;
+ }
+
+ private MathModel createMathModel(String name, Geometry geometry) {
+ MathModel mathModel = new MathModel(null);
+ MathDescription mathDesc = mathModel.getMathDescription();
+ try {
+ mathDesc.setGeometry(geometry);
+ if (geometry.getDimension() == 0) {
+ mathDesc.addSubDomain(
+ new CompartmentSubDomain("Compartment", CompartmentSubDomain.NON_SPATIAL_PRIORITY));
+ } else {
+ try {
+ if (geometry.getDimension() > 0
+ && geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
+ geometry.getGeometrySurfaceDescription().updateAll();
+ }
+ } catch (ImageException e) {
+ e.printStackTrace(System.out);
+ throw new RuntimeException("Geometric surface generation error: \n" + e.getMessage());
+ } catch (GeometryException e) {
+ e.printStackTrace(System.out);
+ throw new RuntimeException("Geometric surface generation error: \n" + e.getMessage());
+ }
+
+ SubVolume[] subVolumes = geometry.getGeometrySpec().getSubVolumes();
+ for (int i = 0; i < subVolumes.length; i++) {
+ mathDesc.addSubDomain(new CompartmentSubDomain(subVolumes[i].getName(), subVolumes[i].getHandle()));
+ }
+ //
+ // add only those MembraneSubDomains corresponding to surfaces that acutally
+ // exist in geometry.
+ //
+ GeometricRegion[] regions = geometry.getGeometrySurfaceDescription().getGeometricRegions();
+ for (int i = 0; i < regions.length; i++) {
+ if (regions[i] instanceof SurfaceGeometricRegion surfaceRegion) {
+ SubVolume subVolume1 = ((VolumeGeometricRegion) surfaceRegion.getAdjacentGeometricRegions()[0])
+ .getSubVolume();
+ SubVolume subVolume2 = ((VolumeGeometricRegion) surfaceRegion.getAdjacentGeometricRegions()[1])
+ .getSubVolume();
+ CompartmentSubDomain compartment1 = mathDesc.getCompartmentSubDomain(subVolume1.getName());
+ CompartmentSubDomain compartment2 = mathDesc.getCompartmentSubDomain(subVolume2.getName());
+ MembraneSubDomain membraneSubDomain = mathDesc.getMembraneSubDomain(compartment1, compartment2);
+ if (membraneSubDomain == null) {
+ SurfaceClass surfaceClass = geometry.getGeometrySurfaceDescription()
+ .getSurfaceClass(subVolume1, subVolume2);
+ membraneSubDomain = new MembraneSubDomain(compartment1, compartment2,
+ surfaceClass.getName());
+ mathDesc.addSubDomain(membraneSubDomain);
+ }
+ }
+ }
+ }
+ mathDesc.isValid();
+ mathModel.setName(name);
+ } catch (Exception e) {
+ e.printStackTrace(System.out);
+ }
+ return mathModel;
+ }
+
+ public void createMathModelFromApplication(final BioModelWindowManager requester, final String name,
+ final SimulationContext simContext) {
+ if (simContext == null) {
+ PopupGenerator.showErrorDialog(requester,
+ "Selected Application is null, cannot generate corresponding math model");
+ return;
+ }
+
+ switch (simContext.getApplicationType()) {
+ case NETWORK_STOCHASTIC:
+ break;
+ case RULE_BASED_STOCHASTIC:
+ case NETWORK_DETERMINISTIC:
+ }
+
+ AsynchClientTask task1 = new AsynchClientTask("Creating MathModel from BioModel Application",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ MathModel newMathModel = new MathModel(null);
+ // Get corresponding mathDesc to create new mathModel.
+ MathDescription mathDesc = simContext.getMathDescription();
+ MathDescription newMathDesc = null;
+ newMathDesc = new MathDescription(name + "_" + (new java.util.Random()).nextInt());
+ try {
+ if (mathDesc.getGeometry().getDimension() > 0
+ && mathDesc.getGeometry().getGeometrySurfaceDescription().getGeometricRegions() == null) {
+ mathDesc.getGeometry().getGeometrySurfaceDescription().updateAll();
+ }
+
+ } catch (ImageException e) {
+ e.printStackTrace(System.out);
+ throw new RuntimeException("Geometric surface generation error:\n" + e.getMessage());
+ } catch (GeometryException e) {
+ e.printStackTrace(System.out);
+ throw new RuntimeException("Geometric surface generation error:\n" + e.getMessage());
+ }
+ newMathDesc.setGeometry(mathDesc.getGeometry());
+ newMathDesc.read_database(new CommentStringTokenizer(mathDesc.getVCML_database()));
+ newMathDesc.isValid();
+
+ newMathModel.setName(name);
+ newMathModel.setMathDescription(newMathDesc);
+ hashTable.put("newMathModel", newMathModel);
+ }
+ };
+
+ AsynchClientTask task2 = new AsynchClientTask("Creating MathModel from BioModel Application",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ MathModel newMathModel = (MathModel) hashTable.get("newMathModel");
+ DocumentWindowManager windowManager = ClientRequestManager.this.createDocumentWindowManager(newMathModel);
+ if (simContext.getBioModel().getVersion() != null) {
+ ((MathModelWindowManager) windowManager).setCopyFromBioModelAppVersionableTypeVersion(
+ new VersionableTypeVersion(VersionableType.BioModelMetaData,
+ simContext.getBioModel().getVersion()));
+ }
+ DocumentWindow dw = ClientRequestManager.this.getMdiManager().createNewDocumentWindow(windowManager);
+ this.setFinalWindow(hashTable, dw);
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
+ new AsynchClientTask[]{task1, task2}, false);
+ }
+
+ public void createBioModelFromApplication(final BioModelWindowManager requester, final String name,
+ final SimulationContext simContext) {
+ if (simContext == null) {
+ PopupGenerator.showErrorDialog(requester,
+ "Selected Application is null, cannot generate corresponding bio model");
+ return;
+ }
+ if (simContext.isRuleBased()) {
+ this.createRuleBasedBioModelFromApplication(requester, name, simContext);
+ return;
+ }
+ AsynchClientTask task1 = new AsynchClientTask("Creating BioModel from BioModel Application",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+
+ MathMapping transformedMathMapping = simContext.createNewMathMapping();
+
+ BioModel newBioModel = new BioModel(null);
+ SimulationContext transformedSimContext = transformedMathMapping
+ .getTransformation().transformedSimContext;
+ Model newModel = transformedSimContext.getModel();
+ newBioModel.setModel(newModel);
+
+ RbmModelContainer rbmmc = newModel.getRbmModelContainer();
+ for (RbmObservable o : rbmmc.getObservableList()) {
+ rbmmc.removeObservable(o);
+ }
+ for (ReactionRule r : rbmmc.getReactionRuleList()) {
+ rbmmc.removeReactionRule(r);
+ }
+ for (ReactionStep rs : newModel.getReactionSteps()) {
+ String oldName = rs.getName();
+ if (oldName.startsWith("_reverse_")) {
+ String newName = newModel.getReactionName("rev", oldName.substring("_reverse_".length()));
+ rs.setName(newName);
+ }
+ }
+
+ hashTable.put("newBioModel", newBioModel);
+ }
+ };
+ AsynchClientTask task2 = new AsynchClientTask("Creating BioModel from BioModel Application",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ BioModel newBioModel = (BioModel) hashTable.get("newBioModel");
+ DocumentWindowManager windowManager = ClientRequestManager.this.createDocumentWindowManager(newBioModel);
// if(simContext.getBioModel().getVersion() != null){
// ((BioModelWindowManager)windowManager). setCopyFromBioModelAppVersionableTypeVersion(
// new VersionableTypeVersion(VersionableType.BioModelMetaData, simContext.getBioModel().getVersion()));
// }
- getMdiManager().createNewDocumentWindow(windowManager);
- }
- };
- ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
- new AsynchClientTask[] { task1, task2 }, false);
- }
-
- public void createRuleBasedBioModelFromApplication(final BioModelWindowManager requester, final String name,
- final SimulationContext simContext) {
- if (simContext == null) {
- PopupGenerator.showErrorDialog(requester,
- "Selected Application is null, cannot generate corresponding bio model");
- return;
- }
- AsynchClientTask task1 = new AsynchClientTask("Creating BioModel from BioModel Application",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
-
- MathMapping transformedMathMapping = simContext.createNewMathMapping();
-
- BioModel newBioModel = new BioModel(null);
- SimulationContext transformedSimContext = transformedMathMapping
- .getTransformation().transformedSimContext;
- Model model = transformedSimContext.getModel();
-
- newBioModel.setModel(model);
-
- hashTable.put("newBioModel", newBioModel);
- }
- };
- AsynchClientTask task2 = new AsynchClientTask("Creating BioModel from BioModel Application",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- BioModel newBioModel = (BioModel) hashTable.get("newBioModel");
- DocumentWindowManager windowManager = createDocumentWindowManager(newBioModel);
- getMdiManager().createNewDocumentWindow(windowManager);
- }
- };
- ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
- new AsynchClientTask[] { task1, task2 }, false);
- }
-
-//public void createBioModelFromApplication(final BioModelWindowManager requester, final String name, final SimulationContext simContext) {
+ ClientRequestManager.this.getMdiManager().createNewDocumentWindow(windowManager);
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
+ new AsynchClientTask[]{task1, task2}, false);
+ }
+
+ public void createRuleBasedBioModelFromApplication(final BioModelWindowManager requester, final String name,
+ final SimulationContext simContext) {
+ if (simContext == null) {
+ PopupGenerator.showErrorDialog(requester,
+ "Selected Application is null, cannot generate corresponding bio model");
+ return;
+ }
+ AsynchClientTask task1 = new AsynchClientTask("Creating BioModel from BioModel Application",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+
+ MathMapping transformedMathMapping = simContext.createNewMathMapping();
+
+ BioModel newBioModel = new BioModel(null);
+ SimulationContext transformedSimContext = transformedMathMapping
+ .getTransformation().transformedSimContext;
+ Model model = transformedSimContext.getModel();
+
+ newBioModel.setModel(model);
+
+ hashTable.put("newBioModel", newBioModel);
+ }
+ };
+ AsynchClientTask task2 = new AsynchClientTask("Creating BioModel from BioModel Application",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ BioModel newBioModel = (BioModel) hashTable.get("newBioModel");
+ DocumentWindowManager windowManager = ClientRequestManager.this.createDocumentWindowManager(newBioModel);
+ ClientRequestManager.this.getMdiManager().createNewDocumentWindow(windowManager);
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
+ new AsynchClientTask[]{task1, task2}, false);
+ }
+
+ //public void createBioModelFromApplication(final BioModelWindowManager requester, final String name, final SimulationContext simContext) {
// if (simContext == null) {
// PopupGenerator.showErrorDialog(requester, "Selected Application is null, cannot generate corresponding bio model");
// return;
@@ -1035,64 +1044,64 @@ public void run(Hashtable hashTable) throws Exception {
// };
// ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(), new AsynchClientTask[]{task1, task2}, false);
//}
-private BioModel createDefaultBioModelDocument(BngUnitSystem bngUnitSystem) throws Exception {
- BioModel bioModel = new BioModel(null);
- bioModel.setName("BioModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1));
-
- Model model;
- if (bngUnitSystem == null) {
- model = new Model("model");
- } else {
- model = new Model("model", bngUnitSystem.createModelUnitSystem());
- }
- bioModel.setModel(model);
-
- model.createFeature();
- return bioModel;
-}
-
- private MathModel createDefaultMathModelDocument() throws Exception {
- Geometry geometry = new Geometry("Untitled", 0);
- MathModel mathModel = createMathModel("Untitled", geometry);
- mathModel.setName("MathModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1));
- return mathModel;
- }
-
- public VCDocumentInfo selectDocumentFromType(VCDocumentType documentType, TopLevelWindowManager requester)
- throws Exception, UserCancelException {
- return getMdiManager().getDatabaseWindowManager().selectDocument(documentType, requester);
- }
-
- public Geometry getGeometryFromDocumentSelection(Component parentComponent, VCDocumentInfo vcDocumentInfo,
- boolean bClearVersion) throws Exception, UserCancelException {
- Geometry geom = null;
- if (vcDocumentInfo.getVersionType()
- .equals(VersionableType.BioModelMetaData)/* documentType == VCDocument.BIOMODEL_DOC */) {
- BioModelInfo bioModelInfo = getDocumentManager()
- .getBioModelInfo(vcDocumentInfo.getVersion().getVersionKey());
- BioModelChildSummary bioModelChildSummary = bioModelInfo.getBioModelChildSummary();
- if (bioModelChildSummary != null && bioModelChildSummary.getSimulationContextNames() != null) {
- Vector spatialV = new Vector();
- for (int i = 0; i < bioModelChildSummary.getSimulationContextNames().length; i++) {
- if (bioModelChildSummary.getGeometryDimensions()[i] > 0) {
- spatialV.add(i);
- }
- }
- if (spatialV.size() > 0) {
- String[] columnNames = new String[] { "Application", "Geometry", "Dimension" };
- String[][] rowData = new String[spatialV.size()][3];
- for (int i = 0; i < spatialV.size(); i++) {
- rowData[i][0] = bioModelChildSummary.getSimulationContextNames()[spatialV.elementAt(i)];
- rowData[i][1] = bioModelChildSummary.getGeometryNames()[spatialV.elementAt(i)];
- rowData[i][2] = bioModelChildSummary.getGeometryDimensions()[spatialV.elementAt(i)] + "";
- }
- int[] selection = DialogUtils.showComponentOKCancelTableList(
- JOptionPane.getFrameForComponent(parentComponent), "Select Geometry", columnNames, rowData,
- ListSelectionModel.SINGLE_SELECTION);
- ModelGeometryOPResults modelGeometryOPResults = (ModelGeometryOPResults) getDocumentManager()
- .getSessionManager().getUserMetaDbServer().doTestSuiteOP(
- new ModelGeometryOP((BioModelInfo) vcDocumentInfo, rowData[selection[0]][0]));
- geom = getDocumentManager().getGeometry(modelGeometryOPResults.getGeometryKey());
+ private BioModel createDefaultBioModelDocument(BngUnitSystem bngUnitSystem) throws Exception {
+ BioModel bioModel = new BioModel(null);
+ bioModel.setName("BioModel" + (this.getMdiManager().getNumCreatedDocumentWindows() + 1));
+
+ Model model;
+ if (bngUnitSystem == null) {
+ model = new Model("model");
+ } else {
+ model = new Model("model", bngUnitSystem.createModelUnitSystem());
+ }
+ bioModel.setModel(model);
+
+ model.createFeature();
+ return bioModel;
+ }
+
+ private MathModel createDefaultMathModelDocument() throws Exception {
+ Geometry geometry = new Geometry("Untitled", 0);
+ MathModel mathModel = this.createMathModel("Untitled", geometry);
+ mathModel.setName("MathModel" + (this.getMdiManager().getNumCreatedDocumentWindows() + 1));
+ return mathModel;
+ }
+
+ public VCDocumentInfo selectDocumentFromType(VCDocumentType documentType, TopLevelWindowManager requester)
+ throws Exception {
+ return this.getMdiManager().getDatabaseWindowManager().selectDocument(documentType, requester);
+ }
+
+ public Geometry getGeometryFromDocumentSelection(Component parentComponent, VCDocumentInfo vcDocumentInfo,
+ boolean bClearVersion) throws Exception {
+ Geometry geom = null;
+ if (vcDocumentInfo.getVersionType()
+ .equals(VersionableType.BioModelMetaData)/* documentType == VCDocument.BIOMODEL_DOC */) {
+ BioModelInfo bioModelInfo = this.getDocumentManager()
+ .getBioModelInfo(vcDocumentInfo.getVersion().getVersionKey());
+ BioModelChildSummary bioModelChildSummary = bioModelInfo.getBioModelChildSummary();
+ if (bioModelChildSummary != null && bioModelChildSummary.getSimulationContextNames() != null) {
+ Vector spatialV = new Vector();
+ for (int i = 0; i < bioModelChildSummary.getSimulationContextNames().length; i++) {
+ if (bioModelChildSummary.getGeometryDimensions()[i] > 0) {
+ spatialV.add(i);
+ }
+ }
+ if (spatialV.size() > 0) {
+ String[] columnNames = new String[]{"Application", "Geometry", "Dimension"};
+ String[][] rowData = new String[spatialV.size()][3];
+ for (int i = 0; i < spatialV.size(); i++) {
+ rowData[i][0] = bioModelChildSummary.getSimulationContextNames()[spatialV.elementAt(i)];
+ rowData[i][1] = bioModelChildSummary.getGeometryNames()[spatialV.elementAt(i)];
+ rowData[i][2] = bioModelChildSummary.getGeometryDimensions()[spatialV.elementAt(i)] + "";
+ }
+ int[] selection = DialogUtils.showComponentOKCancelTableList(
+ JOptionPane.getFrameForComponent(parentComponent), "Select Geometry", columnNames, rowData,
+ ListSelectionModel.SINGLE_SELECTION);
+ ModelGeometryOPResults modelGeometryOPResults = (ModelGeometryOPResults) this.getDocumentManager()
+ .getSessionManager().getUserMetaDbServer().doTestSuiteOP(
+ new ModelGeometryOP((BioModelInfo) vcDocumentInfo, rowData[selection[0]][0]));
+ geom = this.getDocumentManager().getGeometry(modelGeometryOPResults.getGeometryKey());
// BioModel bioModel = getDocumentManager().getBioModel((BioModelInfo)vcDocumentInfo);
// for (int i = 0; i < bioModel.getSimulationContexts().length; i++) {
// if(bioModel.getSimulationContexts()[i].getName().equals(rowData[selection[0]][0])){
@@ -1100,679 +1109,679 @@ public Geometry getGeometryFromDocumentSelection(Component parentComponent, VCDo
// break;
// }
// }
- } else {
- throw new Exception(
- "BioModel '" + bioModelInfo.getVersion().getName() + "' contains no spatial geometries.");
- }
- } else {
- throw new Exception(
- "BioModel '" + bioModelInfo.getVersion().getName() + "' contains no spatial geometries.");
- }
- } else if (vcDocumentInfo.getVersionType()
- .equals(VersionableType.MathModelMetaData)/* documentType == VCDocument.MATHMODEL_DOC */) {
- MathModelInfo mathModelInfo = getDocumentManager()
- .getMathModelInfo(vcDocumentInfo.getVersion().getVersionKey());
- MathModelChildSummary mathModelChildSummary = mathModelInfo.getMathModelChildSummary();
- if (mathModelChildSummary != null) {
- if (mathModelChildSummary.getGeometryDimension() > 0) {
- ModelGeometryOPResults modelGeometryOPResults = (ModelGeometryOPResults) getDocumentManager()
- .getSessionManager().getUserMetaDbServer()
- .doTestSuiteOP(new ModelGeometryOP((MathModelInfo) vcDocumentInfo));
- geom = getDocumentManager().getGeometry(modelGeometryOPResults.getGeometryKey());
+ } else {
+ throw new Exception(
+ "BioModel '" + bioModelInfo.getVersion().getName() + "' contains no spatial geometries.");
+ }
+ } else {
+ throw new Exception(
+ "BioModel '" + bioModelInfo.getVersion().getName() + "' contains no spatial geometries.");
+ }
+ } else if (vcDocumentInfo.getVersionType()
+ .equals(VersionableType.MathModelMetaData)/* documentType == VCDocument.MATHMODEL_DOC */) {
+ MathModelInfo mathModelInfo = this.getDocumentManager()
+ .getMathModelInfo(vcDocumentInfo.getVersion().getVersionKey());
+ MathModelChildSummary mathModelChildSummary = mathModelInfo.getMathModelChildSummary();
+ if (mathModelChildSummary != null) {
+ if (mathModelChildSummary.getGeometryDimension() > 0) {
+ ModelGeometryOPResults modelGeometryOPResults = (ModelGeometryOPResults) this.getDocumentManager()
+ .getSessionManager().getUserMetaDbServer()
+ .doTestSuiteOP(new ModelGeometryOP((MathModelInfo) vcDocumentInfo));
+ geom = this.getDocumentManager().getGeometry(modelGeometryOPResults.getGeometryKey());
// MathModel mathModel = getDocumentManager().getMathModel(mathModelInfo);
// geom = mathModel.getMathDescription().getGeometry();
- } else {
- throw new Exception(
- "MathModel '" + mathModelInfo.getVersion().getName() + "' contains no spatial geometry.");
- }
- } else {
- throw new Exception(
- "MathModel '" + mathModelInfo.getVersion().getName() + "' contains no spatial geometry.");
- }
- } else if (vcDocumentInfo.getVersionType().equals(VersionableType.Geometry)) {
- geom = getDocumentManager().getGeometry((GeometryInfo) vcDocumentInfo);
- if (geom.getDimension() == 0) {
- throw new Exception("Error, Only spatial geometries allowed (dimension > 0).");
- }
- } else {
- throw new IllegalArgumentException("Error selecting geometry from document type "
- + vcDocumentInfo.getVersionType() + ". Must be BioModel,MathModel or Geometry.");
- }
- if (geom == null) {
- throw new Exception("error selecting geometry");
- }
- if (bClearVersion) {
- geom.clearVersion();
- }
- return geom;
- }
-
- public static final String GUI_PARENT = "guiParent";
-
- public static boolean isImportGeometryType(DocumentCreationInfo documentCreationInfo) {
- return documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA
- || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE
- || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH
- || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC
- || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE
+ } else {
+ throw new Exception(
+ "MathModel '" + mathModelInfo.getVersion().getName() + "' contains no spatial geometry.");
+ }
+ } else {
+ throw new Exception(
+ "MathModel '" + mathModelInfo.getVersion().getName() + "' contains no spatial geometry.");
+ }
+ } else if (vcDocumentInfo.getVersionType().equals(VersionableType.Geometry)) {
+ geom = this.getDocumentManager().getGeometry((GeometryInfo) vcDocumentInfo);
+ if (geom.getDimension() == 0) {
+ throw new Exception("Error, Only spatial geometries allowed (dimension > 0).");
+ }
+ } else {
+ throw new IllegalArgumentException("Error selecting geometry from document type "
+ + vcDocumentInfo.getVersionType() + ". Must be BioModel,MathModel or Geometry.");
+ }
+ if (geom == null) {
+ throw new Exception("error selecting geometry");
+ }
+ if (bClearVersion) {
+ geom.clearVersion();
+ }
+ return geom;
+ }
+
+ public static final String GUI_PARENT = "guiParent";
+
+ public static boolean isImportGeometryType(DocumentCreationInfo documentCreationInfo) {
+ return documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA
+ || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE
+ || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH
+ || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC
+ || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE
// || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ ||
// documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER
- ;
- }
-
- private static void throwImportWholeDirectoryException(File invalidFile, String extraInfo) throws Exception {
- throw new Exception("Import whole directory failed: directory '" + invalidFile.getAbsolutePath() + "' "
- + "contains invalid file. Import from whole directory can contain only files for "
- + "a single z-series, each file must be 2D, single time. "
- + "All files must be the same size and have the same number color channels."
- + (extraInfo == null ? "" : "\n" + extraInfo));
-
- }
-
- private static FieldDataFileOperationSpec createFDOSFromVCImage(VCImage dbImage) throws ImageException {
- int[] temp = new int[256];
- short[] templateShorts = new short[dbImage.getNumXYZ()];
- for (int i = 0; i < dbImage.getPixels().length; i++) {
- templateShorts[i] = (short) (0x00FF & dbImage.getPixels()[i]);
- temp[templateShorts[i]]++;
- }
- for (int j = 0; j < dbImage.getPixelClasses().length; j++) {
- short tempshort = (short) (0x00FF & dbImage.getPixelClasses()[j].getPixel());
- }
- FieldDataFileOperationSpec fdfos = null;
- fdfos = new FieldDataFileOperationSpec();
- fdfos.origin = new Origin(0, 0, 0);
- fdfos.extent = dbImage.getExtent();
- fdfos.isize = new ISize(dbImage.getNumX(), dbImage.getNumY(), dbImage.getNumZ());
- fdfos.shortSpecData = new short[][][] { { templateShorts } };
- return fdfos;
- }
-
- public static SurfaceCollection createSurfaceCollectionFromSurfaceFile(File surfaceFile) throws Exception {
- SurfaceCollection surfaceCollection = null;
- if (ExtensionFilter.isMatchingExtension(surfaceFile, ".stl")) {
- surfaceCollection = StlReader.readStl(surfaceFile);
- } else if (ExtensionFilter.isMatchingExtension(surfaceFile, ".mesh")) {// NOT VCell mesh, salk Hughes Hoppe mesh
- // convert to .stl and read
- BufferedWriter stlBufferedWriter = null;
- File tempstlFile = File.createTempFile("salk", ".stl");
- try {
- try (BufferedReader salkBufferedReader = new BufferedReader(new FileReader(surfaceFile))) {
- String line;
- ArrayList vertList = new ArrayList();
- // read vertices
- while ((line = salkBufferedReader.readLine()) != null) {
- StringTokenizer st = new StringTokenizer(line, " ");
- String firstToken = st.nextToken();
- int vertIndex = Integer.parseInt(st.nextToken());
- if (firstToken.equals("Vertex")) {
- vertList.add(new double[] { Double.parseDouble(st.nextToken()),
- Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()) });
- if (vertList.size() != vertIndex) {// numbering starts at 1
- throw new Exception("Index not match position in list");
- }
- } else if (firstToken.equals("Face")) {
- break;// read all vertices
- } else {
- return null;
- }
- }
- stlBufferedWriter = new BufferedWriter(new FileWriter(tempstlFile));
- stlBufferedWriter.write("solid VCell salk convert\n");
- // read faces
- do {
- stlBufferedWriter.write("facet normal 0 0 0\n");
- stlBufferedWriter.write("outer loop\n");
- StringTokenizer st = new StringTokenizer(line, " ");
- String firstToken = st.nextToken();
- Integer.parseInt(st.nextToken());// ignore index token
- if (firstToken.equals("Face")) {
- for (int i = 0; i < 3; i++) {
- int vertListIndex = Integer.parseInt(st.nextToken()) - 1;
- double[] vertCoordinatges = vertList.get(vertListIndex);
- stlBufferedWriter.write("vertex " + vertCoordinatges[0] + " " + vertCoordinatges[1]
- + " " + vertCoordinatges[2] + "\n");// indexes start at 1, not 0
- }
- } else {
- throw new Exception("Expecting token 'Face' but got " + firstToken);
- }
- stlBufferedWriter.write("endloop\n");
- stlBufferedWriter.write("endfacet\n");
- } while ((line = salkBufferedReader.readLine()) != null);
- stlBufferedWriter.write("endsolid VCell salk convert\n");
-
- stlBufferedWriter.close();
- surfaceCollection = StlReader.readStl(tempstlFile);
- }
- } catch (Exception e) {
- // we couldn't read this for some reason
- e.printStackTrace();
- } finally {
- if (stlBufferedWriter != null) {
- try {
- stlBufferedWriter.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- if (tempstlFile != null) {
- tempstlFile.delete();
- }
- }
- }
- return surfaceCollection;
- }
-
- public static FieldDataFileOperationSpec createFDOSFromSurfaceFile(File surfaceFile) throws Exception {
- SurfaceCollection surfaceCollection = createSurfaceCollectionFromSurfaceFile(surfaceFile);
- if (surfaceCollection != null) {
- Geometry geometry = RayCaster.createGeometryFromSTL(new GeometryThumbnailImageFactoryAWT(),
- surfaceCollection, 1000000);
- FieldDataFileOperationSpec fdfos = new FieldDataFileOperationSpec();
- fdfos.origin = geometry.getOrigin();
- fdfos.extent = geometry.getExtent();
- VCImage image = geometry.getGeometrySpec().getImage();
- if (image.getNumPixelClasses() == 1) {
- throw new Exception("STL import failed during processing, pixelclass count=1");
- }
- fdfos.isize = new ISize(image.getNumX(), image.getNumY(), image.getNumZ());
- byte[] pixels = image.getPixels();
- short[] dataToSegment = new short[image.getNumXYZ()];
- for (int i = 0; i < pixels.length; i++) {
- dataToSegment[i] = pixels[i];
- }
- fdfos.shortSpecData = new short[][][] { { dataToSegment } };
- return fdfos;
- }
- return null;
- }
-
- public static final String GEOM_FROM_WORKSPACE = "GEOM_FROM_WORKSPACE";
- public static final String VCPIXELCLASSES = "VCPIXELCLASSES";
-
- private enum NRRDTYPE {
- DOUBLE, FLOAT, UNSIGNEDCHAR
- };
-
- private enum NRRDENCODING {
- RAW, GZIP
- };
-
- public static final String IMPORT_SOURCE_NAME = "IMPORT_SOURCE_NAME";
- private static final String DIR_FILES = "DIR_FILES";
- public static final String ORIG_IMAGE_SIZE_INFO = "ORIG_IMAGE_SIZE_INFO";
- public static final String NEW_IMAGE_SIZE_INFO = "NEW_IMAGE_SIZE_INFO";
- private static final String INITIAL_ANNOTATION = "INITIAL_ANNOTATION";
- private static final String FD_MESH = "FD_MESH";
- private static final String FD_MESHISIZE = "FD_MESHISIZE";
- public static final String FDFOS = "FDFOS";
- private static final String IMAGE_FILE = "IMAGE_FILE";
-
- public static AsynchClientTask getParseImageTask(final Component requesterComp,final VCDocument.DocumentCreationInfo documentCreationInfo,final MDIManager mdiManager) {
- AsynchClientTask parseImageTask = new AsynchClientTask("read and parse image file",AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(final Hashtable hashTable) throws Exception {
-
- final Component guiParent = (Component) hashTable.get(ClientRequestManager.GUI_PARENT);
- try {
- FieldDataFileOperationSpec fdfos = null;
- // if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ){
- // hashTable.put("imageFile",ImageJHelper.vcellWantImage(getClientTaskStatusSupport(),"Image for new VCell geometry"));
- // }
- // if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER){
- // hashTable.put("imageFile",ImageJHelper.vcellWantSurface(getClientTaskStatusSupport(),"Image for new VCell geometry"));
- // }
- if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE
- // || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ ||
- // documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER
- ) {
-
- File imageFile = (File) hashTable.get(IMAGE_FILE);
- if (imageFile == null) {
- throw new Exception("No file selected");
- }
- if (ExtensionFilter.isMatchingExtension(imageFile, ".nrrd")) {
-
- DataInputStream dis = null;
- try {
- dis = new DataInputStream(new BufferedInputStream(new FileInputStream(imageFile)));
- int xsize = 1;
- int ysize = 1;
- int zsize = 1;
- double xspace = 1.0;
- double yspace = 1.0;
- double zspace = 1.0;
- NRRDTYPE type = null;
- NRRDENCODING encoding = null;
- int dimension = -1;
- // read header lines
- while (true) {
- @SuppressWarnings("deprecation")
- String line = dis.readLine();
- if (line == null || line.length() == 0) {
- break;
- }
- StringTokenizer stringTokenizer = new StringTokenizer(line, ": ");
- String headerParam = stringTokenizer.nextToken();
- // System.out.println(headerParam);
- if (headerParam.equals("sizes")) {
- if (dimension != -1) {
- xsize = Integer.parseInt(stringTokenizer.nextToken());
- if (dimension >= 2) {
- ysize = Integer.parseInt(stringTokenizer.nextToken());
- }
- if (dimension >= 3) {
- zsize = Integer.parseInt(stringTokenizer.nextToken());
- }
- for (int i = 4; i < dimension; i++) {
- if (Integer.parseInt(stringTokenizer.nextToken()) != 1) {
- throw new Exception("Dimensions > 3 not supported");
- }
- }
- } else {
- throw new Exception("dimension expected to be set before reading sizes");
- }
- } else if (headerParam.equals("spacings")) {
- if (dimension != -1) {
- xspace = Double.parseDouble(stringTokenizer.nextToken());
- if (dimension >= 2) {
- yspace = Double.parseDouble(stringTokenizer.nextToken());
- }
- if (dimension >= 3) {
- zspace = Double.parseDouble(stringTokenizer.nextToken());
- }
- // ignore other dimension spacings
- } else {
- throw new Exception("dimension expected to be set before reading spacings");
- }
- } else if (headerParam.equals("type")) {
- String nextToken = stringTokenizer.nextToken();
- if (nextToken.equalsIgnoreCase("double")) {
- type = NRRDTYPE.DOUBLE;
- } else if (nextToken.equalsIgnoreCase("float")) {
- type = NRRDTYPE.FLOAT;
- } else if (nextToken.equalsIgnoreCase("unsigned")) {
- nextToken = stringTokenizer.nextToken();
- if (nextToken.equalsIgnoreCase("char")) {
- type = NRRDTYPE.UNSIGNEDCHAR;
- } else {
- throw new Exception("Unknown nrrd data type=" + nextToken);
- }
- } else {
- throw new Exception("Unknown nrrd data type=" + nextToken);
- }
- } else if (headerParam.equals("dimension")) {
- dimension = Integer.parseInt(stringTokenizer.nextToken());
- if (dimension < 1) {
- throw new Exception("unexpected dimension=" + dimension);
- }
- } else if (headerParam.equals("encoding")) {
- encoding = NRRDENCODING.valueOf(stringTokenizer.nextToken().toUpperCase());
- }
- }
- BufferedInputStream bis = null;
- if (encoding == NRRDENCODING.GZIP) {
- dis.close();
- bis = new BufferedInputStream(new FileInputStream(imageFile));
- boolean bnewLine = false;
- while (true) {
- int currentChar = bis.read();
- if (currentChar == '\n') {
- if (bnewLine) {
- break;// 2 newlines end header
- }
- bnewLine = true;
- } else {
- bnewLine = false;
- }
- }
- GZIPInputStream gzipInputStream = new GZIPInputStream(bis);
- dis = new DataInputStream(gzipInputStream);
- }
- double[] data = new double[xsize * ysize * zsize];
- double minValue = Double.POSITIVE_INFINITY;
- double maxValue = Double.NEGATIVE_INFINITY;
- for (int i = 0; i < data.length; i++) {
- if (i % 262144 == 0) {
- if (getClientTaskStatusSupport() != null) {
- getClientTaskStatusSupport().setMessage("Reading " + encoding + " " + type
- + " NRRD data " + (((long) i * (long) 100) / (long) data.length)
- + " % done.");
- }
- }
- if (type == NRRDTYPE.DOUBLE) {
- data[i] = dis.readDouble();
- } else if (type == NRRDTYPE.FLOAT) {
- data[i] = dis.readFloat();
- } else if (type == NRRDTYPE.UNSIGNEDCHAR) {
- data[i] = dis.readUnsignedByte();
- } else {
- throw new Exception("Unexpected data type=" + type.toString());
- }
-
- minValue = Math.min(minValue, data[i]);
- maxValue = Math.max(maxValue, data[i]);
- }
- dis.close();
- if (getClientTaskStatusSupport() != null) {
- getClientTaskStatusSupport()
- .setMessage("Scaling " + encoding + " " + type + " NRRD data.");
- }
-
- short[] dataToSegment = new short[data.length];
- double scaleShort = Math.pow(2, Short.SIZE) - 1;
- for (int i = 0; i < data.length; i++) {
- dataToSegment[i] |= (int) ((data[i] - minValue) / (maxValue - minValue)
- * scaleShort);
- }
- fdfos = new FieldDataFileOperationSpec();
- fdfos.origin = new Origin(0, 0, 0);
- fdfos.extent = new Extent((xsize == 1 ? .5 : (xsize) * xspace),
- (ysize == 1 ? .5 : (ysize) * yspace), (zsize == 1 ? .5 : (zsize) * zspace));
- fdfos.isize = new ISize(xsize, ysize, zsize);
- fdfos.shortSpecData = new short[][][] { { dataToSegment } };
- } finally {
- if (dis != null) {
- try {
- dis.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- } else if ((fdfos = createFDOSFromSurfaceFile(imageFile)) != null) {// try surface file formats
- // work already done at this point
- } else {
- File[] dirFiles = null;
- ImageSizeInfo origImageSizeInfo = null;
- ImageDatasetReaderService imageDatasetReaderServiceInstance = ImageDatasetReaderService
- .getInstance();
- ImageDatasetReader imageDatasetReader = imageDatasetReaderServiceInstance
- .getImageDatasetReader();
- if (imageFile.isDirectory()) {
- dirFiles = imageFile.listFiles(new java.io.FileFilter() {
- public boolean accept(File pathname) {
- return pathname.isFile() && !pathname.isHidden();// exclude windows Thumbs.db
- }
- });
- if (dirFiles.length == 0) {
- throw new Exception("No valid files in selected directory");
- }
- String fileExt0 = null;
- for (int i = 0; i < dirFiles.length; i++) {
- int lastDot = dirFiles[i].getName().lastIndexOf('.');
- String fileExt = (lastDot != -1 ? dirFiles[i].getName().substring(lastDot) : null);
- if (dirFiles[i].isDirectory()) {
- fileExt = "dir";
- }
- if (i == 0) {
- fileExt0 = fileExt;
- } else if (!Compare.isEqualOrNull(fileExt, fileExt0)) {
- String result = DialogUtils.showWarningDialog(requesterComp,
- "Files in '" + imageFile.getAbsolutePath()
- + "' have different name extensions, continue?",
- new String[] { "OK", "Cancel" }, "Cancel");
- if (!"OK".equals(result)) {
- throw UserCancelException.CANCEL_FILE_SELECTION;
- }
- break;
- }
-
- }
- hashTable.put(IMPORT_SOURCE_NAME, "Directory: " + imageFile.getAbsolutePath());
- origImageSizeInfo = imageDatasetReader
- .getImageSizeInfoForceZ(dirFiles[0].getAbsolutePath(), dirFiles.length);
- if (dirFiles.length > 1) {
- final String importZ = "Import Z-Sections";
- final String cancelOption = "Cancel";
- String result = DialogUtils.showWarningDialog(guiParent,
- "Import all files in directory '" + imageFile.getAbsolutePath()
- + "' as Z-Sections",
- new String[] { importZ, cancelOption }, importZ);
- if (result.equals(cancelOption)) {
- throw UserCancelException.CANCEL_GENERIC;
- }
- }
- hashTable.put(DIR_FILES, dirFiles);
- } else {
- origImageSizeInfo = imageDatasetReader
- .getImageSizeInfoForceZ(imageFile.getAbsolutePath(), null);
- hashTable.put(IMPORT_SOURCE_NAME, "File: " + imageFile.getAbsolutePath());
- }
- hashTable.put(ORIG_IMAGE_SIZE_INFO, origImageSizeInfo);
- return;
- }
- } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {
- getClientTaskStatusSupport().setMessage("Reading data from VCell server.");
- VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
- PDEDataContext pdeDataContext = mdiManager.getFieldDataWindowManager()
- .getPDEDataContext(docInfo.getExternalDataID(), null);
- ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
- pdeDataContext.setVariableNameAndTime(docInfo.getVarName(),
- newImageSizeInfo.getTimePoints()[newImageSizeInfo.getSelectedTimeIndex()]);
- double[] data = pdeDataContext.getDataValues();
- hashTable.put(INITIAL_ANNOTATION, hashTable.get(IMPORT_SOURCE_NAME));
- CartesianMesh mesh = (CartesianMesh) hashTable.get(FD_MESH);
- ISize meshISize = (ISize) hashTable.get(FD_MESHISIZE);
- double minValue = Double.POSITIVE_INFINITY;
- double maxValue = Double.NEGATIVE_INFINITY;
- for (int i = 0; i < data.length; i++) {
- minValue = Math.min(minValue, data[i]);
- maxValue = Math.max(maxValue, data[i]);
- }
- short[] dataToSegment = new short[data.length];
- double scaleShort = Math.pow(2, Short.SIZE) - 1;
- for (int i = 0; i < data.length; i++) {
- dataToSegment[i] |= (int) ((data[i] - minValue) / (maxValue - minValue) * scaleShort);
- }
- fdfos = new FieldDataFileOperationSpec();
- fdfos.origin = mesh.getOrigin();
- fdfos.extent = mesh.getExtent();
- fdfos.isize = meshISize;
- fdfos.shortSpecData = new short[][][] { { dataToSegment } };
-
- } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH) {
- ISize isize = getISizeFromUser(guiParent, new ISize(256, 256, 8),
- "Enter # of pixels for x,y,z (e.g. 3D{256,256,8}, 2D{256,256,1}, 1D{256,1,1})");
- fdfos = new FieldDataFileOperationSpec();
- fdfos.origin = new Origin(0, 0, 0);
- fdfos.extent = new Extent(1, 1, 1);
- fdfos.isize = isize;
- hashTable.put(IMPORT_SOURCE_NAME, "Scratch: New Geometry");
- // final int SCRATCH_SIZE_LIMIT = 512*512*20;
- // if(isize.getXYZ() > (SCRATCH_SIZE_LIMIT)){
- // throw new Exception("Total pixels (x*y*z) cannot be >"+SCRATCH_SIZE_LIMIT+".");
- // }
- } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC) {
- if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) {
- Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE);
- ISize defaultISize = workspaceGeom.getGeometrySpec().getDefaultSampledImageSize();
- ISize isize = getISizeFromUser(guiParent, defaultISize,
- "Warning: converting analytic expression geometry into an image based geometry\nwill remove analytic expressions after new image is created.\n\n"
- + "Enter size (x,y,z) for new geometry image (e.g. " + defaultISize.getX()
- + "," + defaultISize.getY() + "," + defaultISize.getZ() + ")");
- hashTable.put(IMPORT_SOURCE_NAME, "Workspace from Analytic Geometry");
- VCImage img = workspaceGeom.getGeometrySpec().createSampledImage(isize);
- Enumeration enumSubvolume = workspaceGeom.getGeometrySpec()
- .getAnalyticOrCSGSubVolumes();
- ArrayList vcPixelClassArrList = new ArrayList();
- while (enumSubvolume.hasMoreElements()) {
- SubVolume subVolume = enumSubvolume.nextElement();
- vcPixelClassArrList
- .add(new VCPixelClass(null, subVolume.getName(), subVolume.getHandle()));
- }
- if (vcPixelClassArrList.size() > img.getPixelClasses().length) {
- String result = DialogUtils.showOKCancelWarningDialog(requesterComp, null,
- "Warning: sampling size is too small to include all subvolumes.");
- if (result == null || !result.equals(SimpleUserMessage.OPTION_OK)) {
- throw UserCancelException.CANCEL_GENERIC;
- }
- }
- hashTable.put(VCPIXELCLASSES, vcPixelClassArrList.toArray(new VCPixelClass[0]));
- fdfos = createFDOSFromVCImage(img);
- } else {
- throw new Exception("Expecting image source for GEOM_OPTION_FROM_WORKSPACE_ANALYTIC");
- }
- } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE) {
- if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) {
- Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE);
- hashTable.put(IMPORT_SOURCE_NAME, "Workspace Image");
- fdfos = createFDOSFromVCImage(workspaceGeom.getGeometrySpec().getImage());
- if (workspaceGeom.getGeometrySpec().getImage().getDescription() != null) {
- hashTable.put(INITIAL_ANNOTATION,
- workspaceGeom.getGeometrySpec().getImage().getDescription());
- }
- GeometryClass[] myGeometryClasses = workspaceGeom.getGeometryClasses();
- VCPixelClass[] myPixelClasses = workspaceGeom.getGeometrySpec().getImage()
- .getPixelClasses();
- VCPixelClass[] newPixelClasses = new VCPixelClass[myPixelClasses.length];
- for (int i = 0; i < myPixelClasses.length; i++) {
- for (int j = 0; j < myGeometryClasses.length; j++) {
- if (myGeometryClasses[j] instanceof ImageSubVolume && myPixelClasses[i]
- .getPixel() == ((ImageSubVolume) myGeometryClasses[j]).getPixelValue()) {
- newPixelClasses[i] = new VCPixelClass(null, myGeometryClasses[j].getName(),
- myPixelClasses[i].getPixel());
- break;
- }
- }
- }
- hashTable.put(VCPIXELCLASSES, newPixelClasses);
- } else {
- throw new Exception("Expecting image source for GEOM_OPTION_FROM_WORKSPACE");
- }
- }
- hashTable.put(FDFOS, fdfos);
- } catch (DataFormatException ex) {
- throw new Exception("Cannot read image file.\n" + ex.getMessage());
- }
- }
- };
- return parseImageTask;
- }
-
- // Get image from file
- public static AsynchClientTask getSelectImageFileTask(final Component requesterComp,final UserPreferences userPreferences) {
- AsynchClientTask selectImageFileTask = new AsynchClientTask("select image file",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- File imageFile = DatabaseWindowManager.showFileChooserDialog(requesterComp, null, userPreferences,JFileChooser.FILES_AND_DIRECTORIES);
- hashTable.put(IMAGE_FILE, imageFile);
- hashTable.put(IMPORT_SOURCE_NAME, "File: " + imageFile.getName());
- }
- };
- return selectImageFileTask;
- }
-
- public static AsynchClientTask getImportFileImageTask(final VCDocument.DocumentCreationInfo documentCreationInfo) {
- AsynchClientTask importFileImageTask = new AsynchClientTask("Importing Image from File...",AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE && hashTable.get(FDFOS) == null) {
- ImageSizeInfo origImageSizeInfo = (ImageSizeInfo) hashTable.get(ORIG_IMAGE_SIZE_INFO);
- ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
- File[] dirFiles = (File[]) hashTable.get(DIR_FILES);
- File imageFile = (File) hashTable.get(IMAGE_FILE);
- FieldDataFileOperationSpec fdfos = null;
- boolean bMergeChannels = origImageSizeInfo.getNumChannels() != newImageSizeInfo.getNumChannels();
- ISize resize = (origImageSizeInfo.getiSize().compareEqual(newImageSizeInfo.getiSize()) ? null
- : newImageSizeInfo.getiSize());
- if (dirFiles != null) {
- Arrays.sort(dirFiles, new Comparator() {
- public int compare(File o1, File o2) {
- return o1.getName().compareToIgnoreCase(o2.getName());
- }
- });
- hashTable.put(INITIAL_ANNOTATION, dirFiles[0].getAbsolutePath() + "\n.\n.\n.\n"
- + dirFiles[dirFiles.length - 1].getAbsolutePath());
- short[][] dataToSegment = null;
- ISize isize = null;
- Origin origin = null;
- Extent extent = null;
- int sizeXY = 0;
- ISize firstImageISize = null;
- for (int i = 0; i < dirFiles.length; i++) {
- if (getClientTaskStatusSupport() != null) {
- getClientTaskStatusSupport()
- .setMessage("reading files " + (i + 1) + " of " + dirFiles.length);
- }
- ImageDataset[] imageDatasets = ImageDatasetReaderService.getInstance()
- .getImageDatasetReader().readImageDatasetChannels(dirFiles[i].getAbsolutePath(),
- getClientTaskStatusSupport(), bMergeChannels, null, resize);
- for (int c = 0; c < imageDatasets.length; c++) {
- if (imageDatasets[c].getSizeZ() != 1 || imageDatasets[c].getSizeT() != 1) {
- throwImportWholeDirectoryException(imageFile,
- dirFiles[i].getAbsolutePath() + " has Z=" + imageDatasets[c].getSizeZ()
- + " T=" + imageDatasets[c].getSizeT());
- }
- if (isize == null) {
- firstImageISize = imageDatasets[c].getISize();
- sizeXY = imageDatasets[c].getISize().getX() * imageDatasets[c].getISize().getY();
- dataToSegment = new short[imageDatasets.length][sizeXY * dirFiles.length];
- isize = new ISize(imageDatasets[c].getISize().getX(),
- imageDatasets[c].getISize().getY(), dirFiles.length);
- origin = imageDatasets[c].getAllImages()[0].getOrigin();
- extent = imageDatasets[c].getExtent();
- }
- if (!firstImageISize.compareEqual(imageDatasets[c].getISize())) {
- throwImportWholeDirectoryException(imageFile,
- dirFiles[0].getAbsolutePath() + " " + firstImageISize + " does not equal "
- + dirFiles[i].getAbsolutePath() + " "
- + imageDatasets[c].getISize());
- }
- System.arraycopy(imageDatasets[c].getImage(0, 0, 0).getPixels(), 0, dataToSegment[c],
- sizeXY * i, sizeXY);
-
- }
- }
- fdfos = new FieldDataFileOperationSpec();
- fdfos.origin = origin;
- fdfos.extent = extent;
- fdfos.isize = isize;
- fdfos.shortSpecData = new short[][][] { dataToSegment };
- } else {
- hashTable.put(INITIAL_ANNOTATION, imageFile.getAbsolutePath());
- Integer userPreferredTimeIndex = null;
- if (origImageSizeInfo.getTimePoints().length > 1) {
- userPreferredTimeIndex = newImageSizeInfo.getSelectedTimeIndex();
- }
- if(getClientTaskStatusSupport() != null) {
- getClientTaskStatusSupport().setMessage("Reading file...");
- }
- ImageDataset[] imageDatasets = ImageDatasetReaderService.getInstance().getImageDatasetReader()
- .readImageDatasetChannels(imageFile.getAbsolutePath(), getClientTaskStatusSupport(),
- bMergeChannels, userPreferredTimeIndex, resize);
- fdfos = ClientRequestManager.createFDOSWithChannels(imageDatasets, null);
- }
- hashTable.put(FDFOS, fdfos);
- hashTable.remove(NEW_IMAGE_SIZE_INFO);
- hashTable.remove(ORIG_IMAGE_SIZE_INFO);
- hashTable.remove(DIR_FILES);
- }
- }
- };
- return importFileImageTask;
- }
-
- public static AsynchClientTask getResizeImageTask(final VCDocument.DocumentCreationInfo documentCreationInfo) {
- AsynchClientTask resizeImageTask = new AsynchClientTask("Resizing Image...",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
- FieldDataFileOperationSpec fdfos = (FieldDataFileOperationSpec) hashTable.get(FDFOS);
- if (newImageSizeInfo != null && fdfos != null
- && !fdfos.isize.compareEqual(newImageSizeInfo.getiSize())) {
+ ;
+ }
+
+ private static void throwImportWholeDirectoryException(File invalidFile, String extraInfo) throws Exception {
+ throw new Exception("Import whole directory failed: directory '" + invalidFile.getAbsolutePath() + "' "
+ + "contains invalid file. Import from whole directory can contain only files for "
+ + "a single z-series, each file must be 2D, single time. "
+ + "All files must be the same size and have the same number color channels."
+ + (extraInfo == null ? "" : "\n" + extraInfo));
+
+ }
+
+ private static FieldDataFileOperationSpec createFDOSFromVCImage(VCImage dbImage) throws ImageException {
+ int[] temp = new int[256];
+ short[] templateShorts = new short[dbImage.getNumXYZ()];
+ for (int i = 0; i < dbImage.getPixels().length; i++) {
+ templateShorts[i] = (short) (0x00FF & dbImage.getPixels()[i]);
+ temp[templateShorts[i]]++;
+ }
+ for (int j = 0; j < dbImage.getPixelClasses().length; j++) {
+ short tempshort = (short) (0x00FF & dbImage.getPixelClasses()[j].getPixel());
+ }
+ FieldDataFileOperationSpec fdfos = null;
+ fdfos = new FieldDataFileOperationSpec();
+ fdfos.origin = new Origin(0, 0, 0);
+ fdfos.extent = dbImage.getExtent();
+ fdfos.isize = new ISize(dbImage.getNumX(), dbImage.getNumY(), dbImage.getNumZ());
+ fdfos.shortSpecData = new short[][][]{{templateShorts}};
+ return fdfos;
+ }
+
+ public static SurfaceCollection createSurfaceCollectionFromSurfaceFile(File surfaceFile) throws Exception {
+ SurfaceCollection surfaceCollection = null;
+ if (ExtensionFilter.isMatchingExtension(surfaceFile, ".stl")) {
+ surfaceCollection = StlReader.readStl(surfaceFile);
+ } else if (ExtensionFilter.isMatchingExtension(surfaceFile, ".mesh")) {// NOT VCell mesh, salk Hughes Hoppe mesh
+ // convert to .stl and read
+ BufferedWriter stlBufferedWriter = null;
+ File tempstlFile = File.createTempFile("salk", ".stl");
+ try {
+ try (BufferedReader salkBufferedReader = new BufferedReader(new FileReader(surfaceFile))) {
+ String line;
+ ArrayList vertList = new ArrayList();
+ // read vertices
+ while ((line = salkBufferedReader.readLine()) != null) {
+ StringTokenizer st = new StringTokenizer(line, " ");
+ String firstToken = st.nextToken();
+ int vertIndex = Integer.parseInt(st.nextToken());
+ if (firstToken.equals("Vertex")) {
+ vertList.add(new double[]{Double.parseDouble(st.nextToken()),
+ Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken())});
+ if (vertList.size() != vertIndex) {// numbering starts at 1
+ throw new Exception("Index not match position in list");
+ }
+ } else if (firstToken.equals("Face")) {
+ break;// read all vertices
+ } else {
+ return null;
+ }
+ }
+ stlBufferedWriter = new BufferedWriter(new FileWriter(tempstlFile));
+ stlBufferedWriter.write("solid VCell salk convert\n");
+ // read faces
+ do {
+ stlBufferedWriter.write("facet normal 0 0 0\n");
+ stlBufferedWriter.write("outer loop\n");
+ StringTokenizer st = new StringTokenizer(line, " ");
+ String firstToken = st.nextToken();
+ Integer.parseInt(st.nextToken());// ignore index token
+ if (firstToken.equals("Face")) {
+ for (int i = 0; i < 3; i++) {
+ int vertListIndex = Integer.parseInt(st.nextToken()) - 1;
+ double[] vertCoordinatges = vertList.get(vertListIndex);
+ stlBufferedWriter.write("vertex " + vertCoordinatges[0] + " " + vertCoordinatges[1]
+ + " " + vertCoordinatges[2] + "\n");// indexes start at 1, not 0
+ }
+ } else {
+ throw new Exception("Expecting token 'Face' but got " + firstToken);
+ }
+ stlBufferedWriter.write("endloop\n");
+ stlBufferedWriter.write("endfacet\n");
+ } while ((line = salkBufferedReader.readLine()) != null);
+ stlBufferedWriter.write("endsolid VCell salk convert\n");
+
+ stlBufferedWriter.close();
+ surfaceCollection = StlReader.readStl(tempstlFile);
+ }
+ } catch (Exception e) {
+ // we couldn't read this for some reason
+ e.printStackTrace();
+ } finally {
+ if (stlBufferedWriter != null) {
+ try {
+ stlBufferedWriter.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ if (tempstlFile != null) {
+ tempstlFile.delete();
+ }
+ }
+ }
+ return surfaceCollection;
+ }
+
+ public static FieldDataFileOperationSpec createFDOSFromSurfaceFile(File surfaceFile) throws Exception {
+ SurfaceCollection surfaceCollection = createSurfaceCollectionFromSurfaceFile(surfaceFile);
+ if (surfaceCollection != null) {
+ Geometry geometry = RayCaster.createGeometryFromSTL(new GeometryThumbnailImageFactoryAWT(),
+ surfaceCollection, 1000000);
+ FieldDataFileOperationSpec fdfos = new FieldDataFileOperationSpec();
+ fdfos.origin = geometry.getOrigin();
+ fdfos.extent = geometry.getExtent();
+ VCImage image = geometry.getGeometrySpec().getImage();
+ if (image.getNumPixelClasses() == 1) {
+ throw new Exception("STL import failed during processing, pixelclass count=1");
+ }
+ fdfos.isize = new ISize(image.getNumX(), image.getNumY(), image.getNumZ());
+ byte[] pixels = image.getPixels();
+ short[] dataToSegment = new short[image.getNumXYZ()];
+ for (int i = 0; i < pixels.length; i++) {
+ dataToSegment[i] = pixels[i];
+ }
+ fdfos.shortSpecData = new short[][][]{{dataToSegment}};
+ return fdfos;
+ }
+ return null;
+ }
+
+ public static final String GEOM_FROM_WORKSPACE = "GEOM_FROM_WORKSPACE";
+ public static final String VCPIXELCLASSES = "VCPIXELCLASSES";
+
+ private enum NRRDTYPE {
+ DOUBLE, FLOAT, UNSIGNEDCHAR
+ }
+
+ private enum NRRDENCODING {
+ RAW, GZIP
+ }
+
+ public static final String IMPORT_SOURCE_NAME = "IMPORT_SOURCE_NAME";
+ private static final String DIR_FILES = "DIR_FILES";
+ public static final String ORIG_IMAGE_SIZE_INFO = "ORIG_IMAGE_SIZE_INFO";
+ public static final String NEW_IMAGE_SIZE_INFO = "NEW_IMAGE_SIZE_INFO";
+ private static final String INITIAL_ANNOTATION = "INITIAL_ANNOTATION";
+ private static final String FD_MESH = "FD_MESH";
+ private static final String FD_MESHISIZE = "FD_MESHISIZE";
+ public static final String FDFOS = "FDFOS";
+ private static final String IMAGE_FILE = "IMAGE_FILE";
+
+ public static AsynchClientTask getParseImageTask(final Component requesterComp, final VCDocument.DocumentCreationInfo documentCreationInfo, final MDIManager mdiManager) {
+ AsynchClientTask parseImageTask = new AsynchClientTask("read and parse image file", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(final Hashtable hashTable) throws Exception {
+
+ final Component guiParent = (Component) hashTable.get(ClientRequestManager.GUI_PARENT);
+ try {
+ FieldDataFileOperationSpec fdfos = null;
+ // if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ){
+ // hashTable.put("imageFile",ImageJHelper.vcellWantImage(getClientTaskStatusSupport(),"Image for new VCell geometry"));
+ // }
+ // if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER){
+ // hashTable.put("imageFile",ImageJHelper.vcellWantSurface(getClientTaskStatusSupport(),"Image for new VCell geometry"));
+ // }
+ if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE
+ // || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ ||
+ // documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER
+ ) {
+
+ File imageFile = (File) hashTable.get(IMAGE_FILE);
+ if (imageFile == null) {
+ throw new Exception("No file selected");
+ }
+ if (ExtensionFilter.isMatchingExtension(imageFile, ".nrrd")) {
+
+ DataInputStream dis = null;
+ try {
+ dis = new DataInputStream(new BufferedInputStream(new FileInputStream(imageFile)));
+ int xsize = 1;
+ int ysize = 1;
+ int zsize = 1;
+ double xspace = 1.0;
+ double yspace = 1.0;
+ double zspace = 1.0;
+ NRRDTYPE type = null;
+ NRRDENCODING encoding = null;
+ int dimension = -1;
+ // read header lines
+ while (true) {
+ @SuppressWarnings("deprecation")
+ String line = dis.readLine();
+ if (line == null || line.length() == 0) {
+ break;
+ }
+ StringTokenizer stringTokenizer = new StringTokenizer(line, ": ");
+ String headerParam = stringTokenizer.nextToken();
+ // System.out.println(headerParam);
+ if (headerParam.equals("sizes")) {
+ if (dimension != -1) {
+ xsize = Integer.parseInt(stringTokenizer.nextToken());
+ if (dimension >= 2) {
+ ysize = Integer.parseInt(stringTokenizer.nextToken());
+ }
+ if (dimension >= 3) {
+ zsize = Integer.parseInt(stringTokenizer.nextToken());
+ }
+ for (int i = 4; i < dimension; i++) {
+ if (Integer.parseInt(stringTokenizer.nextToken()) != 1) {
+ throw new Exception("Dimensions > 3 not supported");
+ }
+ }
+ } else {
+ throw new Exception("dimension expected to be set before reading sizes");
+ }
+ } else if (headerParam.equals("spacings")) {
+ if (dimension != -1) {
+ xspace = Double.parseDouble(stringTokenizer.nextToken());
+ if (dimension >= 2) {
+ yspace = Double.parseDouble(stringTokenizer.nextToken());
+ }
+ if (dimension >= 3) {
+ zspace = Double.parseDouble(stringTokenizer.nextToken());
+ }
+ // ignore other dimension spacings
+ } else {
+ throw new Exception("dimension expected to be set before reading spacings");
+ }
+ } else if (headerParam.equals("type")) {
+ String nextToken = stringTokenizer.nextToken();
+ if (nextToken.equalsIgnoreCase("double")) {
+ type = NRRDTYPE.DOUBLE;
+ } else if (nextToken.equalsIgnoreCase("float")) {
+ type = NRRDTYPE.FLOAT;
+ } else if (nextToken.equalsIgnoreCase("unsigned")) {
+ nextToken = stringTokenizer.nextToken();
+ if (nextToken.equalsIgnoreCase("char")) {
+ type = NRRDTYPE.UNSIGNEDCHAR;
+ } else {
+ throw new Exception("Unknown nrrd data type=" + nextToken);
+ }
+ } else {
+ throw new Exception("Unknown nrrd data type=" + nextToken);
+ }
+ } else if (headerParam.equals("dimension")) {
+ dimension = Integer.parseInt(stringTokenizer.nextToken());
+ if (dimension < 1) {
+ throw new Exception("unexpected dimension=" + dimension);
+ }
+ } else if (headerParam.equals("encoding")) {
+ encoding = NRRDENCODING.valueOf(stringTokenizer.nextToken().toUpperCase());
+ }
+ }
+ BufferedInputStream bis = null;
+ if (encoding == NRRDENCODING.GZIP) {
+ dis.close();
+ bis = new BufferedInputStream(new FileInputStream(imageFile));
+ boolean bnewLine = false;
+ while (true) {
+ int currentChar = bis.read();
+ if (currentChar == '\n') {
+ if (bnewLine) {
+ break;// 2 newlines end header
+ }
+ bnewLine = true;
+ } else {
+ bnewLine = false;
+ }
+ }
+ GZIPInputStream gzipInputStream = new GZIPInputStream(bis);
+ dis = new DataInputStream(gzipInputStream);
+ }
+ double[] data = new double[xsize * ysize * zsize];
+ double minValue = Double.POSITIVE_INFINITY;
+ double maxValue = Double.NEGATIVE_INFINITY;
+ for (int i = 0; i < data.length; i++) {
+ if (i % 262144 == 0) {
+ if (this.getClientTaskStatusSupport() != null) {
+ this.getClientTaskStatusSupport().setMessage("Reading " + encoding + " " + type
+ + " NRRD data " + (((long) i * (long) 100) / (long) data.length)
+ + " % done.");
+ }
+ }
+ if (type == NRRDTYPE.DOUBLE) {
+ data[i] = dis.readDouble();
+ } else if (type == NRRDTYPE.FLOAT) {
+ data[i] = dis.readFloat();
+ } else if (type == NRRDTYPE.UNSIGNEDCHAR) {
+ data[i] = dis.readUnsignedByte();
+ } else {
+ throw new Exception("Unexpected data type=" + type.toString());
+ }
+
+ minValue = Math.min(minValue, data[i]);
+ maxValue = Math.max(maxValue, data[i]);
+ }
+ dis.close();
+ if (this.getClientTaskStatusSupport() != null) {
+ this.getClientTaskStatusSupport()
+ .setMessage("Scaling " + encoding + " " + type + " NRRD data.");
+ }
+
+ short[] dataToSegment = new short[data.length];
+ double scaleShort = Math.pow(2, Short.SIZE) - 1;
+ for (int i = 0; i < data.length; i++) {
+ dataToSegment[i] |= (int) ((data[i] - minValue) / (maxValue - minValue)
+ * scaleShort);
+ }
+ fdfos = new FieldDataFileOperationSpec();
+ fdfos.origin = new Origin(0, 0, 0);
+ fdfos.extent = new Extent((xsize == 1 ? .5 : (xsize) * xspace),
+ (ysize == 1 ? .5 : (ysize) * yspace), (zsize == 1 ? .5 : (zsize) * zspace));
+ fdfos.isize = new ISize(xsize, ysize, zsize);
+ fdfos.shortSpecData = new short[][][]{{dataToSegment}};
+ } finally {
+ if (dis != null) {
+ try {
+ dis.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ } else if ((fdfos = createFDOSFromSurfaceFile(imageFile)) != null) {// try surface file formats
+ // work already done at this point
+ } else {
+ File[] dirFiles = null;
+ ImageSizeInfo origImageSizeInfo = null;
+ ImageDatasetReaderService imageDatasetReaderServiceInstance = ImageDatasetReaderService
+ .getInstance();
+ ImageDatasetReader imageDatasetReader = imageDatasetReaderServiceInstance
+ .getImageDatasetReader();
+ if (imageFile.isDirectory()) {
+ dirFiles = imageFile.listFiles(new java.io.FileFilter() {
+ public boolean accept(File pathname) {
+ return pathname.isFile() && !pathname.isHidden();// exclude windows Thumbs.db
+ }
+ });
+ if (dirFiles.length == 0) {
+ throw new Exception("No valid files in selected directory");
+ }
+ String fileExt0 = null;
+ for (int i = 0; i < dirFiles.length; i++) {
+ int lastDot = dirFiles[i].getName().lastIndexOf('.');
+ String fileExt = (lastDot != -1 ? dirFiles[i].getName().substring(lastDot) : null);
+ if (dirFiles[i].isDirectory()) {
+ fileExt = "dir";
+ }
+ if (i == 0) {
+ fileExt0 = fileExt;
+ } else if (!Compare.isEqualOrNull(fileExt, fileExt0)) {
+ String result = DialogUtils.showWarningDialog(requesterComp,
+ "Files in '" + imageFile.getAbsolutePath()
+ + "' have different name extensions, continue?",
+ new String[]{"OK", "Cancel"}, "Cancel");
+ if (!"OK".equals(result)) {
+ throw UserCancelException.CANCEL_FILE_SELECTION;
+ }
+ break;
+ }
+
+ }
+ hashTable.put(IMPORT_SOURCE_NAME, "Directory: " + imageFile.getAbsolutePath());
+ origImageSizeInfo = imageDatasetReader
+ .getImageSizeInfoForceZ(dirFiles[0].getAbsolutePath(), dirFiles.length);
+ if (dirFiles.length > 1) {
+ final String importZ = "Import Z-Sections";
+ final String cancelOption = "Cancel";
+ String result = DialogUtils.showWarningDialog(guiParent,
+ "Import all files in directory '" + imageFile.getAbsolutePath()
+ + "' as Z-Sections",
+ new String[]{importZ, cancelOption}, importZ);
+ if (result.equals(cancelOption)) {
+ throw UserCancelException.CANCEL_GENERIC;
+ }
+ }
+ hashTable.put(DIR_FILES, dirFiles);
+ } else {
+ origImageSizeInfo = imageDatasetReader
+ .getImageSizeInfoForceZ(imageFile.getAbsolutePath(), null);
+ hashTable.put(IMPORT_SOURCE_NAME, "File: " + imageFile.getAbsolutePath());
+ }
+ hashTable.put(ORIG_IMAGE_SIZE_INFO, origImageSizeInfo);
+ return;
+ }
+ } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {
+ this.getClientTaskStatusSupport().setMessage("Reading data from VCell server.");
+ VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
+ PDEDataContext pdeDataContext = mdiManager.getFieldDataWindowManager()
+ .getPDEDataContext(docInfo.getExternalDataID(), null);
+ ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
+ pdeDataContext.setVariableNameAndTime(docInfo.getVarName(),
+ newImageSizeInfo.getTimePoints()[newImageSizeInfo.getSelectedTimeIndex()]);
+ double[] data = pdeDataContext.getDataValues();
+ hashTable.put(INITIAL_ANNOTATION, hashTable.get(IMPORT_SOURCE_NAME));
+ CartesianMesh mesh = (CartesianMesh) hashTable.get(FD_MESH);
+ ISize meshISize = (ISize) hashTable.get(FD_MESHISIZE);
+ double minValue = Double.POSITIVE_INFINITY;
+ double maxValue = Double.NEGATIVE_INFINITY;
+ for (int i = 0; i < data.length; i++) {
+ minValue = Math.min(minValue, data[i]);
+ maxValue = Math.max(maxValue, data[i]);
+ }
+ short[] dataToSegment = new short[data.length];
+ double scaleShort = Math.pow(2, Short.SIZE) - 1;
+ for (int i = 0; i < data.length; i++) {
+ dataToSegment[i] |= (int) ((data[i] - minValue) / (maxValue - minValue) * scaleShort);
+ }
+ fdfos = new FieldDataFileOperationSpec();
+ fdfos.origin = mesh.getOrigin();
+ fdfos.extent = mesh.getExtent();
+ fdfos.isize = meshISize;
+ fdfos.shortSpecData = new short[][][]{{dataToSegment}};
+
+ } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH) {
+ ISize isize = getISizeFromUser(guiParent, new ISize(256, 256, 8),
+ "Enter # of pixels for x,y,z (e.g. 3D{256,256,8}, 2D{256,256,1}, 1D{256,1,1})");
+ fdfos = new FieldDataFileOperationSpec();
+ fdfos.origin = new Origin(0, 0, 0);
+ fdfos.extent = new Extent(1, 1, 1);
+ fdfos.isize = isize;
+ hashTable.put(IMPORT_SOURCE_NAME, "Scratch: New Geometry");
+ // final int SCRATCH_SIZE_LIMIT = 512*512*20;
+ // if(isize.getXYZ() > (SCRATCH_SIZE_LIMIT)){
+ // throw new Exception("Total pixels (x*y*z) cannot be >"+SCRATCH_SIZE_LIMIT+".");
+ // }
+ } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC) {
+ if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) {
+ Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE);
+ ISize defaultISize = workspaceGeom.getGeometrySpec().getDefaultSampledImageSize();
+ ISize isize = getISizeFromUser(guiParent, defaultISize,
+ "Warning: converting analytic expression geometry into an image based geometry\nwill remove analytic expressions after new image is created.\n\n"
+ + "Enter size (x,y,z) for new geometry image (e.g. " + defaultISize.getX()
+ + "," + defaultISize.getY() + "," + defaultISize.getZ() + ")");
+ hashTable.put(IMPORT_SOURCE_NAME, "Workspace from Analytic Geometry");
+ VCImage img = workspaceGeom.getGeometrySpec().createSampledImage(isize);
+ Enumeration enumSubvolume = workspaceGeom.getGeometrySpec()
+ .getAnalyticOrCSGSubVolumes();
+ ArrayList vcPixelClassArrList = new ArrayList();
+ while (enumSubvolume.hasMoreElements()) {
+ SubVolume subVolume = enumSubvolume.nextElement();
+ vcPixelClassArrList
+ .add(new VCPixelClass(null, subVolume.getName(), subVolume.getHandle()));
+ }
+ if (vcPixelClassArrList.size() > img.getPixelClasses().length) {
+ String result = DialogUtils.showOKCancelWarningDialog(requesterComp, null,
+ "Warning: sampling size is too small to include all subvolumes.");
+ if (result == null || !result.equals(SimpleUserMessage.OPTION_OK)) {
+ throw UserCancelException.CANCEL_GENERIC;
+ }
+ }
+ hashTable.put(VCPIXELCLASSES, vcPixelClassArrList.toArray(new VCPixelClass[0]));
+ fdfos = createFDOSFromVCImage(img);
+ } else {
+ throw new Exception("Expecting image source for GEOM_OPTION_FROM_WORKSPACE_ANALYTIC");
+ }
+ } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE) {
+ if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) {
+ Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE);
+ hashTable.put(IMPORT_SOURCE_NAME, "Workspace Image");
+ fdfos = createFDOSFromVCImage(workspaceGeom.getGeometrySpec().getImage());
+ if (workspaceGeom.getGeometrySpec().getImage().getDescription() != null) {
+ hashTable.put(INITIAL_ANNOTATION,
+ workspaceGeom.getGeometrySpec().getImage().getDescription());
+ }
+ GeometryClass[] myGeometryClasses = workspaceGeom.getGeometryClasses();
+ VCPixelClass[] myPixelClasses = workspaceGeom.getGeometrySpec().getImage()
+ .getPixelClasses();
+ VCPixelClass[] newPixelClasses = new VCPixelClass[myPixelClasses.length];
+ for (int i = 0; i < myPixelClasses.length; i++) {
+ for (int j = 0; j < myGeometryClasses.length; j++) {
+ if (myGeometryClasses[j] instanceof ImageSubVolume && myPixelClasses[i]
+ .getPixel() == ((ImageSubVolume) myGeometryClasses[j]).getPixelValue()) {
+ newPixelClasses[i] = new VCPixelClass(null, myGeometryClasses[j].getName(),
+ myPixelClasses[i].getPixel());
+ break;
+ }
+ }
+ }
+ hashTable.put(VCPIXELCLASSES, newPixelClasses);
+ } else {
+ throw new Exception("Expecting image source for GEOM_OPTION_FROM_WORKSPACE");
+ }
+ }
+ hashTable.put(FDFOS, fdfos);
+ } catch (DataFormatException ex) {
+ throw new Exception("Cannot read image file.\n" + ex.getMessage());
+ }
+ }
+ };
+ return parseImageTask;
+ }
+
+ // Get image from file
+ public static AsynchClientTask getSelectImageFileTask(final Component requesterComp, final UserPreferences userPreferences) {
+ AsynchClientTask selectImageFileTask = new AsynchClientTask("select image file",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ File imageFile = DatabaseWindowManager.showFileChooserDialog(requesterComp, null, userPreferences, JFileChooser.FILES_AND_DIRECTORIES);
+ hashTable.put(IMAGE_FILE, imageFile);
+ hashTable.put(IMPORT_SOURCE_NAME, "File: " + imageFile.getName());
+ }
+ };
+ return selectImageFileTask;
+ }
+
+ public static AsynchClientTask getImportFileImageTask(final VCDocument.DocumentCreationInfo documentCreationInfo) {
+ AsynchClientTask importFileImageTask = new AsynchClientTask("Importing Image from File...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE && hashTable.get(FDFOS) == null) {
+ ImageSizeInfo origImageSizeInfo = (ImageSizeInfo) hashTable.get(ORIG_IMAGE_SIZE_INFO);
+ ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
+ File[] dirFiles = (File[]) hashTable.get(DIR_FILES);
+ File imageFile = (File) hashTable.get(IMAGE_FILE);
+ FieldDataFileOperationSpec fdfos = null;
+ boolean bMergeChannels = origImageSizeInfo.getNumChannels() != newImageSizeInfo.getNumChannels();
+ ISize resize = (origImageSizeInfo.getiSize().compareEqual(newImageSizeInfo.getiSize()) ? null
+ : newImageSizeInfo.getiSize());
+ if (dirFiles != null) {
+ Arrays.sort(dirFiles, new Comparator() {
+ public int compare(File o1, File o2) {
+ return o1.getName().compareToIgnoreCase(o2.getName());
+ }
+ });
+ hashTable.put(INITIAL_ANNOTATION, dirFiles[0].getAbsolutePath() + "\n.\n.\n.\n"
+ + dirFiles[dirFiles.length - 1].getAbsolutePath());
+ short[][] dataToSegment = null;
+ ISize isize = null;
+ Origin origin = null;
+ Extent extent = null;
+ int sizeXY = 0;
+ ISize firstImageISize = null;
+ for (int i = 0; i < dirFiles.length; i++) {
+ if (this.getClientTaskStatusSupport() != null) {
+ this.getClientTaskStatusSupport()
+ .setMessage("reading files " + (i + 1) + " of " + dirFiles.length);
+ }
+ ImageDataset[] imageDatasets = ImageDatasetReaderService.getInstance()
+ .getImageDatasetReader().readImageDatasetChannels(dirFiles[i].getAbsolutePath(),
+ this.getClientTaskStatusSupport(), bMergeChannels, null, resize);
+ for (int c = 0; c < imageDatasets.length; c++) {
+ if (imageDatasets[c].getSizeZ() != 1 || imageDatasets[c].getSizeT() != 1) {
+ throwImportWholeDirectoryException(imageFile,
+ dirFiles[i].getAbsolutePath() + " has Z=" + imageDatasets[c].getSizeZ()
+ + " T=" + imageDatasets[c].getSizeT());
+ }
+ if (isize == null) {
+ firstImageISize = imageDatasets[c].getISize();
+ sizeXY = imageDatasets[c].getISize().getX() * imageDatasets[c].getISize().getY();
+ dataToSegment = new short[imageDatasets.length][sizeXY * dirFiles.length];
+ isize = new ISize(imageDatasets[c].getISize().getX(),
+ imageDatasets[c].getISize().getY(), dirFiles.length);
+ origin = imageDatasets[c].getAllImages()[0].getOrigin();
+ extent = imageDatasets[c].getExtent();
+ }
+ if (!firstImageISize.compareEqual(imageDatasets[c].getISize())) {
+ throwImportWholeDirectoryException(imageFile,
+ dirFiles[0].getAbsolutePath() + " " + firstImageISize + " does not equal "
+ + dirFiles[i].getAbsolutePath() + " "
+ + imageDatasets[c].getISize());
+ }
+ System.arraycopy(imageDatasets[c].getImage(0, 0, 0).getPixels(), 0, dataToSegment[c],
+ sizeXY * i, sizeXY);
+
+ }
+ }
+ fdfos = new FieldDataFileOperationSpec();
+ fdfos.origin = origin;
+ fdfos.extent = extent;
+ fdfos.isize = isize;
+ fdfos.shortSpecData = new short[][][]{dataToSegment};
+ } else {
+ hashTable.put(INITIAL_ANNOTATION, imageFile.getAbsolutePath());
+ Integer userPreferredTimeIndex = null;
+ if (origImageSizeInfo.getTimePoints().length > 1) {
+ userPreferredTimeIndex = newImageSizeInfo.getSelectedTimeIndex();
+ }
+ if (this.getClientTaskStatusSupport() != null) {
+ this.getClientTaskStatusSupport().setMessage("Reading file...");
+ }
+ ImageDataset[] imageDatasets = ImageDatasetReaderService.getInstance().getImageDatasetReader()
+ .readImageDatasetChannels(imageFile.getAbsolutePath(), this.getClientTaskStatusSupport(),
+ bMergeChannels, userPreferredTimeIndex, resize);
+ fdfos = ClientRequestManager.createFDOSWithChannels(imageDatasets, null);
+ }
+ hashTable.put(FDFOS, fdfos);
+ hashTable.remove(NEW_IMAGE_SIZE_INFO);
+ hashTable.remove(ORIG_IMAGE_SIZE_INFO);
+ hashTable.remove(DIR_FILES);
+ }
+ }
+ };
+ return importFileImageTask;
+ }
+
+ public static AsynchClientTask getResizeImageTask(final VCDocument.DocumentCreationInfo documentCreationInfo) {
+ AsynchClientTask resizeImageTask = new AsynchClientTask("Resizing Image...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
+ FieldDataFileOperationSpec fdfos = (FieldDataFileOperationSpec) hashTable.get(FDFOS);
+ if (newImageSizeInfo != null && fdfos != null
+ && !fdfos.isize.compareEqual(newImageSizeInfo.getiSize())) {
// resizeImage((FieldDataFileOperationSpec) hashTable.get(FDFOS), newImageSizeInfo.getiSize(),
// documentCreationInfo.getOption());
- resize0(hashTable);
- }
- }
- };
- return resizeImageTask;
- }
-
- private static void resize0(Hashtable hashTable/*ImageSizeInfo sourceSize,ImageSizeInfo newSize*/) {
+ resize0(hashTable);
+ }
+ }
+ };
+ return resizeImageTask;
+ }
+
+ private static void resize0(Hashtable hashTable/*ImageSizeInfo sourceSize,ImageSizeInfo newSize*/) {
// OrigOrigin = new Origin
// CartesianMesh origMesh = CartesianMesh.createSimpleCartesianMesh(orig, extent, size, regionImage);
// ISize varISize = dataProcessingOutputInfo.getVariableISize(varName);
@@ -1794,1323 +1803,1315 @@ private static void resize0(Hashtable hashTable/*ImageSizeInfo sourceSize,ImageS
// varExtent,
// varISize, regionImage);
- CartesianMesh origMesh = (CartesianMesh) hashTable.get("sourceMesh");
- CartesianMesh resampleMesh = (CartesianMesh) hashTable.get("newMesh");
- FieldDataFileOperationSpec fdfos = (FieldDataFileOperationSpec) hashTable.get(FDFOS);
- double[] origData = new double[fdfos.isize.getXYZ()];
- for(int i=0;i hashTable) throws Exception {
- VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
- PDEDataContext pdeDataContext = getMdiManager().getFieldDataWindowManager()
- .getPDEDataContext(docInfo.getExternalDataID(), null);
- CartesianMesh mesh = pdeDataContext.getCartesianMesh();
- ISize meshISize = new ISize(mesh.getSizeX(), mesh.getSizeY(), mesh.getSizeZ());
- double[] timePoints = pdeDataContext.getTimePoints();
- hashTable.put(FD_MESH, mesh);
- hashTable.put(FD_MESHISIZE, meshISize);
- hashTable.put(FD_TIMEPOINTS, timePoints);
- }
- };
- AsynchClientTask queryImageResizeTask = new AsynchClientTask("Query File Image Resize...",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- String importSourceName = (String) hashTable.get(IMPORT_SOURCE_NAME);
- if ((ImageSizeInfo) hashTable.get(ORIG_IMAGE_SIZE_INFO) != null) {// from file
- ImageSizeInfo newImagesiSizeInfo = queryImageResize(requester.getComponent(),
- (ImageSizeInfo) hashTable.get(ORIG_IMAGE_SIZE_INFO), true);
- hashTable.put(NEW_IMAGE_SIZE_INFO, newImagesiSizeInfo);
- } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {// from fielddata
- VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
- double[] fieldDataTimes = (double[]) hashTable.get(FD_TIMEPOINTS);
- hashTable.remove(FD_TIMEPOINTS);
- ISize fieldDataISize = (ISize) hashTable.get(FD_MESHISIZE);
- ImageSizeInfo origImageSizeInfo = new ImageSizeInfo(importSourceName, fieldDataISize, 1,
- fieldDataTimes, null);
- ImageSizeInfo newImagesiSizeInfo = queryImageResize(requester.getComponent(), origImageSizeInfo,
- true);
- hashTable.put(NEW_IMAGE_SIZE_INFO, newImagesiSizeInfo);
- hashTable.put(IMPORT_SOURCE_NAME,
- "FieldData: " + docInfo.getExternalDataID().getName() + " varName=" + docInfo.getVarName()
- + " timeIndex="
- + newImagesiSizeInfo.getTimePoints()[newImagesiSizeInfo.getSelectedTimeIndex()]);
- }
- }
- };
-
- AsynchClientTask importFileImageTask = getImportFileImageTask(documentCreationInfo);
-
- AsynchClientTask resizeImageTask = getResizeImageTask(documentCreationInfo);
-
- AsynchClientTask finishTask = new AsynchClientTask("Finishing...",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(final Hashtable hashTable) throws Exception {
- getClientTaskStatusSupport().setMessage("Initializing...");
- final ROIMultiPaintManager roiMultiPaintManager = new ROIMultiPaintManager();
- roiMultiPaintManager.setDocumentManager(ClientRequestManager.this.getDocumentManager());
- roiMultiPaintManager.initROIAndUnderlay((FieldDataFileOperationSpec) hashTable.get(FDFOS));
- final Geometry[] geomHolder = new Geometry[1];
- final VCPixelClass[] postProcessPixelClasses = (VCPixelClass[]) hashTable.get(VCPIXELCLASSES);
- AsynchClientTask task1 = new AsynchClientTask("edit geometry", AsynchClientTask.TASKTYPE_SWING_BLOCKING,
- false) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- geomHolder[0] = roiMultiPaintManager.showGUI(okButtonText,
- (String) hashTable.get(IMPORT_SOURCE_NAME), (Component) hashTable.get(GUI_PARENT),
- (String) hashTable.get(INITIAL_ANNOTATION), postProcessPixelClasses,
- getUserPreferences(),
- (hashTable.get(BioModelWindowManager.FIELD_DATA_FLAG)==null?false:((Boolean)hashTable.get(BioModelWindowManager.FIELD_DATA_FLAG)).booleanValue()));
- }
- };
- AsynchClientTask task2 = new AsynchClientTask("update geometry",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- // Create default name for image
- String dateTimeString = BeanUtils.generateDateTimeString();
- geomHolder[0].getGeometrySpec().getImage().setName("img_" + dateTimeString);
- geomHolder[0].setName("geom_" + dateTimeString);
- // cause update in this thread so later swing threads won't be delayed
- geomHolder[0].precomputeAll(new GeometryThumbnailImageFactoryAWT());
- hashTable.put("doc", geomHolder[0]);
- }
- };
-
- AsynchClientTask[] finalTasks = afterTasks;
- if (finalTasks == null) {
- finalTasks = new AsynchClientTask[] { getSaveImageAndGeometryTask() };
- }
- AsynchClientTask[] tasks = new AsynchClientTask[2 + finalTasks.length];
- tasks[0] = task1;
- tasks[1] = task2;
- System.arraycopy(finalTasks, 0, tasks, 2, finalTasks.length);
- ClientTaskDispatcher.dispatch((Component) hashTable.get(GUI_PARENT), hashTable, tasks, false, false,
- null, true);
- }
- };
- Vector tasksV = new Vector();
- if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH) {
- tasksV.addAll(Arrays.asList(new AsynchClientTask[] { parseImageTask, finishTask }));
- } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC) {
- tasksV.addAll(Arrays.asList(new AsynchClientTask[] { parseImageTask, finishTask }));
- } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE) {
- tasksV.addAll(Arrays.asList(new AsynchClientTask[] { parseImageTask, resizeImageTask, finishTask }));
- } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE) {
- tasksV.addAll(Arrays.asList(new AsynchClientTask[] { selectImageFileTask, parseImageTask,
- queryImageResizeTask, importFileImageTask/* resizes */, finishTask }));
- }
+ }
+
+ public AsynchClientTask[] createNewGeometryTasks(final TopLevelWindowManager requester,
+ final VCDocument.DocumentCreationInfo documentCreationInfo, final AsynchClientTask[] afterTasks,
+ final String okButtonText) {
+
+ if (!isImportGeometryType(documentCreationInfo)) {
+ throw new IllegalArgumentException("Analytic geometry not implemented.");
+
+ }
+
+ AsynchClientTask selectImageFileTask = getSelectImageFileTask(requester.getComponent(), this.getUserPreferences());
+
+ final String INITIAL_ANNOTATION = "INITIAL_ANNOTATION";
+ final String NEW_IMAGE_SIZE_INFO = "NEW_IMAGE_SIZE_INFO";
+ final String FD_TIMEPOINTS = "FD_TIMEPOINTS";
+
+ AsynchClientTask parseImageTask = getParseImageTask(requester.getComponent(), documentCreationInfo, this.getMdiManager());
+
+ AsynchClientTask getFieldDataImageParams = new AsynchClientTask("Getting DB Image parameters...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
+ PDEDataContext pdeDataContext = ClientRequestManager.this.getMdiManager().getFieldDataWindowManager()
+ .getPDEDataContext(docInfo.getExternalDataID(), null);
+ CartesianMesh mesh = pdeDataContext.getCartesianMesh();
+ ISize meshISize = new ISize(mesh.getSizeX(), mesh.getSizeY(), mesh.getSizeZ());
+ double[] timePoints = pdeDataContext.getTimePoints();
+ hashTable.put(FD_MESH, mesh);
+ hashTable.put(FD_MESHISIZE, meshISize);
+ hashTable.put(FD_TIMEPOINTS, timePoints);
+ }
+ };
+ AsynchClientTask queryImageResizeTask = new AsynchClientTask("Query File Image Resize...",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ String importSourceName = (String) hashTable.get(IMPORT_SOURCE_NAME);
+ if (hashTable.get(ORIG_IMAGE_SIZE_INFO) != null) {// from file
+ ImageSizeInfo newImagesiSizeInfo = queryImageResize(requester.getComponent(),
+ (ImageSizeInfo) hashTable.get(ORIG_IMAGE_SIZE_INFO), true);
+ hashTable.put(NEW_IMAGE_SIZE_INFO, newImagesiSizeInfo);
+ } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {// from fielddata
+ VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
+ double[] fieldDataTimes = (double[]) hashTable.get(FD_TIMEPOINTS);
+ hashTable.remove(FD_TIMEPOINTS);
+ ISize fieldDataISize = (ISize) hashTable.get(FD_MESHISIZE);
+ ImageSizeInfo origImageSizeInfo = new ImageSizeInfo(importSourceName, fieldDataISize, 1,
+ fieldDataTimes, null);
+ ImageSizeInfo newImagesiSizeInfo = queryImageResize(requester.getComponent(), origImageSizeInfo,
+ true);
+ hashTable.put(NEW_IMAGE_SIZE_INFO, newImagesiSizeInfo);
+ hashTable.put(IMPORT_SOURCE_NAME,
+ "FieldData: " + docInfo.getExternalDataID().getName() + " varName=" + docInfo.getVarName()
+ + " timeIndex="
+ + newImagesiSizeInfo.getTimePoints()[newImagesiSizeInfo.getSelectedTimeIndex()]);
+ }
+ }
+ };
+
+ AsynchClientTask importFileImageTask = getImportFileImageTask(documentCreationInfo);
+
+ AsynchClientTask resizeImageTask = getResizeImageTask(documentCreationInfo);
+
+ AsynchClientTask finishTask = new AsynchClientTask("Finishing...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(final Hashtable hashTable) throws Exception {
+ this.getClientTaskStatusSupport().setMessage("Initializing...");
+ final ROIMultiPaintManager roiMultiPaintManager = new ROIMultiPaintManager();
+ roiMultiPaintManager.setDocumentManager(ClientRequestManager.this.getDocumentManager());
+ roiMultiPaintManager.initROIAndUnderlay((FieldDataFileOperationSpec) hashTable.get(FDFOS));
+ final Geometry[] geomHolder = new Geometry[1];
+ final VCPixelClass[] postProcessPixelClasses = (VCPixelClass[]) hashTable.get(VCPIXELCLASSES);
+ AsynchClientTask task1 = new AsynchClientTask("edit geometry", AsynchClientTask.TASKTYPE_SWING_BLOCKING,
+ false) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ geomHolder[0] = roiMultiPaintManager.showGUI(okButtonText,
+ (String) hashTable.get(IMPORT_SOURCE_NAME), (Component) hashTable.get(GUI_PARENT),
+ (String) hashTable.get(INITIAL_ANNOTATION), postProcessPixelClasses,
+ ClientRequestManager.this.getUserPreferences(),
+ (hashTable.get(BioModelWindowManager.FIELD_DATA_FLAG) != null && ((Boolean) hashTable.get(BioModelWindowManager.FIELD_DATA_FLAG)).booleanValue()));
+ }
+ };
+ AsynchClientTask task2 = new AsynchClientTask("update geometry",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ // Create default name for image
+ String dateTimeString = BeanUtils.generateDateTimeString();
+ geomHolder[0].getGeometrySpec().getImage().setName("img_" + dateTimeString);
+ geomHolder[0].setName("geom_" + dateTimeString);
+ // cause update in this thread so later swing threads won't be delayed
+ geomHolder[0].precomputeAll(new GeometryThumbnailImageFactoryAWT());
+ hashTable.put("doc", geomHolder[0]);
+ }
+ };
+
+ AsynchClientTask[] finalTasks = afterTasks;
+ if (finalTasks == null) {
+ finalTasks = new AsynchClientTask[]{ClientRequestManager.this.getSaveImageAndGeometryTask()};
+ }
+ AsynchClientTask[] tasks = new AsynchClientTask[2 + finalTasks.length];
+ tasks[0] = task1;
+ tasks[1] = task2;
+ System.arraycopy(finalTasks, 0, tasks, 2, finalTasks.length);
+ ClientTaskDispatcher.dispatch((Component) hashTable.get(GUI_PARENT), hashTable, tasks, false, false,
+ null, true);
+ }
+ };
+ Vector tasksV = new Vector();
+ if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH) {
+ tasksV.addAll(Arrays.asList(parseImageTask, finishTask));
+ } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC) {
+ tasksV.addAll(Arrays.asList(parseImageTask, finishTask));
+ } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE) {
+ tasksV.addAll(Arrays.asList(parseImageTask, resizeImageTask, finishTask));
+ } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE) {
+ tasksV.addAll(Arrays.asList(selectImageFileTask, parseImageTask,
+ queryImageResizeTask, importFileImageTask/* resizes */, finishTask));
+ }
// else if(documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER){
// tasksV.addAll(Arrays.asList(new AsynchClientTask[] {parseImageTask,queryImageResizeTask,importFileImageTask/*resizes*/,finishTask}));
// }
- else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {
- tasksV.addAll(Arrays.asList(new AsynchClientTask[] { getFieldDataImageParams, queryImageResizeTask,
- parseImageTask, resizeImageTask, finishTask }));
- }
- return tasksV.toArray(new AsynchClientTask[0]);
- }
-
- public static ISize getISizeFromUser(Component guiParent, ISize initISize, String textMessage)
- throws UserCancelException {
- Integer imageDimension = (initISize == null ? null
- : (initISize.getX() != 1 ? 1 : 0) + (initISize.getY() != 1 ? 1 : 0) + (initISize.getZ() != 1 ? 1 : 0));
- if (imageDimension != null && (imageDimension < 1 || imageDimension > 3)) {
- throw new IllegalArgumentException("Dimension must be 1, 2 or 3.");
- }
- try {
- int xsize = (imageDimension == null ? -1 : initISize.getX());
- int ysize = (imageDimension == null ? -1 : initISize.getY());
- int zsize = (imageDimension == null ? -1 : initISize.getZ());
- do {
- String result = (imageDimension == null ? "256,256,8" : xsize + "," + ysize + "," + zsize);
- result = DialogUtils.showInputDialog0(guiParent, textMessage, result);
- String tempResult = result;
- try {
- if (result == null || result.length() == 0) {
- result = "";
- throw new Exception("No size values entered.");
- }
- xsize = Integer.parseInt(tempResult.substring(0, tempResult.indexOf(",")));
- tempResult = tempResult.substring(tempResult.indexOf(",") + 1, tempResult.length());
- ysize = Integer.parseInt(tempResult.substring(0, tempResult.indexOf(",")));
- tempResult = tempResult.substring(tempResult.indexOf(",") + 1, tempResult.length());
- zsize = Integer.parseInt(tempResult);
- if (imageDimension != null) {
- if (imageDimension == 2 && zsize != 1) {
- throw new Exception("Dimension " + imageDimension + " must have z = 1.");
- } else if (imageDimension == 1 && zsize != 1 && ysize != 1) {
- throw new Exception("Dimension " + imageDimension + " must have z = 1 and y = 1.");
- }
- }
- ISize isize = new ISize(xsize, ysize, zsize);
- if (isize.getXYZ() <= 0) {
- throw new Exception("Total pixels (" + xsize + "*" + ysize + "*" + zsize + ") cannot be <=0.");
- }
- return isize;
- } catch (Exception e) {
- DialogUtils.showErrorDialog(guiParent, "Error entering starting sizes\n" + e.getMessage(), e);
- }
- } while (true);
- } catch (UtilCancelException e2) {
- throw UserCancelException.CANCEL_GENERIC;
- }
-
- }
-
- public static ImageSizeInfo queryImageResize(final Component requester, final ImageSizeInfo origImageSizeInfo,
- boolean bFullMode) {
- ImageResizePanel imageResizePanel = new ImageResizePanel();
- imageResizePanel.init(origImageSizeInfo, bFullMode);
- imageResizePanel.setPreferredSize(new Dimension(400, 200));
- while (true) {
- int flag = DialogUtils.showComponentOKCancelDialog(requester, imageResizePanel,
- "Optionally convert imported images.");
- if (flag != JOptionPane.OK_OPTION) {
- throw UserCancelException.CANCEL_GENERIC;
- }
- try {
- ImageSizeInfo imagesizeInfo = imageResizePanel.getNewImageSizeInfo();
- return imagesizeInfo;
- } catch (Exception e) {
- e.printStackTrace();
- DialogUtils.showErrorDialog(requester, "Error getting x,y,z: " + e.getMessage());
- }
- }
- }
-
- private static void resizeImage(FieldDataFileOperationSpec fdfos, ISize newImagesISize, int imageType)
- throws Exception {
- final int ORIG_XYSIZE = fdfos.isize.getX() * fdfos.isize.getY();
- try {
- int xsize = newImagesISize.getX();
- int ysize = newImagesISize.getY();
- double scaleFactor = (double) newImagesISize.getX() / (double) fdfos.isize.getX();
- if (xsize != fdfos.isize.getX() || ysize != fdfos.isize.getY()) {
- int numChannels = fdfos.shortSpecData[0].length;// this normally contains different variables but is
- // used for channels here
- // resize each z section to xsize,ysize
- AffineTransform scaleAffineTransform = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
- AffineTransformOp scaleAffineTransformOp = new AffineTransformOp(scaleAffineTransform,
- AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
- short[][][] resizeData = new short[1][numChannels][fdfos.isize.getZ() * xsize * ysize];
- for (int c = 0; c < numChannels; c++) {
- BufferedImage originalImage = new BufferedImage(fdfos.isize.getX(), fdfos.isize.getY(),
- BufferedImage.TYPE_USHORT_GRAY);
- BufferedImage scaledImage = new BufferedImage(xsize, ysize, BufferedImage.TYPE_USHORT_GRAY);
- for (int z = 0; z < fdfos.isize.getZ(); z++) {
- short[] originalImageBuffer = ((DataBufferUShort) (originalImage.getRaster().getDataBuffer()))
- .getData();
- System.arraycopy(fdfos.shortSpecData[0][c], z * ORIG_XYSIZE, originalImageBuffer, 0,
- ORIG_XYSIZE);
- scaleAffineTransformOp.filter(originalImage, scaledImage);
- short[] scaledImageBuffer = ((DataBufferUShort) (scaledImage.getRaster().getDataBuffer()))
- .getData();
- System.arraycopy(scaledImageBuffer, 0, resizeData[0][c], z * xsize * ysize, xsize * ysize);
- }
- }
- fdfos.isize = new ISize(xsize, ysize, fdfos.isize.getZ());
- fdfos.shortSpecData = resizeData;
- }
- } catch (Exception e) {
- throw new Exception("Error scaling imported image:\n" + e.getMessage());
- }
- }
-
- public AsynchClientTask[] createNewDocument(final TopLevelWindowManager requester,
- final VCDocument.DocumentCreationInfo documentCreationInfo) {// throws UserCancelException, Exception {
- /* asynchronous and not blocking any window */
- AsynchClientTask[] taskArray = null;
-
- final int createOption = documentCreationInfo.getOption();
- switch (documentCreationInfo.getDocumentType()) {
- case BIOMODEL_DOC: {
- AsynchClientTask task1 = new AsynchClientTask("creating biomodel",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- BioModel bioModel = createDefaultBioModelDocument(null);
- hashTable.put("doc", bioModel);
- }
- };
- taskArray = new AsynchClientTask[] { task1 };
- break;
- }
- case MATHMODEL_DOC: {
- if ((createOption == VCDocument.MATH_OPTION_NONSPATIAL)
- || (createOption == VCDocument.MATH_OPTION_SPATIAL_EXISTS)) {
- AsynchClientTask task2 = new AsynchClientTask("creating mathmodel",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- Geometry geometry = null;
- if (createOption == VCDocument.MATH_OPTION_NONSPATIAL) {
- geometry = new Geometry("Untitled", 0);
- } else {
- geometry = (Geometry) hashTable.get(GEOMETRY_KEY);
- }
- MathModel mathModel = createMathModel("Untitled", geometry);
- mathModel.setName("MathModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1));
- hashTable.put("doc", mathModel);
- }
- };
- if (createOption == VCDocument.MATH_OPTION_SPATIAL_EXISTS) {
- AsynchClientTask task1 = createSelectDocTask(requester);
- AsynchClientTask task1b = createSelectLoadGeomTask(requester);
- taskArray = new AsynchClientTask[] { task1, task1b, task2 };
- } else {
- taskArray = new AsynchClientTask[] { task2 };
- }
- break;
- } else if (createOption == VCDocument.MATH_OPTION_FROMBIOMODELAPP) {
-
- AsynchClientTask task1 = new AsynchClientTask("select biomodel application",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- // spatial or non-spatial
- BioModelInfo bioModelInfo = (BioModelInfo) DialogUtils.getDBTreePanelSelection(
- requester.getComponent(),
- getMdiManager().getDatabaseWindowManager().getBioModelDbTreePanel(), "Open",
- "Select BioModel");
- if (bioModelInfo != null) { // may throw UserCancelException
- hashTable.put("bioModelInfo", bioModelInfo);
- }
- }
- };
- AsynchClientTask task2 = new AsynchClientTask("find sim contexts in biomodel application",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- // spatial or non-spatial
- // Get the simContexts in the corresponding BioModel
- BioModelInfo bioModelInfo = (BioModelInfo) hashTable.get("bioModelInfo");
- SimulationContext[] simContexts = getDocumentManager().getBioModel(bioModelInfo)
- .getSimulationContexts();
- if (simContexts != null) { // may throw UserCancelException
- hashTable.put("simContexts", simContexts);
- }
- }
- };
- AsynchClientTask task3 = new AsynchClientTask("create math model from biomodel application",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- SimulationContext[] simContexts = (SimulationContext[]) hashTable.get("simContexts");
- String[] simContextNames = new String[simContexts.length];
-
- if (simContextNames.length == 0) {
- throw new RuntimeException("no application is available");
- } else {
- for (int i = 0; i < simContexts.length; i++) {
- simContextNames[i] = simContexts[i].getName();
- }
- Component component = requester.getComponent();
- // Get the simContext names, so that user can choose which simContext math to
- // import
- String simContextChoice = (String) PopupGenerator.showListDialog(component, simContextNames,
- "Please select Application");
- if (simContextChoice == null) {
- throw UserCancelException.CANCEL_DB_SELECTION;
- }
- SimulationContext chosenSimContext = null;
- for (int i = 0; i < simContexts.length; i++) {
- if (simContexts[i].getName().equals(simContextChoice)) {
- chosenSimContext = simContexts[i];
- break;
- }
- }
- Objects.requireNonNull(chosenSimContext);
-
- BioModelInfo bioModelInfo = (BioModelInfo) hashTable.get("bioModelInfo");
- // Get corresponding mathDesc to create new mathModel and return.
- String newName = bioModelInfo.getVersion().getName() + "_" + chosenSimContext.getName();
- MathDescription bioMathDesc = chosenSimContext.getMathDescription();
- MathDescription newMathDesc = null;
- newMathDesc = new MathDescription(newName + "_" + (new Random()).nextInt());
-
- newMathDesc.setGeometry(bioMathDesc.getGeometry());
- newMathDesc.read_database(new CommentStringTokenizer(bioMathDesc.getVCML_database()));
- newMathDesc.isValid();
-
- MathModel newMathModel = new MathModel(null);
- newMathModel.setName(newName);
- newMathModel.setMathDescription(newMathDesc);
- hashTable.put("doc", newMathModel);
- }
- }
- };
- taskArray = new AsynchClientTask[] { task1, task2, task3 };
- break;
- } else {
- throw new RuntimeException(
- "Unknown MathModel Document creation option value=" + documentCreationInfo.getOption());
- }
- }
- case GEOMETRY_DOC: {
- if (createOption == VCDocument.GEOM_OPTION_1D || createOption == VCDocument.GEOM_OPTION_2D
- || createOption == VCDocument.GEOM_OPTION_3D) {
- // analytic
- AsynchClientTask task1 = new AsynchClientTask("creating analytic geometry",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- Geometry geometry = new Geometry(
- "Geometry" + (getMdiManager().getNumCreatedDocumentWindows() + 1),
- documentCreationInfo.getOption());
- geometry.getGeometrySpec()
- .addSubVolume(new AnalyticSubVolume("subdomain0", new Expression(1.0)));
- geometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
- hashTable.put("doc", geometry);
- }
- };
- taskArray = new AsynchClientTask[] { task1 };
- break;
- }
- if (createOption == VCDocument.GEOM_OPTION_CSGEOMETRY_3D) {
- // constructed solid geometry
- AsynchClientTask task1 = new AsynchClientTask("creating constructed solid geometry",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- Geometry geometry = new Geometry(
- "Geometry" + (getMdiManager().getNumCreatedDocumentWindows() + 1), 3);
- Extent extent = geometry.getExtent();
- if (extent != null) {
- // create a CSGPrimitive of type cube and scale it to the 'extent' components.
- // Use this as the default or background CSGObject (subdomain).
- // This can be considered as the equivalent of subdomain (with expression) 1.0
- // for analyticSubvolume.
- // basic cube
- CSGPrimitive cube = new CSGPrimitive("cube", CSGPrimitive.PrimitiveType.CUBE);
- // scaled cube
- double x = extent.getX();
- double y = extent.getY();
- double z = extent.getZ();
- CSGScale scaledCube = new CSGScale("scale", new Vect3d(x / 2.0, y / 2.0, z / 2.0));
- scaledCube.setChild(cube);
- // translated scaled cube
- CSGTranslation translatedScaledCube = new CSGTranslation("translation",
- new Vect3d(x / 2, y / 2, z / 2));
- translatedScaledCube.setChild(scaledCube);
- CSGObject csgObject = new CSGObject(null, "subdomain0", 0);
- csgObject.setRoot(translatedScaledCube);
- geometry.getGeometrySpec().addSubVolume(csgObject, false);
- geometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
- hashTable.put("doc", geometry);
- }
- }
- };
- taskArray = new AsynchClientTask[] { task1 };
- break;
- } else {
- throw new RuntimeException(
- "Unknown Geometry Document creation option value=" + documentCreationInfo.getOption());
- }
- }
- default: {
- throw new RuntimeException("Unknown default document type: " + documentCreationInfo.getDocumentType());
- }
- }
- return taskArray;
- }
-
- private static final int MAX_NUMBER_OF_COLORS_IMPORTED_FILE = 256;
-
- public static VCImage createVCImageFromUnsignedShorts(short[] dataToSegment, Extent extent, ISize isize,
- BitSet uniquePixelBS) throws Exception {
- // auto segment
-
- int minVal = dataToSegment[0] & 0x0000FFFF;
- int maxVal = minVal;
- for (int i = 0; i < dataToSegment.length; i++) {
- int usIntVal = (int) (dataToSegment[i] & 0x0000FFFF);
- minVal = Math.min(usIntVal, minVal);
- maxVal = Math.max(usIntVal, maxVal);
- }
- byte[] byteData = new byte[dataToSegment.length];
-
- if (maxVal >= MAX_NUMBER_OF_COLORS_IMPORTED_FILE) {
- if (uniquePixelBS.cardinality() <= MAX_NUMBER_OF_COLORS_IMPORTED_FILE) {
- int index = 0;
- int[] indexRef = new int[(int) Math.pow(2, Short.SIZE)];
- Arrays.fill(indexRef, -1);
- for (int i = 0; i < indexRef.length; i++) {
- if (uniquePixelBS.get(i)) {
- indexRef[i] = index;
- index++;
- }
- }
- for (int i = 0; i < dataToSegment.length; i++) {
- byteData[i] = (byte) indexRef[(int) (dataToSegment[i] & 0x0000FFFF)];
- }
- } else {
- for (int i = 0; i < dataToSegment.length; i++) {
- byteData[i] = (byte) (0xFF & (int) ((double) (dataToSegment[i] - minVal)
- / (double) (maxVal - minVal) * (MAX_NUMBER_OF_COLORS_IMPORTED_FILE - 1)));
- }
- }
- } else {
- for (int i = 0; i < byteData.length; i++) {
- byteData[i] = (byte) (dataToSegment[i] & 0xFF);
- }
- }
- VCImage autoSegmentVCImage = new VCImageUncompressed(null, byteData, extent, isize.getX(), isize.getY(),
- isize.getZ());
- return autoSegmentVCImage;
-
- }
-
- public void curateDocument(final VCDocumentInfo documentInfo, final int curateType,
- final TopLevelWindowManager requester) {
-
- if (documentInfo != null) {
- // see if we have this open
- String documentID = documentInfo.getVersion().getVersionKey().toString();
- if (getMdiManager().haveWindow(documentID)) {
- // already open, refuse
- PopupGenerator.showErrorDialog(requester,
- "Selected edition is open, cannot " + CurateSpec.CURATE_TYPE_NAMES[curateType]);
- return;
- } else {
- // don't have it open, try to CURATE it
- int confirm = PopupGenerator.showComponentOKCancelDialog(requester.getComponent(),
- new JTextArea(CurateSpec.CURATE_TYPE_ACTIONS[curateType]
- + " cannot be undone without VCELL administrative assistance.\n"
- + CurateSpec.CURATE_TYPE_STATES[curateType]
- + " versions of documents cannot be deleted without VCELL administrative assistance.\n"
- + (curateType == CurateSpec.PUBLISH ? CurateSpec.CURATE_TYPE_STATES[curateType]
- + " versions of documents MUST remain publically accessible to other VCELL users.\n"
- : "")
- + "Do you want to " + CurateSpec.CURATE_TYPE_NAMES[curateType] + " document '"
- + documentInfo.getVersion().getName() + "'" + "\nwith version date '"
- + documentInfo.getVersion().getDate().toString() + "'?"),
- "WARNING -- " + CurateSpec.CURATE_TYPE_ACTIONS[curateType] + " operation cannot be undone");
- if (confirm == JOptionPane.OK_OPTION) {
- AsynchClientTask task1 = new AsynchClientTask(
- CurateSpec.CURATE_TYPE_ACTIONS[curateType] + " document...",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- if (documentInfo instanceof BioModelInfo) {
- getDocumentManager().curate(new CurateSpec((BioModelInfo) documentInfo, curateType));
- } else if (documentInfo instanceof MathModelInfo) {
- getDocumentManager().curate(new CurateSpec((MathModelInfo) documentInfo, curateType));
- } else {
- throw new RuntimeException(CurateSpec.CURATE_TYPE_ACTIONS[curateType]
- + " not supported for VCDocumentInfo type "
- + documentInfo.getClass().getName());
- }
- }
- };
- ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
- new AsynchClientTask[] { task1 }, false);
- } else {
- // user canceled
- return;
- }
- }
- } else {
- // nothing selected
- return;
- }
- }
-
- public void deleteDocument(final VCDocumentInfo documentInfo, final TopLevelWindowManager requester) {
- deleteDocument(documentInfo, requester, false);
- }
-
- public void deleteDocument(final VCDocumentInfo documentInfo, final TopLevelWindowManager requester,
- boolean bDontAsk) {
- if (documentInfo != null) {
- // see if we have this open
- String documentID = documentInfo.getVersion().getVersionKey().toString();
- if (getMdiManager().haveWindow(documentID)) {
- // already open, refuse
- PopupGenerator.showErrorDialog(requester, "Selected edition is open, cannot delete");
- return;
- } else {
- // don't have it open, try to delete it
- String confirm = UserMessage.OPTION_CANCEL;
- if (bDontAsk) {
- confirm = UserMessage.OPTION_DELETE;
- } else {
- SimpleDateFormat sdf = new SimpleDateFormat(BeanUtils.vcDateFormat);
- confirm = PopupGenerator.showWarningDialog(requester, getUserPreferences(),
- UserMessage.warn_deleteDocument, documentInfo.getVersion().getName() + " "
- + sdf.format(documentInfo.getVersion().getDate()));
- }
- if (confirm.equals(UserMessage.OPTION_DELETE)) {
- AsynchClientTask task1 = new AsynchClientTask("Deleting document...",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- if (documentInfo instanceof BioModelInfo) {
- getDocumentManager().delete((BioModelInfo) documentInfo);
- } else if (documentInfo instanceof MathModelInfo) {
- getDocumentManager().delete((MathModelInfo) documentInfo);
- } else if (documentInfo instanceof GeometryInfo) {
- getDocumentManager().delete((GeometryInfo) documentInfo);
- } else {
- throw new RuntimeException("delete not supported for VCDocumentInfo type "
- + documentInfo.getClass().getName());
- }
- }
- };
- ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
- new AsynchClientTask[] { task1 }, false);
- } else {
- // user canceled
- return;
- }
- }
- } else {
- // nothing selected
- return;
- }
- }
-
- /**
- * hashtable key for data bytes of file
- */
- private final static String BYTES_KEY = "bytes";
-
- /**
- * Comment
- */
- public static void downloadExportedData(final Component requester, final UserPreferences userPrefs,
- final ExportEvent evt) {
- TreeSet exportsRecord = getExportsRecord();
- if (exportsRecord.contains(evt.getJobID() + "")) {
- return;
- }
- if (evt.getLocation().toLowerCase().endsWith("." + N5Specs.n5Suffix)){
- return;
- }
- AsynchClientTask task1 = new AsynchClientTask("Retrieving data from '" + evt.getLocation() + "'",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- final Exception[] excArr = new Exception[] { null };
- final boolean[] bFlagArr = new boolean[] { false };
- final ByteArrayOutputStream[] baosArr = new ByteArrayOutputStream[1];
- final HttpGet[] httpGetArr = new HttpGet[1];
- // Start download of exported file in separate thread that is interruptible
- // (apache HTTPClient)
- Thread interruptible = new Thread(new Runnable() {
- @Override
- public void run() {
- if (getClientTaskStatusSupport() != null) {
- getClientTaskStatusSupport().setMessage("downloading data...");
- }
- CloseableHttpClient httpclient = HttpClients.createDefault();
- httpGetArr[0] = new HttpGet(evt.getLocation());
- CloseableHttpResponse response = null;
- try {
- response = httpclient.execute(httpGetArr[0]);
- if (response.getStatusLine() != null
- && (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
- throw new Exception(
- evt.getLocation() + " " + response.getStatusLine().getReasonPhrase());
- }
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- long size = entity.getContentLength();
- InputStream instream = entity.getContent();
- try {
- if (size > 0) {
- baosArr[0] = new ByteArrayOutputStream((int) size);
- } else {
- baosArr[0] = new ByteArrayOutputStream();
- }
- IOUtils.copy(instream, baosArr[0]);
- } finally {
- instream.close();
- }
- }
-
- } catch (Exception e) {
- excArr[0] = e;
- } finally {
- if (response != null) {
- try {
- response.close();
- } catch (Exception e) {
- }
- }
- if (httpclient != null) {
- try {
- httpclient.close();
- } catch (Exception e) {
- }
- }
- bFlagArr[0] = true;
- }
- }
- });
- interruptible.start();
- // Wait for download to 1-finish, 2-fail or 3-be cancelled by user
- while (!bFlagArr[0]) {
- if (getClientTaskStatusSupport() != null && getClientTaskStatusSupport().isInterrupted()) {// user
- // cancelled
- if (httpGetArr[0] != null) {
- httpGetArr[0].abort();
- }
- throw UserCancelException.CANCEL_GENERIC;
- }
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {// caused by pressing 'cancel' button on progresspopup
- if (httpGetArr[0] != null) {
- httpGetArr[0].abort();
- }
- if (getClientTaskStatusSupport() != null && getClientTaskStatusSupport().isInterrupted()) {
- throw UserCancelException.CANCEL_GENERIC;
- }
- }
- }
- if (excArr[0] != null) {// download failed
- throw excArr[0];
- }
- //
- // finished downloading, either save to file or send to ImageJ directly
- //
- if (evt.getFormat() == null || !evt.getFormat().equals("IMAGEJ")) {
- // save for file save operations
- hashTable.put(BYTES_KEY, baosArr[0].toByteArray());
- }
- }
- };
- AsynchClientTask task2 = new AsynchClientTask("selecting file to save",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- // user pref could be null if trying local export
- String defaultPath = getPreferredPath(userPrefs);
- final VCFileChooser fileChooser = new VCFileChooser(defaultPath);
- fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
- fileChooser.setMultiSelectionEnabled(false);
- String name = evt.getDataIdString();
- String suffix = null;
- if (evt.getLocation().toLowerCase().endsWith(".mov")) {
- fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_MOV);
- fileChooser.setFileFilter(FileFilters.FILE_FILTER_MOV);
-
- suffix = "_exported.mov";
- } else if (evt.getLocation().toLowerCase().endsWith(".gif")) {
- fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_GIF);
- fileChooser.setFileFilter(FileFilters.FILE_FILTER_GIF);
-
- suffix = "_exported.gif";
- } else if (evt.getLocation().toLowerCase().endsWith(".jpeg")) {
- fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_JPEG);
- fileChooser.setFileFilter(FileFilters.FILE_FILTER_JPEG);
-
- suffix = "_exported.jpeg";
- } else if (evt.getLocation().toLowerCase().endsWith(".hdf5")) {
- fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_HDF5);
- fileChooser.setFileFilter(FileFilters.FILE_FILTER_HDF5);
-
- suffix = "_exported.hdf5";
- } else {
- fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_ZIP);
- fileChooser.setFileFilter(FileFilters.FILE_FILTER_ZIP);
-
- suffix = "_exported.zip";
- }
- File file = new File(name + suffix);
- if (file.exists()) {
- int count = 0;
- do {
- file = new File(name + "_" + count + suffix);
- count++;
- } while (file.exists());
- }
-
- fileChooser.setSelectedFile(file);
- fileChooser.setDialogTitle("Save exported dataset...");
- int approve = fileChooser.showSaveDialog(requester);
- if (approve == JFileChooser.APPROVE_OPTION) {
- hashTable.put("selectedFile", fileChooser.getSelectedFile());
- } else {
- fileChooser.setSelectedFile(null);
- }
- }
- };
- AsynchClientTask task3 = new AsynchClientTask("saving to file", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- addExportRecord(evt.getJobID() + "");
-
- File selectedFile = (File) hashTable.get("selectedFile");
- if (selectedFile == null) {
- return;
- }
- setPreferredPath(userPrefs, selectedFile);
+ else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {
+ tasksV.addAll(Arrays.asList(getFieldDataImageParams, queryImageResizeTask,
+ parseImageTask, resizeImageTask, finishTask));
+ }
+ return tasksV.toArray(new AsynchClientTask[0]);
+ }
+
+ public static ISize getISizeFromUser(Component guiParent, ISize initISize, String textMessage)
+ throws UserCancelException {
+ Integer imageDimension = (initISize == null ? null
+ : (initISize.getX() != 1 ? 1 : 0) + (initISize.getY() != 1 ? 1 : 0) + (initISize.getZ() != 1 ? 1 : 0));
+ if (imageDimension != null && (imageDimension < 1 || imageDimension > 3)) {
+ throw new IllegalArgumentException("Dimension must be 1, 2 or 3.");
+ }
+ try {
+ int xsize = (imageDimension == null ? -1 : initISize.getX());
+ int ysize = (imageDimension == null ? -1 : initISize.getY());
+ int zsize = (imageDimension == null ? -1 : initISize.getZ());
+ do {
+ String result = (imageDimension == null ? "256,256,8" : xsize + "," + ysize + "," + zsize);
+ result = DialogUtils.showInputDialog0(guiParent, textMessage, result);
+ String tempResult = result;
+ try {
+ if (result == null || result.length() == 0) {
+ result = "";
+ throw new Exception("No size values entered.");
+ }
+ xsize = Integer.parseInt(tempResult.substring(0, tempResult.indexOf(",")));
+ tempResult = tempResult.substring(tempResult.indexOf(",") + 1);
+ ysize = Integer.parseInt(tempResult.substring(0, tempResult.indexOf(",")));
+ tempResult = tempResult.substring(tempResult.indexOf(",") + 1);
+ zsize = Integer.parseInt(tempResult);
+ if (imageDimension != null) {
+ if (imageDimension == 2 && zsize != 1) {
+ throw new Exception("Dimension " + imageDimension + " must have z = 1.");
+ } else if (imageDimension == 1 && zsize != 1 && ysize != 1) {
+ throw new Exception("Dimension " + imageDimension + " must have z = 1 and y = 1.");
+ }
+ }
+ ISize isize = new ISize(xsize, ysize, zsize);
+ if (isize.getXYZ() <= 0) {
+ throw new Exception("Total pixels (" + xsize + "*" + ysize + "*" + zsize + ") cannot be <=0.");
+ }
+ return isize;
+ } catch (Exception e) {
+ DialogUtils.showErrorDialog(guiParent, "Error entering starting sizes\n" + e.getMessage(), e);
+ }
+ } while (true);
+ } catch (UtilCancelException e2) {
+ throw UserCancelException.CANCEL_GENERIC;
+ }
+
+ }
+
+ public static ImageSizeInfo queryImageResize(final Component requester, final ImageSizeInfo origImageSizeInfo,
+ boolean bFullMode) {
+ ImageResizePanel imageResizePanel = new ImageResizePanel();
+ imageResizePanel.init(origImageSizeInfo, bFullMode);
+ imageResizePanel.setPreferredSize(new Dimension(400, 200));
+ while (true) {
+ int flag = DialogUtils.showComponentOKCancelDialog(requester, imageResizePanel,
+ "Optionally convert imported images.");
+ if (flag != JOptionPane.OK_OPTION) {
+ throw UserCancelException.CANCEL_GENERIC;
+ }
+ try {
+ ImageSizeInfo imagesizeInfo = imageResizePanel.getNewImageSizeInfo();
+ return imagesizeInfo;
+ } catch (Exception e) {
+ e.printStackTrace();
+ DialogUtils.showErrorDialog(requester, "Error getting x,y,z: " + e.getMessage());
+ }
+ }
+ }
+
+ private static void resizeImage(FieldDataFileOperationSpec fdfos, ISize newImagesISize, int imageType)
+ throws Exception {
+ final int ORIG_XYSIZE = fdfos.isize.getX() * fdfos.isize.getY();
+ try {
+ int xsize = newImagesISize.getX();
+ int ysize = newImagesISize.getY();
+ double scaleFactor = (double) newImagesISize.getX() / (double) fdfos.isize.getX();
+ if (xsize != fdfos.isize.getX() || ysize != fdfos.isize.getY()) {
+ int numChannels = fdfos.shortSpecData[0].length;// this normally contains different variables but is
+ // used for channels here
+ // resize each z section to xsize,ysize
+ AffineTransform scaleAffineTransform = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
+ AffineTransformOp scaleAffineTransformOp = new AffineTransformOp(scaleAffineTransform,
+ AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
+ short[][][] resizeData = new short[1][numChannels][fdfos.isize.getZ() * xsize * ysize];
+ for (int c = 0; c < numChannels; c++) {
+ BufferedImage originalImage = new BufferedImage(fdfos.isize.getX(), fdfos.isize.getY(),
+ BufferedImage.TYPE_USHORT_GRAY);
+ BufferedImage scaledImage = new BufferedImage(xsize, ysize, BufferedImage.TYPE_USHORT_GRAY);
+ for (int z = 0; z < fdfos.isize.getZ(); z++) {
+ short[] originalImageBuffer = ((DataBufferUShort) (originalImage.getRaster().getDataBuffer()))
+ .getData();
+ System.arraycopy(fdfos.shortSpecData[0][c], z * ORIG_XYSIZE, originalImageBuffer, 0,
+ ORIG_XYSIZE);
+ scaleAffineTransformOp.filter(originalImage, scaledImage);
+ short[] scaledImageBuffer = ((DataBufferUShort) (scaledImage.getRaster().getDataBuffer()))
+ .getData();
+ System.arraycopy(scaledImageBuffer, 0, resizeData[0][c], z * xsize * ysize, xsize * ysize);
+ }
+ }
+ fdfos.isize = new ISize(xsize, ysize, fdfos.isize.getZ());
+ fdfos.shortSpecData = resizeData;
+ }
+ } catch (Exception e) {
+ throw new Exception("Error scaling imported image:\n" + e.getMessage());
+ }
+ }
+
+ public AsynchClientTask[] createNewDocument(final TopLevelWindowManager requester,
+ final VCDocument.DocumentCreationInfo documentCreationInfo) {// throws UserCancelException, Exception {
+ /* asynchronous and not blocking any window */
+ AsynchClientTask[] taskArray = null;
+
+ final int createOption = documentCreationInfo.getOption();
+ switch (documentCreationInfo.getDocumentType()) {
+ case BIOMODEL_DOC: {
+ AsynchClientTask task1 = new AsynchClientTask("creating biomodel",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ BioModel bioModel = ClientRequestManager.this.createDefaultBioModelDocument(null);
+ hashTable.put("doc", bioModel);
+ }
+ };
+ taskArray = new AsynchClientTask[]{task1};
+ break;
+ }
+ case MATHMODEL_DOC: {
+ if ((createOption == VCDocument.MATH_OPTION_NONSPATIAL)
+ || (createOption == VCDocument.MATH_OPTION_SPATIAL_EXISTS)) {
+ AsynchClientTask task2 = new AsynchClientTask("creating mathmodel",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ Geometry geometry = null;
+ if (createOption == VCDocument.MATH_OPTION_NONSPATIAL) {
+ geometry = new Geometry("Untitled", 0);
+ } else {
+ geometry = (Geometry) hashTable.get(GEOMETRY_KEY);
+ }
+ MathModel mathModel = ClientRequestManager.this.createMathModel("Untitled", geometry);
+ mathModel.setName("MathModel" + (ClientRequestManager.this.getMdiManager().getNumCreatedDocumentWindows() + 1));
+ hashTable.put("doc", mathModel);
+ }
+ };
+ if (createOption == VCDocument.MATH_OPTION_SPATIAL_EXISTS) {
+ AsynchClientTask task1 = this.createSelectDocTask(requester);
+ AsynchClientTask task1b = this.createSelectLoadGeomTask(requester);
+ taskArray = new AsynchClientTask[]{task1, task1b, task2};
+ } else {
+ taskArray = new AsynchClientTask[]{task2};
+ }
+ break;
+ } else if (createOption == VCDocument.MATH_OPTION_FROMBIOMODELAPP) {
+
+ AsynchClientTask task1 = new AsynchClientTask("select biomodel application",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ // spatial or non-spatial
+ BioModelInfo bioModelInfo = (BioModelInfo) DialogUtils.getDBTreePanelSelection(
+ requester.getComponent(),
+ ClientRequestManager.this.getMdiManager().getDatabaseWindowManager().getBioModelDbTreePanel(), "Open",
+ "Select BioModel");
+ if (bioModelInfo != null) { // may throw UserCancelException
+ hashTable.put("bioModelInfo", bioModelInfo);
+ }
+ }
+ };
+ AsynchClientTask task2 = new AsynchClientTask("find sim contexts in biomodel application",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ // spatial or non-spatial
+ // Get the simContexts in the corresponding BioModel
+ BioModelInfo bioModelInfo = (BioModelInfo) hashTable.get("bioModelInfo");
+ SimulationContext[] simContexts = ClientRequestManager.this.getDocumentManager().getBioModel(bioModelInfo)
+ .getSimulationContexts();
+ if (simContexts != null) { // may throw UserCancelException
+ hashTable.put("simContexts", simContexts);
+ }
+ }
+ };
+ AsynchClientTask task3 = new AsynchClientTask("create math model from biomodel application",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ SimulationContext[] simContexts = (SimulationContext[]) hashTable.get("simContexts");
+ String[] simContextNames = new String[simContexts.length];
+
+ if (simContextNames.length == 0) {
+ throw new RuntimeException("no application is available");
+ } else {
+ for (int i = 0; i < simContexts.length; i++) {
+ simContextNames[i] = simContexts[i].getName();
+ }
+ Component component = requester.getComponent();
+ // Get the simContext names, so that user can choose which simContext math to
+ // import
+ String simContextChoice = (String) PopupGenerator.showListDialog(component, simContextNames,
+ "Please select Application");
+ if (simContextChoice == null) {
+ throw UserCancelException.CANCEL_DB_SELECTION;
+ }
+ SimulationContext chosenSimContext = null;
+ for (int i = 0; i < simContexts.length; i++) {
+ if (simContexts[i].getName().equals(simContextChoice)) {
+ chosenSimContext = simContexts[i];
+ break;
+ }
+ }
+ Objects.requireNonNull(chosenSimContext);
+
+ BioModelInfo bioModelInfo = (BioModelInfo) hashTable.get("bioModelInfo");
+ // Get corresponding mathDesc to create new mathModel and return.
+ String newName = bioModelInfo.getVersion().getName() + "_" + chosenSimContext.getName();
+ MathDescription bioMathDesc = chosenSimContext.getMathDescription();
+ MathDescription newMathDesc = null;
+ newMathDesc = new MathDescription(newName + "_" + (new Random()).nextInt());
+
+ newMathDesc.setGeometry(bioMathDesc.getGeometry());
+ newMathDesc.read_database(new CommentStringTokenizer(bioMathDesc.getVCML_database()));
+ newMathDesc.isValid();
+
+ MathModel newMathModel = new MathModel(null);
+ newMathModel.setName(newName);
+ newMathModel.setMathDescription(newMathDesc);
+ hashTable.put("doc", newMathModel);
+ }
+ }
+ };
+ taskArray = new AsynchClientTask[]{task1, task2, task3};
+ break;
+ } else {
+ throw new RuntimeException(
+ "Unknown MathModel Document creation option value=" + documentCreationInfo.getOption());
+ }
+ }
+ case GEOMETRY_DOC: {
+ if (createOption == VCDocument.GEOM_OPTION_1D || createOption == VCDocument.GEOM_OPTION_2D
+ || createOption == VCDocument.GEOM_OPTION_3D) {
+ // analytic
+ AsynchClientTask task1 = new AsynchClientTask("creating analytic geometry",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ Geometry geometry = new Geometry(
+ "Geometry" + (ClientRequestManager.this.getMdiManager().getNumCreatedDocumentWindows() + 1),
+ documentCreationInfo.getOption());
+ geometry.getGeometrySpec()
+ .addSubVolume(new AnalyticSubVolume("subdomain0", new Expression(1.0)));
+ geometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
+ hashTable.put("doc", geometry);
+ }
+ };
+ taskArray = new AsynchClientTask[]{task1};
+ break;
+ }
+ if (createOption == VCDocument.GEOM_OPTION_CSGEOMETRY_3D) {
+ // constructed solid geometry
+ AsynchClientTask task1 = new AsynchClientTask("creating constructed solid geometry",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ Geometry geometry = new Geometry(
+ "Geometry" + (ClientRequestManager.this.getMdiManager().getNumCreatedDocumentWindows() + 1), 3);
+ Extent extent = geometry.getExtent();
+ if (extent != null) {
+ // create a CSGPrimitive of type cube and scale it to the 'extent' components.
+ // Use this as the default or background CSGObject (subdomain).
+ // This can be considered as the equivalent of subdomain (with expression) 1.0
+ // for analyticSubvolume.
+ // basic cube
+ CSGPrimitive cube = new CSGPrimitive("cube", CSGPrimitive.PrimitiveType.CUBE);
+ // scaled cube
+ double x = extent.getX();
+ double y = extent.getY();
+ double z = extent.getZ();
+ CSGScale scaledCube = new CSGScale("scale", new Vect3d(x / 2.0, y / 2.0, z / 2.0));
+ scaledCube.setChild(cube);
+ // translated scaled cube
+ CSGTranslation translatedScaledCube = new CSGTranslation("translation",
+ new Vect3d(x / 2, y / 2, z / 2));
+ translatedScaledCube.setChild(scaledCube);
+ CSGObject csgObject = new CSGObject(null, "subdomain0", 0);
+ csgObject.setRoot(translatedScaledCube);
+ geometry.getGeometrySpec().addSubVolume(csgObject, false);
+ geometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
+ hashTable.put("doc", geometry);
+ }
+ }
+ };
+ taskArray = new AsynchClientTask[]{task1};
+ break;
+ } else {
+ throw new RuntimeException(
+ "Unknown Geometry Document creation option value=" + documentCreationInfo.getOption());
+ }
+ }
+ default: {
+ throw new RuntimeException("Unknown default document type: " + documentCreationInfo.getDocumentType());
+ }
+ }
+ return taskArray;
+ }
+
+ private static final int MAX_NUMBER_OF_COLORS_IMPORTED_FILE = 256;
+
+ public static VCImage createVCImageFromUnsignedShorts(short[] dataToSegment, Extent extent, ISize isize,
+ BitSet uniquePixelBS) throws Exception {
+ // auto segment
+
+ int minVal = dataToSegment[0] & 0x0000FFFF;
+ int maxVal = minVal;
+ for (int i = 0; i < dataToSegment.length; i++) {
+ int usIntVal = dataToSegment[i] & 0x0000FFFF;
+ minVal = Math.min(usIntVal, minVal);
+ maxVal = Math.max(usIntVal, maxVal);
+ }
+ byte[] byteData = new byte[dataToSegment.length];
+
+ if (maxVal >= MAX_NUMBER_OF_COLORS_IMPORTED_FILE) {
+ if (uniquePixelBS.cardinality() <= MAX_NUMBER_OF_COLORS_IMPORTED_FILE) {
+ int index = 0;
+ int[] indexRef = new int[(int) Math.pow(2, Short.SIZE)];
+ Arrays.fill(indexRef, -1);
+ for (int i = 0; i < indexRef.length; i++) {
+ if (uniquePixelBS.get(i)) {
+ indexRef[i] = index;
+ index++;
+ }
+ }
+ for (int i = 0; i < dataToSegment.length; i++) {
+ byteData[i] = (byte) indexRef[dataToSegment[i] & 0x0000FFFF];
+ }
+ } else {
+ for (int i = 0; i < dataToSegment.length; i++) {
+ byteData[i] = (byte) (0xFF & (int) ((double) (dataToSegment[i] - minVal)
+ / (double) (maxVal - minVal) * (MAX_NUMBER_OF_COLORS_IMPORTED_FILE - 1)));
+ }
+ }
+ } else {
+ for (int i = 0; i < byteData.length; i++) {
+ byteData[i] = (byte) (dataToSegment[i] & 0xFF);
+ }
+ }
+ VCImage autoSegmentVCImage = new VCImageUncompressed(null, byteData, extent, isize.getX(), isize.getY(),
+ isize.getZ());
+ return autoSegmentVCImage;
+
+ }
+
+ public void curateDocument(final VCDocumentInfo documentInfo, final int curateType,
+ final TopLevelWindowManager requester) {
+
+ if (documentInfo != null) {
+ // see if we have this open
+ String documentID = documentInfo.getVersion().getVersionKey().toString();
+ if (this.getMdiManager().haveWindow(documentID)) {
+ // already open, refuse
+ PopupGenerator.showErrorDialog(requester,
+ "Selected edition is open, cannot " + CurateSpec.CURATE_TYPE_NAMES[curateType]);
+ } else {
+ // don't have it open, try to CURATE it
+ int confirm = PopupGenerator.showComponentOKCancelDialog(requester.getComponent(),
+ new JTextArea(CurateSpec.CURATE_TYPE_ACTIONS[curateType]
+ + " cannot be undone without VCELL administrative assistance.\n"
+ + CurateSpec.CURATE_TYPE_STATES[curateType]
+ + " versions of documents cannot be deleted without VCELL administrative assistance.\n"
+ + (curateType == CurateSpec.PUBLISH ? CurateSpec.CURATE_TYPE_STATES[curateType]
+ + " versions of documents MUST remain publically accessible to other VCELL users.\n"
+ : "")
+ + "Do you want to " + CurateSpec.CURATE_TYPE_NAMES[curateType] + " document '"
+ + documentInfo.getVersion().getName() + "'" + "\nwith version date '"
+ + documentInfo.getVersion().getDate().toString() + "'?"),
+ "WARNING -- " + CurateSpec.CURATE_TYPE_ACTIONS[curateType] + " operation cannot be undone");
+ if (confirm == JOptionPane.OK_OPTION) {
+ AsynchClientTask task1 = new AsynchClientTask(
+ CurateSpec.CURATE_TYPE_ACTIONS[curateType] + " document...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ if (documentInfo instanceof BioModelInfo) {
+ ClientRequestManager.this.getDocumentManager().curate(new CurateSpec((BioModelInfo) documentInfo, curateType));
+ } else if (documentInfo instanceof MathModelInfo) {
+ ClientRequestManager.this.getDocumentManager().curate(new CurateSpec((MathModelInfo) documentInfo, curateType));
+ } else {
+ throw new RuntimeException(CurateSpec.CURATE_TYPE_ACTIONS[curateType]
+ + " not supported for VCDocumentInfo type "
+ + documentInfo.getClass().getName());
+ }
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
+ new AsynchClientTask[]{task1}, false);
+ } else {
+ // user canceled
+ }
+ }
+ } else {
+ // nothing selected
+ }
+ }
+
+ public void deleteDocument(final VCDocumentInfo documentInfo, final TopLevelWindowManager requester) {
+ this.deleteDocument(documentInfo, requester, false);
+ }
+
+ public void deleteDocument(final VCDocumentInfo documentInfo, final TopLevelWindowManager requester,
+ boolean bDontAsk) {
+ if (documentInfo != null) {
+ // see if we have this open
+ String documentID = documentInfo.getVersion().getVersionKey().toString();
+ if (this.getMdiManager().haveWindow(documentID)) {
+ // already open, refuse
+ PopupGenerator.showErrorDialog(requester, "Selected edition is open, cannot delete");
+ } else {
+ // don't have it open, try to delete it
+ String confirm = UserMessage.OPTION_CANCEL;
+ if (bDontAsk) {
+ confirm = UserMessage.OPTION_DELETE;
+ } else {
+ SimpleDateFormat sdf = new SimpleDateFormat(BeanUtils.vcDateFormat);
+ confirm = PopupGenerator.showWarningDialog(requester, this.getUserPreferences(),
+ UserMessage.warn_deleteDocument, documentInfo.getVersion().getName() + " "
+ + sdf.format(documentInfo.getVersion().getDate()));
+ }
+ if (confirm.equals(UserMessage.OPTION_DELETE)) {
+ AsynchClientTask task1 = new AsynchClientTask("Deleting document...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ if (documentInfo instanceof BioModelInfo) {
+ ClientRequestManager.this.getDocumentManager().delete((BioModelInfo) documentInfo);
+ } else if (documentInfo instanceof MathModelInfo) {
+ ClientRequestManager.this.getDocumentManager().delete((MathModelInfo) documentInfo);
+ } else if (documentInfo instanceof GeometryInfo) {
+ ClientRequestManager.this.getDocumentManager().delete((GeometryInfo) documentInfo);
+ } else {
+ throw new RuntimeException("delete not supported for VCDocumentInfo type "
+ + documentInfo.getClass().getName());
+ }
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
+ new AsynchClientTask[]{task1}, false);
+ } else {
+ // user canceled
+ }
+ }
+ } else {
+ // nothing selected
+ }
+ }
+
+ /**
+ * hashtable key for data bytes of file
+ */
+ private final static String BYTES_KEY = "bytes";
+
+ /**
+ * Comment
+ */
+ public static void downloadExportedData(final Component requester, final UserPreferences userPrefs,
+ final ExportEvent evt) {
+ TreeSet exportsRecord = getExportsRecord();
+ if (exportsRecord.contains(evt.getJobID() + "")) {
+ return;
+ }
+ if (evt.getLocation().toLowerCase().endsWith("." + N5Specs.n5Suffix)) {
+ return;
+ }
+ AsynchClientTask task1 = new AsynchClientTask("Retrieving data from '" + evt.getLocation() + "'",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ final Exception[] excArr = new Exception[]{null};
+ final boolean[] bFlagArr = new boolean[]{false};
+ final ByteArrayOutputStream[] baosArr = new ByteArrayOutputStream[1];
+ final HttpGet[] httpGetArr = new HttpGet[1];
+ // Start download of exported file in separate thread that is interruptible
+ // (apache HTTPClient)
+ Thread interruptible = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ if (getClientTaskStatusSupport() != null) {
+ getClientTaskStatusSupport().setMessage("downloading data...");
+ }
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ httpGetArr[0] = new HttpGet(evt.getLocation());
+ CloseableHttpResponse response = null;
+ try {
+ response = httpclient.execute(httpGetArr[0]);
+ if (response.getStatusLine() != null
+ && (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
+ throw new Exception(
+ evt.getLocation() + " " + response.getStatusLine().getReasonPhrase());
+ }
+ HttpEntity entity = response.getEntity();
+ if (entity != null) {
+ long size = entity.getContentLength();
+ InputStream instream = entity.getContent();
+ try {
+ if (size > 0) {
+ baosArr[0] = new ByteArrayOutputStream((int) size);
+ } else {
+ baosArr[0] = new ByteArrayOutputStream();
+ }
+ IOUtils.copy(instream, baosArr[0]);
+ } finally {
+ instream.close();
+ }
+ }
+
+ } catch (Exception e) {
+ excArr[0] = e;
+ } finally {
+ if (response != null) {
+ try {
+ response.close();
+ } catch (Exception e) {
+ }
+ }
+ if (httpclient != null) {
+ try {
+ httpclient.close();
+ } catch (Exception e) {
+ }
+ }
+ bFlagArr[0] = true;
+ }
+ }
+ });
+ interruptible.start();
+ // Wait for download to 1-finish, 2-fail or 3-be cancelled by user
+ while (!bFlagArr[0]) {
+ if (this.getClientTaskStatusSupport() != null && this.getClientTaskStatusSupport().isInterrupted()) {// user
+ // cancelled
+ if (httpGetArr[0] != null) {
+ httpGetArr[0].abort();
+ }
+ throw UserCancelException.CANCEL_GENERIC;
+ }
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {// caused by pressing 'cancel' button on progresspopup
+ if (httpGetArr[0] != null) {
+ httpGetArr[0].abort();
+ }
+ if (this.getClientTaskStatusSupport() != null && this.getClientTaskStatusSupport().isInterrupted()) {
+ throw UserCancelException.CANCEL_GENERIC;
+ }
+ }
+ }
+ if (excArr[0] != null) {// download failed
+ throw excArr[0];
+ }
+ //
+ // finished downloading, either save to file or send to ImageJ directly
+ //
+ if (evt.getFormat() == null || !evt.getFormat().equals("IMAGEJ")) {
+ // save for file save operations
+ hashTable.put(BYTES_KEY, baosArr[0].toByteArray());
+ }
+ }
+ };
+ AsynchClientTask task2 = new AsynchClientTask("selecting file to save",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ // user pref could be null if trying local export
+ String defaultPath = getPreferredPath(userPrefs);
+ final VCFileChooser fileChooser = new VCFileChooser(defaultPath);
+ fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
+ fileChooser.setMultiSelectionEnabled(false);
+ String name = evt.getDataIdString();
+ String suffix = null;
+ if (evt.getLocation().toLowerCase().endsWith(".mov")) {
+ fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_MOV);
+ fileChooser.setFileFilter(FileFilters.FILE_FILTER_MOV);
+
+ suffix = "_exported.mov";
+ } else if (evt.getLocation().toLowerCase().endsWith(".gif")) {
+ fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_GIF);
+ fileChooser.setFileFilter(FileFilters.FILE_FILTER_GIF);
+
+ suffix = "_exported.gif";
+ } else if (evt.getLocation().toLowerCase().endsWith(".jpeg")) {
+ fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_JPEG);
+ fileChooser.setFileFilter(FileFilters.FILE_FILTER_JPEG);
+
+ suffix = "_exported.jpeg";
+ } else if (evt.getLocation().toLowerCase().endsWith(".hdf5")) {
+ fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_HDF5);
+ fileChooser.setFileFilter(FileFilters.FILE_FILTER_HDF5);
+
+ suffix = "_exported.hdf5";
+ } else {
+ fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_ZIP);
+ fileChooser.setFileFilter(FileFilters.FILE_FILTER_ZIP);
+
+ suffix = "_exported.zip";
+ }
+ File file = new File(name + suffix);
+ if (file.exists()) {
+ int count = 0;
+ do {
+ file = new File(name + "_" + count + suffix);
+ count++;
+ } while (file.exists());
+ }
+
+ fileChooser.setSelectedFile(file);
+ fileChooser.setDialogTitle("Save exported dataset...");
+ int approve = fileChooser.showSaveDialog(requester);
+ if (approve == JFileChooser.APPROVE_OPTION) {
+ hashTable.put("selectedFile", fileChooser.getSelectedFile());
+ } else {
+ fileChooser.setSelectedFile(null);
+ }
+ }
+ };
+ AsynchClientTask task3 = new AsynchClientTask("saving to file", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ addExportRecord(evt.getJobID() + "");
+
+ File selectedFile = (File) hashTable.get("selectedFile");
+ if (selectedFile == null) {
+ return;
+ }
+ setPreferredPath(userPrefs, selectedFile);
// System.out.println("New preferred file path: " + newPath + ", Old preferred file path: " + defaultPath);
- if (selectedFile.exists()) {
- String question = null;
- if (userPrefs != null) {
- question = PopupGenerator.showWarningDialog(requester, userPrefs,
- UserMessage.warn_OverwriteFile, selectedFile.getAbsolutePath());
- } else {
- question = DialogUtils.showWarningDialog(requester, "Overwrite File?",
- "Overwrite file '" + selectedFile.getAbsolutePath() + "'?",
- new String[] { UserMessage.OPTION_OVERWRITE_FILE, UserMessage.OPTION_CANCEL },
- UserMessage.OPTION_OVERWRITE_FILE);
- }
- if (question != null && question.equals(UserMessage.OPTION_CANCEL)) {
- return;
- }
- }
- byte[] bytes = (byte[]) hashTable.get(BYTES_KEY);
- FileOutputStream fo = new FileOutputStream(selectedFile);
- fo.write(bytes);
- fo.close();
- }
- };
- ClientTaskDispatcher.dispatch(requester, new Hashtable(),
- new AsynchClientTask[] { task1, task2, task3 }, false, true, null);
- }
-
- private static String EXPORT_RECORD_FILE_NAME = "exportRecords";
-
- private static TreeSet getExportsRecord() {
- try {
- if (ResourceUtil.getVcellHome() != null) {
- File exportRecordsFile = new File(ResourceUtil.getVcellHome(), EXPORT_RECORD_FILE_NAME);
- if (exportRecordsFile.exists()) {
- List exportRecordsList = Files.readAllLines(exportRecordsFile.toPath());
- return new TreeSet(exportRecordsList);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return new TreeSet();
- }
-
- private static void addExportRecord(String exportRecord) {
- try {
- if (ResourceUtil.getVcellHome() != null) {
- File exportRecordsFile = new File(ResourceUtil.getVcellHome(), EXPORT_RECORD_FILE_NAME);
- Files.write(exportRecordsFile.toPath(), (exportRecord + System.lineSeparator()).getBytes(),
- StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public static String EXPORT_METADATA_FILENAME = "exportMetaData.json";
-
- private static void updateExportMetaData(final ExportEvent exportEvent){
- try{
- if(ResourceUtil.getVcellHome() != null){
-
- String stringJobID = String.valueOf(exportEvent.getJobID());
- String exportFormat = exportEvent.getFormat();
- if(stringJobID == null) {
- throw new RuntimeException("stringJobID is null");
- }
- if(exportFormat == null) {
- throw new RuntimeException("exportFormat is null");
- }
- String globalID = stringJobID + "," + exportFormat;
-
- ExportDataRepresentation exportDataRepresentation = new ExportDataRepresentation(new Stack<>(), new HashMap<>());
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
- // put lock
- File jsonFile = new File(ResourceUtil.getVcellHome(), EXPORT_METADATA_FILENAME);
-
- HumanReadableExportData humanReadableExportData = exportEvent.getHumanReadableData();
- DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- double[] exportTimes = exportEvent.getTimeSpecs().getAllTimes();
-
-
- if (jsonFile.exists()){
- String stringJSON = new String(Files.readAllBytes(jsonFile.toPath()));
- exportDataRepresentation = stringJSON.isEmpty() ?
- exportDataRepresentation : gson.fromJson(stringJSON, ExportDataRepresentation.class);
- }
-
- int sizeOfList = exportDataRepresentation.globalJobIDs.size();
- int startOfSearch = sizeOfList > 200 ? sizeOfList - 200 : 0;
- // only write new data, checking the last 200 elements in the stack
- if (!exportDataRepresentation.globalJobIDs.subList(startOfSearch, sizeOfList).contains(globalID)){
- ExportDataRepresentation.FormatExportDataRepresentation formatData = exportDataRepresentation.formatData.containsKey(exportFormat) ?
- exportDataRepresentation.formatData.get(exportFormat) : new ExportDataRepresentation.FormatExportDataRepresentation(new HashMap<>(), new ArrayList<>());
-
-
- ExportDataRepresentation.SimulationExportDataRepresentation simulationExportDataRepresentation = new ExportDataRepresentation.SimulationExportDataRepresentation(
- dateFormat.format(new Date()),
- exportEvent.getLocation(),
- stringJobID,
- exportEvent.getDataIdString(),
- humanReadableExportData.simulationName,
- humanReadableExportData.applicationName,
- humanReadableExportData.biomodelName,
+ if (selectedFile.exists()) {
+ String question = null;
+ if (userPrefs != null) {
+ question = PopupGenerator.showWarningDialog(requester, userPrefs,
+ UserMessage.warn_OverwriteFile, selectedFile.getAbsolutePath());
+ } else {
+ question = DialogUtils.showWarningDialog(requester, "Overwrite File?",
+ "Overwrite file '" + selectedFile.getAbsolutePath() + "'?",
+ new String[]{UserMessage.OPTION_OVERWRITE_FILE, UserMessage.OPTION_CANCEL},
+ UserMessage.OPTION_OVERWRITE_FILE);
+ }
+ if (question != null && question.equals(UserMessage.OPTION_CANCEL)) {
+ return;
+ }
+ }
+ byte[] bytes = (byte[]) hashTable.get(BYTES_KEY);
+ FileOutputStream fo = new FileOutputStream(selectedFile);
+ fo.write(bytes);
+ fo.close();
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester, new Hashtable(),
+ new AsynchClientTask[]{task1, task2, task3}, false, true, null);
+ }
+
+ private static final String EXPORT_RECORD_FILE_NAME = "exportRecords";
+
+ private static TreeSet getExportsRecord() {
+ try {
+ if (ResourceUtil.getVcellHome() != null) {
+ File exportRecordsFile = new File(ResourceUtil.getVcellHome(), EXPORT_RECORD_FILE_NAME);
+ if (exportRecordsFile.exists()) {
+ List exportRecordsList = Files.readAllLines(exportRecordsFile.toPath());
+ return new TreeSet(exportRecordsList);
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return new TreeSet();
+ }
+
+ private static void addExportRecord(String exportRecord) {
+ try {
+ if (ResourceUtil.getVcellHome() != null) {
+ File exportRecordsFile = new File(ResourceUtil.getVcellHome(), EXPORT_RECORD_FILE_NAME);
+ Files.write(exportRecordsFile.toPath(), (exportRecord + System.lineSeparator()).getBytes(),
+ StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static String EXPORT_METADATA_FILENAME = "exportMetaData.json";
+
+ private static void updateExportMetaData(final ExportEvent exportEvent) {
+ try {
+ if (ResourceUtil.getVcellHome() != null) {
+
+ String stringJobID = String.valueOf(exportEvent.getJobID());
+ String exportFormat = exportEvent.getFormat();
+ if (stringJobID == null) {
+ throw new RuntimeException("stringJobID is null");
+ }
+ if (exportFormat == null) {
+ throw new RuntimeException("exportFormat is null");
+ }
+ String globalID = stringJobID + "," + exportFormat;
+
+ ExportDataRepresentation exportDataRepresentation = new ExportDataRepresentation(new Stack<>(), new HashMap<>());
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ // put lock
+ File jsonFile = new File(ResourceUtil.getVcellHome(), EXPORT_METADATA_FILENAME);
+
+ HumanReadableExportData humanReadableExportData = exportEvent.getHumanReadableData();
+ DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
+ double[] exportTimes = exportEvent.getTimeSpecs().getAllTimes();
+
+
+ if (jsonFile.exists()) {
+ String stringJSON = new String(Files.readAllBytes(jsonFile.toPath()));
+ exportDataRepresentation = stringJSON.isEmpty() ?
+ exportDataRepresentation : gson.fromJson(stringJSON, ExportDataRepresentation.class);
+ }
+
+ int sizeOfList = exportDataRepresentation.globalJobIDs.size();
+ int startOfSearch = sizeOfList > 200 ? sizeOfList - 200 : 0;
+ // only write new data, checking the last 200 elements in the stack
+ if (!exportDataRepresentation.globalJobIDs.subList(startOfSearch, sizeOfList).contains(globalID)) {
+ ExportDataRepresentation.FormatExportDataRepresentation formatData = exportDataRepresentation.formatData.containsKey(exportFormat) ?
+ exportDataRepresentation.formatData.get(exportFormat) : new ExportDataRepresentation.FormatExportDataRepresentation(new HashMap<>(), new ArrayList<>());
+
+
+ ExportDataRepresentation.SimulationExportDataRepresentation simulationExportDataRepresentation = new ExportDataRepresentation.SimulationExportDataRepresentation(
+ dateFormat.format(new Date()),
+ exportEvent.getLocation(),
+ stringJobID,
+ exportEvent.getDataIdString(),
+ humanReadableExportData.simulationName,
+ humanReadableExportData.applicationName,
+ humanReadableExportData.biomodelName,
Arrays.toString(exportEvent.getVariableSpecs().getVariableNames()),
- exportTimes[exportEvent.getTimeSpecs().getBeginTimeIndex()] + "/" + exportTimes[exportEvent.getTimeSpecs().getEndTimeIndex()],
- humanReadableExportData.differentParameterValues,
- humanReadableExportData.serverSavedFileName,
- humanReadableExportData.applicationType,
- humanReadableExportData.nonSpatial
- );
-
- formatData.simulationDataMap.put(stringJobID, simulationExportDataRepresentation);
- formatData.formatJobIDs.add(stringJobID);
-
- exportDataRepresentation.formatData.put(exportFormat, formatData);
- exportDataRepresentation.globalJobIDs.add(globalID);
-
-
- String json = gson.toJson(exportDataRepresentation, ExportDataRepresentation.class);
- FileWriter jsonFileWriter = new FileWriter(jsonFile);
- jsonFileWriter.write(json);
-
- jsonFileWriter.close();
- }
- }
- }
- catch (Exception e){
- lg.error("Failed Update Export Metadata", e);
- }
- }
-
- public void exitApplication(boolean loggingOut) {
- try (VCellThreadChecker.SuppressIntensive si = new VCellThreadChecker.SuppressIntensive()) {
- if (!bExiting) {
- // close all windows - this will run checks
- boolean closedAllWindows = closeAllWindows(true);
- if (!closedAllWindows) {
- // user bailed out at some point, we're not gonna exit
- return;
- }
- }
- // ready to exit
- if (!ClientTaskDispatcher.hasOutstandingTasks()) {
- // simply exit in this case
- if (loggingOut) {
- Auth0ConnectionUtils.setShowLoginPopUp(true);
- if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
- try {
- Desktop.getDesktop().browse(new URI("https://vcell-stage.cam.uchc.edu/login_success"));
- } catch (IOException | URISyntaxException e) {
- throw new RuntimeException(e);
- }
- }
- }
- System.exit(0);
- }
- new Timer(1000, evt -> checkTasksDone()).start();
- }
- }
-
- public void exitApplication(){
- exitApplication(false);
- }
-
- /**
- * see if there are outstanding tasks ... if not, exit the application
- */
- private void checkTasksDone() {
- Collection ot = ClientTaskDispatcher.outstandingTasks();
- if (ot.isEmpty()) {
- // ready to exit now
- System.exit(0);
- }
- System.out.println("waiting for " + ot.toString());
- }
-
- /**
- * Comment
- */
- public void exportDocument(TopLevelWindowManager manager, FileFilter forceFilefilter) {
- /* block window */
- JFrame currentWindow = getMdiManager().blockWindow(manager.getManagerID());
- /* prepare hashtable for tasks */
- Hashtable hash = new Hashtable();
- hash.put("mdiManager", getMdiManager());
- hash.put(DocumentManager.IDENT, getDocumentManager());
- hash.put("topLevelWindowManager", manager);
- hash.put("currentWindow", currentWindow);
- hash.put("userPreferences", getUserPreferences());
- if (forceFilefilter != null) {
- hash.put(ChooseFile.FORCE_FILE_FILTER, forceFilefilter);
- }
-
- hash.put("CallAction", CallAction.EXPORT);
- hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, manager);
- hash.put("currentDocumentWindow", currentWindow);
-
- /* create tasks */
- AsynchClientTask documentValid = new DocumentValidTask();
- AsynchClientTask setMathDescription = new SetMathDescription();
-
- // get document to be exported
- AsynchClientTask documentToExport = new DocumentToExport();
- // get file
- AsynchClientTask chooseFile = new ChooseFile();
- // export it
- AsynchClientTask exportDocument = new ExportDocument();
- // clean-up
- AsynchClientTask finishExport = new FinishExport();
- // assemble array
- AsynchClientTask[] tasks = null;
- tasks = new AsynchClientTask[] { documentToExport, chooseFile, documentValid, setMathDescription, exportDocument, finishExport };
- /* run tasks */
- ClientTaskDispatcher.dispatch(currentWindow, hash, tasks, false);
- }
-
- public void exportMessage(ExportEvent event) {
- if (event.getEventTypeID() == ExportEvent.EXPORT_COMPLETE) {
- // try to download the thing
- if(!Objects.equals(event.getFormat(), ExportFormat.N5.name())){
- downloadExportedData(getMdiManager().getFocusedWindowManager().getComponent(), getUserPreferences(), event);
- }
- // create export metadata
- updateExportMetaData(event);
- }
- }
-
- public AsynchMessageManager getAsynchMessageManager() {
- return getClientServerManager().getAsynchMessageManager();
- }
-
- private ClientServerManager getClientServerManager() {
- // shorthand
- return getVcellClient().getClientServerManager();
- }
-
- public ConnectionStatus getConnectionStatus() {
- return getClientServerManager().getConnectionStatus();
- }
-
- public DataManager getDataManager(OutputContext outputContext, VCDataIdentifier vcDataId, boolean isSpatial)
- throws DataAccessException {
- //
- // Create ODE or PDE or Merged Datamanager depending on ODE or PDE or Merged
- // data.
- //
- DataManager dataManager = null;
- VCDataManager vcDataManager = getClientServerManager().getVCDataManager();
- if (isSpatial) {
- dataManager = new PDEDataManager(outputContext, vcDataManager, vcDataId);
- } else {
- dataManager = new ODEDataManager(outputContext, vcDataManager, vcDataId);
- }
+ exportTimes[exportEvent.getTimeSpecs().getBeginTimeIndex()] + "/" + exportTimes[exportEvent.getTimeSpecs().getEndTimeIndex()],
+ humanReadableExportData.differentParameterValues,
+ humanReadableExportData.serverSavedFileName,
+ humanReadableExportData.applicationType,
+ humanReadableExportData.nonSpatial
+ );
+
+ formatData.simulationDataMap.put(stringJobID, simulationExportDataRepresentation);
+ formatData.formatJobIDs.add(stringJobID);
+
+ exportDataRepresentation.formatData.put(exportFormat, formatData);
+ exportDataRepresentation.globalJobIDs.add(globalID);
+
+
+ String json = gson.toJson(exportDataRepresentation, ExportDataRepresentation.class);
+ FileWriter jsonFileWriter = new FileWriter(jsonFile);
+ jsonFileWriter.write(json);
+
+ jsonFileWriter.close();
+ }
+ }
+ } catch (Exception e) {
+ lg.error("Failed Update Export Metadata", e);
+ }
+ }
+
+ public void exitApplication(boolean loggingOut) {
+ try (VCellThreadChecker.SuppressIntensive si = new VCellThreadChecker.SuppressIntensive()) {
+ if (!this.bExiting) {
+ // close all windows - this will run checks
+ boolean closedAllWindows = this.closeAllWindows(true);
+ if (!closedAllWindows) {
+ // user bailed out at some point, we're not gonna exit
+ return;
+ }
+ }
+ // ready to exit
+ if (!ClientTaskDispatcher.hasOutstandingTasks()) {
+ // simply exit in this case
+ if (loggingOut) {
+ Auth0ConnectionUtils.setShowLoginPopUp(true);
+ if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
+ try {
+ Desktop.getDesktop().browse(new URI("https://vcell-stage.cam.uchc.edu/login_success"));
+ } catch (IOException | URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+ System.exit(0);
+ }
+ new Timer(1000, evt -> this.checkTasksDone()).start();
+ }
+ }
+
+ public void exitApplication() {
+ this.exitApplication(false);
+ }
+
+ /**
+ * see if there are outstanding tasks ... if not, exit the application
+ */
+ private void checkTasksDone() {
+ Collection ot = ClientTaskDispatcher.outstandingTasks();
+ if (ot.isEmpty()) {
+ // ready to exit now
+ System.exit(0);
+ }
+ System.out.println("waiting for " + ot);
+ }
+
+ /**
+ * Comment
+ */
+ public void exportDocument(TopLevelWindowManager manager, FileFilter forceFilefilter) {
+ /* block window */
+ JFrame currentWindow = this.getMdiManager().blockWindow(manager.getManagerID());
+ /* prepare hashtable for tasks */
+ Hashtable hash = new Hashtable();
+ hash.put("mdiManager", this.getMdiManager());
+ hash.put(DocumentManager.IDENT, this.getDocumentManager());
+ hash.put("topLevelWindowManager", manager);
+ hash.put("currentWindow", currentWindow);
+ hash.put("userPreferences", this.getUserPreferences());
+ if (forceFilefilter != null) {
+ hash.put(ChooseFile.FORCE_FILE_FILTER, forceFilefilter);
+ }
+
+ hash.put("CallAction", CallAction.EXPORT);
+ hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, manager);
+ hash.put("currentDocumentWindow", currentWindow);
+
+ /* create tasks */
+ AsynchClientTask documentValid = new DocumentValidTask();
+ AsynchClientTask setMathDescription = new SetMathDescription();
+
+ // get document to be exported
+ AsynchClientTask documentToExport = new DocumentToExport();
+ // get file
+ AsynchClientTask chooseFile = new ChooseFile();
+ // export it
+ AsynchClientTask exportDocument = new ExportDocument();
+ // clean-up
+ AsynchClientTask finishExport = new FinishExport();
+ // assemble array
+ AsynchClientTask[] tasks = null;
+ tasks = new AsynchClientTask[]{documentToExport, chooseFile, documentValid, setMathDescription, exportDocument, finishExport};
+ /* run tasks */
+ ClientTaskDispatcher.dispatch(currentWindow, hash, tasks, false);
+ }
+
+ public void exportMessage(ExportEvent event) {
+ if (event.getEventTypeID() == ExportEvent.EXPORT_COMPLETE) {
+ // try to download the thing
+ if (!Objects.equals(event.getFormat(), ExportFormat.N5.name())) {
+ downloadExportedData(this.getMdiManager().getFocusedWindowManager().getComponent(), this.getUserPreferences(), event);
+ }
+ // create export metadata
+ updateExportMetaData(event);
+ }
+ }
+
+ public AsynchMessageManager getAsynchMessageManager() {
+ return this.getClientServerManager().getAsynchMessageManager();
+ }
+
+ private ClientServerManager getClientServerManager() {
+ // shorthand
+ return this.getVcellClient().getClientServerManager();
+ }
+
+ public ConnectionStatus getConnectionStatus() {
+ return this.getClientServerManager().getConnectionStatus();
+ }
+
+ public DataManager getDataManager(OutputContext outputContext, VCDataIdentifier vcDataId, boolean isSpatial)
+ throws DataAccessException {
+ //
+ // Create ODE or PDE or Merged Datamanager depending on ODE or PDE or Merged
+ // data.
+ //
+ DataManager dataManager = null;
+ VCDataManager vcDataManager = this.getClientServerManager().getVCDataManager();
+ if (isSpatial) {
+ dataManager = new PDEDataManager(outputContext, vcDataManager, vcDataId);
+ } else {
+ dataManager = new ODEDataManager(outputContext, vcDataManager, vcDataId);
+ }
// dataManager.connect();
- return dataManager;
- }
-
- @Override
- public VtkManager getVtkManager(OutputContext outputContext, VCDataIdentifier vcDataID) throws DataAccessException {
- VCDataManager vcDataManager = getClientServerManager().getVCDataManager();
- return new VtkManager(outputContext, vcDataManager, vcDataID);
- }
-
- public DocumentManager getDocumentManager() {
- // this should not be exposed here, but needs many changes outside project in
- // order to live without it...
- // will eliminate when finishing up new client
- return getVcellClient().getClientServerManager().getDocumentManager();
- }
-
- public MergedDatasetViewerController getMergedDatasetViewerController(OutputContext outputContext,
- VCDataIdentifier vcdId, boolean expectODEData) throws DataAccessException {
- if (vcdId instanceof MergedDataInfo) {
- DataManager dataManager = getDataManager(outputContext, vcdId, !expectODEData);
- return new MergedDatasetViewerController(dataManager);
- } else {
- return null;
- }
- }
-
- public DataViewerController getDataViewerController(OutputContext outputContext, Simulation simulation,
- int jobIndex) throws DataAccessException {
- VCSimulationIdentifier vcSimulationIdentifier = simulation.getSimulationInfo()
- .getAuthoritativeVCSimulationIdentifier();
- final VCDataIdentifier vcdataIdentifier = new VCSimulationDataIdentifier(vcSimulationIdentifier, jobIndex);
- boolean isSpatialData = simulation.isSpatial()
- && simulation.getSolverTaskDescription().getLangevinSimulationOptions() == null;
- DataManager dataManager = getDataManager(outputContext, vcdataIdentifier, isSpatialData);
- return new SimResultsViewerController(dataManager, simulation);
- }
-
- // utility method
- private VCDocumentInfo getMatchingDocumentInfo(VCDocument vcDoc) throws DataAccessException {
-
- VCDocumentInfo vcDocInfo = null;
-
- switch (vcDoc.getDocumentType()) {
- case BIOMODEL_DOC: {
- BioModel bm = ((BioModel) vcDoc);
- vcDocInfo = getDocumentManager().getBioModelInfo(bm.getVersion().getVersionKey());
- break;
- }
- case MATHMODEL_DOC: {
- MathModel mm = ((MathModel) vcDoc);
- vcDocInfo = getDocumentManager().getMathModelInfo(mm.getVersion().getVersionKey());
- break;
- }
- case GEOMETRY_DOC: {
- Geometry geom = ((Geometry) vcDoc);
- vcDocInfo = getDocumentManager().getGeometryInfo(geom.getKey());
- break;
- }
- default: {
- throw new IllegalArgumentException("Invalid VC document: " + vcDoc.getDocumentType());
- }
- }
-
- return vcDocInfo;
- }
-
- private MDIManager getMdiManager() {
- // shorthand
- return getVcellClient().getMdiManager();
- }
-
- public SimulationStatus getServerSimulationStatus(SimulationInfo simInfo) {
-
- SimulationStatus simStatus = null;
- if (simInfo == null) {
- // unsaved simulation ... won't have simulation status
- return null;
- }
- try {
- VCSimulationIdentifier vcSimulationIdentifier = simInfo.getAuthoritativeVCSimulationIdentifier();
- simStatus = getClientServerManager().getJobManager().getServerSimulationStatus(vcSimulationIdentifier);
- } catch (Throwable exc) {
- exc.printStackTrace(System.out);
- }
- return simStatus;
- }
-
- public UserPreferences getUserPreferences() {
- return getVcellClient().getClientServerManager().getUserPreferences();
- }
-
- private VCellClient getVcellClient() {
- return vcellClient;
- }
-
- /**
- *
- * @return false
- */
- @Deprecated
- public boolean isApplet() {
- return false;
- }
-
- public void managerIDchanged(java.lang.String oldID, java.lang.String newID) {
- if (oldID != null) {
- getMdiManager().updateDocumentID(oldID, newID);
- }
- }
-
- public AsynchClientTask[] newDocument(TopLevelWindowManager requester,
- final VCDocument.DocumentCreationInfo documentCreationInfo) {
- // gcwtodo
-
- AsynchClientTask createNewDocumentTask = new AsynchClientTask("Creating New Document",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- VCDocument doc = (VCDocument) hashTable.get("doc");
- DocumentWindowManager windowManager = createDocumentWindowManager(doc);
- DocumentWindow dw = getMdiManager().createNewDocumentWindow(windowManager);
- if (windowManager != null) {
- hashTable.put("windowManager", windowManager);
- }
- setFinalWindow(hashTable, dw);
- }
- };
-
- if (documentCreationInfo.getDocumentType() == VCDocumentType.MATHMODEL_DOC
- && documentCreationInfo.getOption() == VCDocument.MATH_OPTION_SPATIAL_NEW) {
- final AsynchClientTask createSpatialMathModelTask = new AsynchClientTask("creating mathmodel",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- Geometry geometry = null;
- geometry = (Geometry) hashTable.get("doc");
- MathModel mathModel = createMathModel("Untitled", geometry);
- mathModel.setName("MathModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1));
- hashTable.put("doc", mathModel);
- }
- };
-
- requester.createGeometry(null, new AsynchClientTask[] { createSpatialMathModelTask, createNewDocumentTask },
- "Choose geometry type to start MathModel creation", "Create MathModel", null);
- return null;
- }
-
- /* asynchronous and not blocking any window */
- AsynchClientTask[] taskArray = null;
- if (documentCreationInfo.getPreCreatedDocument() == null) {
- AsynchClientTask[] taskArray1 = createNewDocument(requester, documentCreationInfo);
- taskArray = new AsynchClientTask[taskArray1.length + 1];
- System.arraycopy(taskArray1, 0, taskArray, 0, taskArray1.length);
- } else {
- taskArray = new AsynchClientTask[2];
- taskArray[0] = new AsynchClientTask("Setting document...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- hashTable.put("doc", documentCreationInfo.getPreCreatedDocument());
- }
- };
- }
-
- taskArray[taskArray.length - 1] = createNewDocumentTask;
- return taskArray;
- }
-
- private static VCImage saveImageAutoName(RequestManager requestManager, VCImage vcImage) throws Exception {
- VCImageInfo[] imageInfos = null;
- try {
- imageInfos = requestManager.getDocumentManager().getImageInfos();
- } catch (DataAccessException e) {
- e.printStackTrace(System.out);
- }
- String newName = null;
- boolean bNameIsGood = false;
+ return dataManager;
+ }
+
+ @Override
+ public VtkManager getVtkManager(OutputContext outputContext, VCDataIdentifier vcDataID) throws DataAccessException {
+ VCDataManager vcDataManager = this.getClientServerManager().getVCDataManager();
+ return new VtkManager(outputContext, vcDataManager, vcDataID);
+ }
+
+ public DocumentManager getDocumentManager() {
+ // this should not be exposed here, but needs many changes outside project in
+ // order to live without it...
+ // will eliminate when finishing up new client
+ return this.getVcellClient().getClientServerManager().getDocumentManager();
+ }
+
+ public MergedDatasetViewerController getMergedDatasetViewerController(OutputContext outputContext,
+ VCDataIdentifier vcdId, boolean expectODEData) throws DataAccessException {
+ if (vcdId instanceof MergedDataInfo) {
+ DataManager dataManager = this.getDataManager(outputContext, vcdId, !expectODEData);
+ return new MergedDatasetViewerController(dataManager);
+ } else {
+ return null;
+ }
+ }
+
+ public DataViewerController getDataViewerController(OutputContext outputContext, Simulation simulation,
+ int jobIndex) throws DataAccessException {
+ VCSimulationIdentifier vcSimulationIdentifier = simulation.getSimulationInfo()
+ .getAuthoritativeVCSimulationIdentifier();
+ final VCDataIdentifier vcdataIdentifier = new VCSimulationDataIdentifier(vcSimulationIdentifier, jobIndex);
+ boolean isSpatialData = simulation.isSpatial()
+ && simulation.getSolverTaskDescription().getLangevinSimulationOptions() == null;
+ DataManager dataManager = this.getDataManager(outputContext, vcdataIdentifier, isSpatialData);
+ return new SimResultsViewerController(dataManager, simulation);
+ }
+
+ // utility method
+ private VCDocumentInfo getMatchingDocumentInfo(VCDocument vcDoc) throws DataAccessException {
+
+ VCDocumentInfo vcDocInfo = null;
+
+ switch (vcDoc.getDocumentType()) {
+ case BIOMODEL_DOC: {
+ BioModel bm = ((BioModel) vcDoc);
+ vcDocInfo = this.getDocumentManager().getBioModelInfo(bm.getVersion().getVersionKey());
+ break;
+ }
+ case MATHMODEL_DOC: {
+ MathModel mm = ((MathModel) vcDoc);
+ vcDocInfo = this.getDocumentManager().getMathModelInfo(mm.getVersion().getVersionKey());
+ break;
+ }
+ case GEOMETRY_DOC: {
+ Geometry geom = ((Geometry) vcDoc);
+ vcDocInfo = this.getDocumentManager().getGeometryInfo(geom.getKey());
+ break;
+ }
+ default: {
+ throw new IllegalArgumentException("Invalid VC document: " + vcDoc.getDocumentType());
+ }
+ }
+
+ return vcDocInfo;
+ }
+
+ private MDIManager getMdiManager() {
+ // shorthand
+ return this.getVcellClient().getMdiManager();
+ }
+
+ public SimulationStatus getServerSimulationStatus(SimulationInfo simInfo) {
+
+ SimulationStatus simStatus = null;
+ if (simInfo == null) {
+ // unsaved simulation ... won't have simulation status
+ return null;
+ }
+ try {
+ VCSimulationIdentifier vcSimulationIdentifier = simInfo.getAuthoritativeVCSimulationIdentifier();
+ simStatus = this.getClientServerManager().getJobManager().getServerSimulationStatus(vcSimulationIdentifier);
+ } catch (Throwable exc) {
+ exc.printStackTrace(System.out);
+ }
+ return simStatus;
+ }
+
+ public UserPreferences getUserPreferences() {
+ return this.getVcellClient().getClientServerManager().getUserPreferences();
+ }
+
+ private VCellClient getVcellClient() {
+ return this.vcellClient;
+ }
+
+ /**
+ * @return false
+ */
+ @Deprecated
+ public boolean isApplet() {
+ return false;
+ }
+
+ public void managerIDchanged(java.lang.String oldID, java.lang.String newID) {
+ if (oldID != null) {
+ this.getMdiManager().updateDocumentID(oldID, newID);
+ }
+ }
+
+ public AsynchClientTask[] newDocument(TopLevelWindowManager requester,
+ final VCDocument.DocumentCreationInfo documentCreationInfo) {
+ // gcwtodo
+
+ AsynchClientTask createNewDocumentTask = new AsynchClientTask("Creating New Document",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ VCDocument doc = (VCDocument) hashTable.get("doc");
+ DocumentWindowManager windowManager = ClientRequestManager.this.createDocumentWindowManager(doc);
+ DocumentWindow dw = ClientRequestManager.this.getMdiManager().createNewDocumentWindow(windowManager);
+ if (windowManager != null) {
+ hashTable.put("windowManager", windowManager);
+ }
+ this.setFinalWindow(hashTable, dw);
+ }
+ };
+
+ if (documentCreationInfo.getDocumentType() == VCDocumentType.MATHMODEL_DOC
+ && documentCreationInfo.getOption() == VCDocument.MATH_OPTION_SPATIAL_NEW) {
+ final AsynchClientTask createSpatialMathModelTask = new AsynchClientTask("creating mathmodel",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ Geometry geometry = null;
+ geometry = (Geometry) hashTable.get("doc");
+ MathModel mathModel = ClientRequestManager.this.createMathModel("Untitled", geometry);
+ mathModel.setName("MathModel" + (ClientRequestManager.this.getMdiManager().getNumCreatedDocumentWindows() + 1));
+ hashTable.put("doc", mathModel);
+ }
+ };
+
+ requester.createGeometry(null, new AsynchClientTask[]{createSpatialMathModelTask, createNewDocumentTask},
+ "Choose geometry type to start MathModel creation", "Create MathModel", null);
+ return null;
+ }
+
+ /* asynchronous and not blocking any window */
+ AsynchClientTask[] taskArray = null;
+ if (documentCreationInfo.getPreCreatedDocument() == null) {
+ AsynchClientTask[] taskArray1 = this.createNewDocument(requester, documentCreationInfo);
+ taskArray = new AsynchClientTask[taskArray1.length + 1];
+ System.arraycopy(taskArray1, 0, taskArray, 0, taskArray1.length);
+ } else {
+ taskArray = new AsynchClientTask[2];
+ taskArray[0] = new AsynchClientTask("Setting document...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ hashTable.put("doc", documentCreationInfo.getPreCreatedDocument());
+ }
+ };
+ }
+
+ taskArray[taskArray.length - 1] = createNewDocumentTask;
+ return taskArray;
+ }
+
+ private static VCImage saveImageAutoName(RequestManager requestManager, VCImage vcImage) throws Exception {
+ VCImageInfo[] imageInfos = null;
+ try {
+ imageInfos = requestManager.getDocumentManager().getImageInfos();
+ } catch (DataAccessException e) {
+ e.printStackTrace(System.out);
+ }
+ String newName = null;
+ boolean bNameIsGood = false;
// Calendar calendar = Calendar.getInstance();
- newName = "image_" + BeanUtils.generateDateTimeString();
- while (!bNameIsGood) {
- if (imageInfos == null) {
- bNameIsGood = true; // if no image information assume image name is good
- } else {
- boolean bNameExists = false;
- for (int i = 0; i < imageInfos.length; i++) {
- if (imageInfos[i].getVersion().getName().equals(newName)) {
- bNameExists = true;
- break;
- }
- }
- if (!bNameExists) {
- bNameIsGood = true;
- }
- }
- if (!bNameIsGood) {
- newName = TokenMangler.getNextEnumeratedToken(newName);
- }
- }
-
- return requestManager.getDocumentManager().saveAsNew(vcImage, newName);
-
- }
-
- private AsynchClientTask getSaveImageAndGeometryTask() {
-
- final AsynchClientTask saveImageAndGeometryTask = new AsynchClientTask("creating geometry",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- getClientTaskStatusSupport().setMessage("Getting new Geometry name...");
- String newGeometryName = null;
- while (true) {
- newGeometryName = ClientRequestManager.this.getMdiManager().getDatabaseWindowManager()
- .showSaveDialog(((Geometry) hashTable.get("doc")).getDocumentType(),
- (Component) hashTable.get(ClientRequestManager.GUI_PARENT),
- (newGeometryName == null ? "NewGeometry" : newGeometryName));
- if (newGeometryName == null || newGeometryName.trim().length() == 0) {
- newGeometryName = null;
- DialogUtils.showWarningDialog((Component) hashTable.get(ClientRequestManager.GUI_PARENT),
- "New Geometry name cannot be empty.");
- continue;
- }
- // Check name conflict
- GeometryInfo[] geometryInfos = ClientRequestManager.this.getDocumentManager().getGeometryInfos();
- boolean bNameConflict = false;
- for (int i = 0; i < geometryInfos.length; i++) {
- if (geometryInfos[i].getVersion().getOwner()
- .equals(ClientRequestManager.this.getDocumentManager().getUser())) {
- if (geometryInfos[i].getVersion().getName().equals(newGeometryName)) {
- bNameConflict = true;
- break;
- }
- }
- }
- if (bNameConflict) {
- DialogUtils.showWarningDialog((Component) hashTable.get(ClientRequestManager.GUI_PARENT),
- "A Geometry with name " + newGeometryName
- + " already exists. Choose a different name.");
- continue;
- } else {
- break;
- }
- }
- getClientTaskStatusSupport().setMessage("Saving image portion of Geometry...");
- saveImageAutoName(ClientRequestManager.this,
- ((Geometry) hashTable.get("doc")).getGeometrySpec().getImage());
- getClientTaskStatusSupport().setMessage("Saving final Geometry...");
- ClientRequestManager.this.getDocumentManager().saveAsNew((Geometry) hashTable.get("doc"),
- newGeometryName);
- }
- };
-
- return saveImageAndGeometryTask;
- }
-
- /**
- * onVCellMessageEvent method comment.
- */
- public void onVCellMessageEvent(final VCellMessageEvent event) {
- if (event.getEventTypeID() == VCellMessageEvent.VCELL_MESSAGEEVENT_TYPE_BROADCAST) {
- DialogUtils.showInfoDialog(getMdiManager().getFocusedWindowManager().getComponent(),"Message for All VCell Users",
- event.getMessageData().getData().toString());
- }
- }
+ newName = "image_" + BeanUtils.generateDateTimeString();
+ while (!bNameIsGood) {
+ if (imageInfos == null) {
+ bNameIsGood = true; // if no image information assume image name is good
+ } else {
+ boolean bNameExists = false;
+ for (int i = 0; i < imageInfos.length; i++) {
+ if (imageInfos[i].getVersion().getName().equals(newName)) {
+ bNameExists = true;
+ break;
+ }
+ }
+ if (!bNameExists) {
+ bNameIsGood = true;
+ }
+ }
+ if (!bNameIsGood) {
+ newName = TokenMangler.getNextEnumeratedToken(newName);
+ }
+ }
+
+ return requestManager.getDocumentManager().saveAsNew(vcImage, newName);
+
+ }
+
+ private AsynchClientTask getSaveImageAndGeometryTask() {
+
+ final AsynchClientTask saveImageAndGeometryTask = new AsynchClientTask("creating geometry",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ this.getClientTaskStatusSupport().setMessage("Getting new Geometry name...");
+ String newGeometryName = null;
+ while (true) {
+ newGeometryName = ClientRequestManager.this.getMdiManager().getDatabaseWindowManager()
+ .showSaveDialog(((Geometry) hashTable.get("doc")).getDocumentType(),
+ (Component) hashTable.get(ClientRequestManager.GUI_PARENT),
+ (newGeometryName == null ? "NewGeometry" : newGeometryName));
+ if (newGeometryName == null || newGeometryName.trim().length() == 0) {
+ newGeometryName = null;
+ DialogUtils.showWarningDialog((Component) hashTable.get(ClientRequestManager.GUI_PARENT),
+ "New Geometry name cannot be empty.");
+ continue;
+ }
+ // Check name conflict
+ GeometryInfo[] geometryInfos = ClientRequestManager.this.getDocumentManager().getGeometryInfos();
+ boolean bNameConflict = false;
+ for (int i = 0; i < geometryInfos.length; i++) {
+ if (geometryInfos[i].getVersion().getOwner()
+ .equals(ClientRequestManager.this.getDocumentManager().getUser())) {
+ if (geometryInfos[i].getVersion().getName().equals(newGeometryName)) {
+ bNameConflict = true;
+ break;
+ }
+ }
+ }
+ if (bNameConflict) {
+ DialogUtils.showWarningDialog((Component) hashTable.get(ClientRequestManager.GUI_PARENT),
+ "A Geometry with name " + newGeometryName
+ + " already exists. Choose a different name.");
+ continue;
+ } else {
+ break;
+ }
+ }
+ this.getClientTaskStatusSupport().setMessage("Saving image portion of Geometry...");
+ saveImageAutoName(ClientRequestManager.this,
+ ((Geometry) hashTable.get("doc")).getGeometrySpec().getImage());
+ this.getClientTaskStatusSupport().setMessage("Saving final Geometry...");
+ ClientRequestManager.this.getDocumentManager().saveAsNew((Geometry) hashTable.get("doc"),
+ newGeometryName);
+ }
+ };
+
+ return saveImageAndGeometryTask;
+ }
+
+ /**
+ * onVCellMessageEvent method comment.
+ */
+ public void onVCellMessageEvent(final VCellMessageEvent event) {
+ if (event.getEventTypeID() == VCellMessageEvent.VCELL_MESSAGEEVENT_TYPE_BROADCAST) {
+ DialogUtils.showInfoDialog(this.getMdiManager().getFocusedWindowManager().getComponent(), "Message for All VCell Users",
+ event.getMessageData().getData().toString());
+ }
+ }
//private void openBnglDebugger() {
//try {
@@ -3133,283 +3134,278 @@ public void onVCellMessageEvent(final VCellMessageEvent event) {
//}
//}
- /**
- * DocumentWindowManager hash table key
- */
- private final static String WIN_MGR_KEY = "WIN_MGR_KY";
-
- private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindowManager requester,
- final boolean inNewWindow) {
-
- final String DOCUMENT_INFO = "documentInfo";
- final String SEDML_TASK = "SedMLTask";
- final String SEDML_MODELS = "SedMLModels";
- final String BNG_UNIT_SYSTEM = "bngUnitSystem";
- final String BMDB_DEFAULT_APPLICATION = "Deterministic";
- /* asynchronous and not blocking any window */
- bOpening = true;
- Hashtable hashTable = new Hashtable();
-
- // may want to insert corrected VCDocumentInfo later if our import debugger
- // corrects it (BNGL Debugger).
- hashTable.put(DOCUMENT_INFO, documentInfo);
- hashTable.put("isBMDB", false);
- hashTable.put("isSEDML", false);
-
-
- // start a thread that gets it and updates the GUI by creating a new document
- // desktop
- String taskName = null;
- if (documentInfo instanceof ExternalDocInfo) {
- taskName = "Importing document";
- ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
-
- File file = externalDocInfo.getFile();
- if (file != null && !file.getName().isEmpty() && file.getName().endsWith("bngl")) {
-
- BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
- String fileText;
- String originalFileText;
- try {
- fileText = BeanUtils.readBytesFromFile(file, null);
- originalFileText = new String(fileText);
- } catch (IOException e1) {
- e1.printStackTrace();
- DialogUtils.showErrorDialog(requester.getComponent(),
- "Error reading file " + file.getPath() + "");
- return;
- }
- Reader reader = externalDocInfo.getReader();
- boolean bException = true;
- while (bException) {
- try {
- BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
- boolean bStochastic = true;
- boolean bRuleBased = true;
- SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("temp NFSim app",
- SimulationContext.Application.RULE_BASED_STOCHASTIC);
- List appList = new ArrayList();
- appList.add(ruleBasedSimContext);
-
- RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
- RbmUtils.reactionRuleLabelIndex = 0;
- RbmUtils.reactionRuleNames.clear();
- ASTModel astModel = RbmUtils.importBnglFile(reader);
- // TODO: if we imported a unit system from the bngl file, update bngUnitSystem
- // at this point
- // for now, hasUnitSystem() always returns false
- if (astModel.hasUnitSystem()) {
- bngUnitSystem = astModel.getUnitSystem();
- }
- if (astModel.hasCompartments()) {
- Structure struct = bioModel.getModel().getStructure(0);
- if (struct != null) {
- bioModel.getModel().removeStructure(struct, true);
- }
- }
- BnglObjectConstructionVisitor constructionVisitor = null;
- if (!astModel.hasMolecularDefinitions()) {
- System.out.println("Molecular Definition Block missing.");
- constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList,
- bngUnitSystem, false);
- } else {
- constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList,
- bngUnitSystem, true);
- }
- astModel.jjtAccept(constructionVisitor, rbmModelContainer);
- bException = false;
- } catch (final Exception e) {
- e.printStackTrace(System.out);
- BNGLDebuggerPanel panel = new BNGLDebuggerPanel(fileText, e);
- int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel,
- "Bngl Debugger: " + file.getName());
- if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
- throw new UserCancelException("Canceling Import");
- }
-
- // inserting corrected DocumentInfo
- fileText = panel.getText();
- externalDocInfo = new ExternalDocInfo(panel.getText());
- reader = externalDocInfo.getReader();
- hashTable.put(DOCUMENT_INFO, externalDocInfo);
- }
- }
-
- if (!originalFileText.equals(fileText)) { // file has been modified
- String message = "Importing " + file.getName()
- + " into vCell.
Overwrite the file on the disk?
";
- message = "" + message + "";
- Object[] options = { "Overwrite and Import", "Import Only", "Cancel" };
- int returnCode = JOptionPane.showOptionDialog(requester.getComponent(), message, "Bngl Debugger",
- JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
- if (returnCode == JOptionPane.YES_OPTION) {
- try {
- FileWriter fw = new FileWriter(file);
- fw.write(fileText);
- fw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else if (returnCode == JOptionPane.CANCEL_OPTION || returnCode == JOptionPane.CLOSED_OPTION) {
- return;
- }
- }
-
- if (!(bngUnitSystem.getOrigin() == BngUnitOrigin.PARSER)) {
- BNGLUnitsPanel panel = new BNGLUnitsPanel(bngUnitSystem);
- int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel,
- " Bngl Units Selector", null, false);
- if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
- return; // TODO: or do nothing and continue with default values?
- } else {
- bngUnitSystem = panel.getUnits();
- }
- }
- hashTable.put(BNG_UNIT_SYSTEM, bngUnitSystem);
- } else if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx")
- || file.getName().toLowerCase().endsWith(".omex"))) {
- try {
- ArchiveComponents ac = null;
- ac = Libsedml.readSEDMLArchive(new FileInputStream(file));
- List docs = ac.getSedmlDocuments();
- if (docs.isEmpty()) {
- throw new RuntimeException("Did not find any supported SEDML files in archive " + file.getName());
- }
- List sedmls = new ArrayList<>();
- for (SEDMLDocument doc : docs) {
- SedML sedml =doc.getSedMLModel();
- if (sedml == null) {
- throw new RuntimeException("Failed importing " + file.getName());
- }
- if (sedml.getModels().isEmpty()) {
- throw new RuntimeException("Unable to find any model in " + file.getName());
- }
- sedmls.add(sedml);
- }
- hashTable.put(SEDML_MODELS, sedmls);
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("failed to read archive: " + e.getMessage(), e);
- }
- }
- } else {
- taskName = "Loading document '" + documentInfo.getVersion().getName() + "' from database";
- }
-
- AsynchClientTask task0 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
- public void run(Hashtable hashTable) throws Exception {
- if (!inNewWindow) {
- // request was to replace the document in an existing window
- getMdiManager().blockWindow(requester.getManagerID());
- }
- }
- };
- AsynchClientTask task1 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- VCDocument doc = null;
- List docs = new ArrayList<>();
- boolean isBMDB = false;
- boolean isSEDML = false;
- VCDocumentInfo documentInfo = (VCDocumentInfo) hashTable.get(DOCUMENT_INFO);
- if (documentInfo instanceof BioModelInfo) {
- BioModelInfo bmi = (BioModelInfo) documentInfo;
- doc = getDocumentManager().getBioModel(bmi);
- } else if (documentInfo instanceof MathModelInfo) {
- MathModelInfo mmi = (MathModelInfo) documentInfo;
- doc = getDocumentManager().getMathModel(mmi);
- } else if (documentInfo instanceof GeometryInfo) {
- GeometryInfo gmi = (GeometryInfo) documentInfo;
- doc = getDocumentManager().getGeometry(gmi);
- } else if (documentInfo instanceof ExternalDocInfo) {
- ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
- File file = externalDocInfo.getFile();
- if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx")
- || file.getName().toLowerCase().endsWith(".omex"))) {
- TranslationLogger transLogger = new TranslationLogger(requester);
- // iterate through one or more SEDML objects
- List sedmls = (List) hashTable.get(SEDML_MODELS);
- for (SedML sedml : sedmls) {
- // default to import all tasks
- List vcdocs = XmlHelper.importSEDML(transLogger, externalDocInfo, sedml, false);
- for (VCDocument vcdoc : vcdocs) {
- docs.add(vcdoc);
- }
- }
- isSEDML = true; // treat the same since OMEX is just and archive with SED-ML file(s)
- } else if (!externalDocInfo.isXML()) {
- if (hashTable.containsKey(BNG_UNIT_SYSTEM)) { // not XML, look for BNGL etc.
- // we use the BngUnitSystem already created during the 1st pass
- BngUnitSystem bngUnitSystem = (BngUnitSystem) hashTable.get(BNG_UNIT_SYSTEM);
- BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
-
- SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("NFSim app",
- SimulationContext.Application.RULE_BASED_STOCHASTIC);
- SimulationContext odeSimContext = bioModel.addNewSimulationContext("BioNetGen app",
- SimulationContext.Application.NETWORK_DETERMINISTIC);
- List appList = new ArrayList();
- appList.add(ruleBasedSimContext);
- appList.add(odeSimContext);
- // set convention for initial conditions in generated application for seed
- // species (concentration or count)
- ruleBasedSimContext.setUsingConcentration(bngUnitSystem.isConcentration(), false);
- odeSimContext.setUsingConcentration(bngUnitSystem.isConcentration(), false);
-
- RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
- RbmUtils.reactionRuleLabelIndex = 0;
- RbmUtils.reactionRuleNames.clear();
- Reader reader = externalDocInfo.getReader();
- ASTModel astModel = RbmUtils.importBnglFile(reader);
- if (bioModel.getModel() != null && bioModel.getModel().getVcMetaData() != null) {
- VCMetaData vcMetaData = bioModel.getModel().getVcMetaData();
- vcMetaData.setFreeTextAnnotation(bioModel, astModel.getProlog());
- }
- if (astModel.hasCompartments()) {
- Structure struct = bioModel.getModel().getStructure(0);
- if (struct != null) {
- bioModel.getModel().removeStructure(struct, true);
- }
- }
-
- BnglObjectConstructionVisitor constructionVisitor = null;
- if (!astModel.hasMolecularDefinitions()) {
- System.out.println(
- "Molecular Definition Block missing. Extracting it from Species, Reactions, Obserbables.");
- constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList,
- bngUnitSystem, false);
- } else {
- constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList,
- bngUnitSystem, true);
- }
- // we'll convert the kinetic parameters to BngUnitSystem inside the
- // visit(ASTKineticsParameter...)
- astModel.jjtAccept(constructionVisitor, rbmModelContainer);
-
- // set the volume in the newly created application to
- // BngUnitSystem.bnglModelVolume
- // TODO: set the right values if we import compartments from the bngl file!
+ /**
+ * DocumentWindowManager hash table key
+ */
+ private final static String WIN_MGR_KEY = "WIN_MGR_KY";
+
+ private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindowManager requester,
+ final boolean inNewWindow) {
+
+ final String DOCUMENT_INFO = "documentInfo";
+ final String SEDML_TASK = "SedMLTask";
+ final String SEDML_MODELS = "SedMLModels";
+ final String BNG_UNIT_SYSTEM = "bngUnitSystem";
+ final String BMDB_DEFAULT_APPLICATION = "Deterministic";
+ /* asynchronous and not blocking any window */
+ this.bOpening = true;
+ Hashtable hashTable = new Hashtable();
+
+ // may want to insert corrected VCDocumentInfo later if our import debugger
+ // corrects it (BNGL Debugger).
+ hashTable.put(DOCUMENT_INFO, documentInfo);
+ hashTable.put("isBMDB", false);
+ hashTable.put("isSEDML", false);
+
+
+ // start a thread that gets it and updates the GUI by creating a new document
+ // desktop
+ String taskName = null;
+ if (documentInfo instanceof ExternalDocInfo externalDocInfo) {
+ taskName = "Importing document";
+
+ File file = externalDocInfo.getFile();
+ if (file != null && !file.getName().isEmpty() && file.getName().endsWith("bngl")) {
+
+ BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
+ String fileText;
+ String originalFileText;
+ try {
+ fileText = BeanUtils.readBytesFromFile(file, null);
+ originalFileText = fileText;
+ } catch (IOException e1) {
+ e1.printStackTrace();
+ DialogUtils.showErrorDialog(requester.getComponent(),
+ "Error reading file " + file.getPath() + "");
+ return;
+ }
+ Reader reader = externalDocInfo.getReader();
+ boolean bException = true;
+ while (bException) {
+ try {
+ BioModel bioModel = this.createDefaultBioModelDocument(bngUnitSystem);
+ boolean bStochastic = true;
+ boolean bRuleBased = true;
+ SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("temp NFSim app",
+ SimulationContext.Application.RULE_BASED_STOCHASTIC);
+ List appList = new ArrayList();
+ appList.add(ruleBasedSimContext);
+
+ RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
+ RbmUtils.reactionRuleLabelIndex = 0;
+ RbmUtils.reactionRuleNames.clear();
+ ASTModel astModel = RbmUtils.importBnglFile(reader);
+ // TODO: if we imported a unit system from the bngl file, update bngUnitSystem
+ // at this point
+ // for now, hasUnitSystem() always returns false
+ if (astModel.hasUnitSystem()) {
+ bngUnitSystem = astModel.getUnitSystem();
+ }
+ if (astModel.hasCompartments()) {
+ Structure struct = bioModel.getModel().getStructure(0);
+ if (struct != null) {
+ bioModel.getModel().removeStructure(struct, true);
+ }
+ }
+ BnglObjectConstructionVisitor constructionVisitor = null;
+ if (!astModel.hasMolecularDefinitions()) {
+ System.out.println("Molecular Definition Block missing.");
+ constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList,
+ bngUnitSystem, false);
+ } else {
+ constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList,
+ bngUnitSystem, true);
+ }
+ astModel.jjtAccept(constructionVisitor, rbmModelContainer);
+ bException = false;
+ } catch (final Exception e) {
+ e.printStackTrace(System.out);
+ BNGLDebuggerPanel panel = new BNGLDebuggerPanel(fileText, e);
+ int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel,
+ "Bngl Debugger: " + file.getName());
+ if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
+ throw new UserCancelException("Canceling Import");
+ }
+
+ // inserting corrected DocumentInfo
+ fileText = panel.getText();
+ externalDocInfo = new ExternalDocInfo(panel.getText());
+ reader = externalDocInfo.getReader();
+ hashTable.put(DOCUMENT_INFO, externalDocInfo);
+ }
+ }
+
+ if (!originalFileText.equals(fileText)) { // file has been modified
+ String message = "Importing " + file.getName()
+ + " into vCell.
Overwrite the file on the disk?
";
+ message = "" + message + "";
+ Object[] options = {"Overwrite and Import", "Import Only", "Cancel"};
+ int returnCode = JOptionPane.showOptionDialog(requester.getComponent(), message, "Bngl Debugger",
+ JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
+ if (returnCode == JOptionPane.YES_OPTION) {
+ try {
+ FileWriter fw = new FileWriter(file);
+ fw.write(fileText);
+ fw.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ } else if (returnCode == JOptionPane.CANCEL_OPTION || returnCode == JOptionPane.CLOSED_OPTION) {
+ return;
+ }
+ }
+
+ if (!(bngUnitSystem.getOrigin() == BngUnitOrigin.PARSER)) {
+ BNGLUnitsPanel panel = new BNGLUnitsPanel(bngUnitSystem);
+ int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel,
+ " Bngl Units Selector", null, false);
+ if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
+ return; // TODO: or do nothing and continue with default values?
+ } else {
+ bngUnitSystem = panel.getUnits();
+ }
+ }
+ hashTable.put(BNG_UNIT_SYSTEM, bngUnitSystem);
+ } else if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx")
+ || file.getName().toLowerCase().endsWith(".omex"))) {
+ try {
+ ArchiveComponents ac = null;
+ ac = Libsedml.readSEDMLArchive(new FileInputStream(file));
+ List docs = ac.getSedmlDocuments();
+ if (docs.isEmpty()) {
+ throw new RuntimeException("Did not find any supported SEDML files in archive " + file.getName());
+ }
+ List sedmls = new ArrayList<>();
+ for (SEDMLDocument doc : docs) {
+ SedML sedml = doc.getSedMLModel();
+ if (sedml == null) {
+ throw new RuntimeException("Failed importing " + file.getName());
+ }
+ if (sedml.getModels().isEmpty()) {
+ throw new RuntimeException("Unable to find any model in " + file.getName());
+ }
+ sedmls.add(sedml);
+ }
+ hashTable.put(SEDML_MODELS, sedmls);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new RuntimeException("failed to read archive: " + e.getMessage(), e);
+ }
+ }
+ } else {
+ taskName = "Loading document '" + documentInfo.getVersion().getName() + "' from database";
+ }
+
+ AsynchClientTask task0 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
+ public void run(Hashtable hashTable) throws Exception {
+ if (!inNewWindow) {
+ // request was to replace the document in an existing window
+ ClientRequestManager.this.getMdiManager().blockWindow(requester.getManagerID());
+ }
+ }
+ };
+ AsynchClientTask task1 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ VCDocument doc = null;
+ List docs = new ArrayList<>();
+ boolean isBMDB = false;
+ boolean isSEDML = false;
+ VCDocumentInfo documentInfo = (VCDocumentInfo) hashTable.get(DOCUMENT_INFO);
+ if (documentInfo instanceof BioModelInfo bmi) {
+ doc = ClientRequestManager.this.getDocumentManager().getBioModel(bmi);
+ } else if (documentInfo instanceof MathModelInfo mmi) {
+ doc = ClientRequestManager.this.getDocumentManager().getMathModel(mmi);
+ } else if (documentInfo instanceof GeometryInfo gmi) {
+ doc = ClientRequestManager.this.getDocumentManager().getGeometry(gmi);
+ } else if (documentInfo instanceof ExternalDocInfo externalDocInfo) {
+ File file = externalDocInfo.getFile();
+ if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx")
+ || file.getName().toLowerCase().endsWith(".omex"))) {
+ TranslationLogger transLogger = new TranslationLogger(requester);
+ // iterate through one or more SEDML objects
+ List sedmls = (List) hashTable.get(SEDML_MODELS);
+ for (SedML sedml : sedmls) {
+ // default to import all tasks
+ List vcdocs = XmlHelper.importSEDML(transLogger, externalDocInfo, sedml, false);
+ for (VCDocument vcdoc : vcdocs) {
+ docs.add(vcdoc);
+ }
+ }
+ isSEDML = true; // treat the same since OMEX is just and archive with SED-ML file(s)
+ } else if (!externalDocInfo.isXML()) {
+ if (hashTable.containsKey(BNG_UNIT_SYSTEM)) { // not XML, look for BNGL etc.
+ // we use the BngUnitSystem already created during the 1st pass
+ BngUnitSystem bngUnitSystem = (BngUnitSystem) hashTable.get(BNG_UNIT_SYSTEM);
+ BioModel bioModel = ClientRequestManager.this.createDefaultBioModelDocument(bngUnitSystem);
+
+ SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("NFSim app",
+ SimulationContext.Application.RULE_BASED_STOCHASTIC);
+ SimulationContext odeSimContext = bioModel.addNewSimulationContext("BioNetGen app",
+ SimulationContext.Application.NETWORK_DETERMINISTIC);
+ List appList = new ArrayList();
+ appList.add(ruleBasedSimContext);
+ appList.add(odeSimContext);
+ // set convention for initial conditions in generated application for seed
+ // species (concentration or count)
+ ruleBasedSimContext.setUsingConcentration(bngUnitSystem.isConcentration(), false);
+ odeSimContext.setUsingConcentration(bngUnitSystem.isConcentration(), false);
+
+ RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
+ RbmUtils.reactionRuleLabelIndex = 0;
+ RbmUtils.reactionRuleNames.clear();
+ Reader reader = externalDocInfo.getReader();
+ ASTModel astModel = RbmUtils.importBnglFile(reader);
+ if (bioModel.getModel() != null && bioModel.getModel().getVcMetaData() != null) {
+ VCMetaData vcMetaData = bioModel.getModel().getVcMetaData();
+ vcMetaData.setFreeTextAnnotation(bioModel, astModel.getProlog());
+ }
+ if (astModel.hasCompartments()) {
+ Structure struct = bioModel.getModel().getStructure(0);
+ if (struct != null) {
+ bioModel.getModel().removeStructure(struct, true);
+ }
+ }
+
+ BnglObjectConstructionVisitor constructionVisitor = null;
+ if (!astModel.hasMolecularDefinitions()) {
+ System.out.println(
+ "Molecular Definition Block missing. Extracting it from Species, Reactions, Obserbables.");
+ constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList,
+ bngUnitSystem, false);
+ } else {
+ constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList,
+ bngUnitSystem, true);
+ }
+ // we'll convert the kinetic parameters to BngUnitSystem inside the
+ // visit(ASTKineticsParameter...)
+ astModel.jjtAccept(constructionVisitor, rbmModelContainer);
+
+ // set the volume in the newly created application to
+ // BngUnitSystem.bnglModelVolume
+ // TODO: set the right values if we import compartments from the bngl file!
// if(!bngUnitSystem.isConcentration()) {
- Expression sizeExpression = new Expression(bngUnitSystem.getVolume());
- ruleBasedSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter()
- .setExpression(sizeExpression);
- odeSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter()
- .setExpression(sizeExpression);
+ Expression sizeExpression = new Expression(bngUnitSystem.getVolume());
+ ruleBasedSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter()
+ .setExpression(sizeExpression);
+ odeSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter()
+ .setExpression(sizeExpression);
// }
- // we remove the NFSim application if any seed species is clamped because NFSim
- // doesn't know what to do with it
- boolean bClamped = false;
- for (SpeciesContextSpec scs : ruleBasedSimContext.getReactionContext()
- .getSpeciesContextSpecs()) {
- if (scs.isConstant()) {
- bClamped = true;
- break;
- }
- }
- if (bClamped) {
- bioModel.removeSimulationContext(ruleBasedSimContext);
- }
+ // we remove the NFSim application if any seed species is clamped because NFSim
+ // doesn't know what to do with it
+ boolean bClamped = false;
+ for (SpeciesContextSpec scs : ruleBasedSimContext.getReactionContext()
+ .getSpeciesContextSpecs()) {
+ if (scs.isConstant()) {
+ bClamped = true;
+ break;
+ }
+ }
+ if (bClamped) {
+ bioModel.removeSimulationContext(ruleBasedSimContext);
+ }
// // TODO: DON'T delete this code
// // the code below is needed if we also want to create simulations, example for 1 rule based simulation
@@ -3419,1143 +3415,1132 @@ public void run(Hashtable hashTable) throws Exception {
// ruleBasedSimContext.refreshMathDescription(callback,networkGenerationRequirements);
// Simulation sim = ruleBasedSimContext.addNewSimulation(SimulationOwner.DEFAULT_SIM_NAME_PREFIX,callback,networkGenerationRequirements);
- doc = bioModel;
- }
- } else { // is XML
- try (TranslationLogger transLogger = new TranslationLogger(requester)) {
- XMLSource xmlSource = externalDocInfo.createXMLSource();
- org.jdom.Element rootElement = xmlSource.getXmlDoc().getRootElement();
- String xmlType = rootElement.getName();
- String modelXmlType = null;
- if (xmlType.equals(XMLTags.VcmlRootNodeTag)) {
- // For now, assuming that element has only one child (biomodel, mathmodel
- // or geometry).
- // Will deal with multiple children of Element when we get to model
- // composition.
- @SuppressWarnings("unchecked")
- List childElementList = rootElement.getChildren();
- Element modelElement = childElementList.get(0); // assuming first child is the biomodel,
- // mathmodel or geometry.
- modelXmlType = modelElement.getName();
- }
- if (xmlType.equals(XMLTags.BioModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag)
- && modelXmlType.equals(XMLTags.BioModelTag))) {
- doc = XmlHelper.XMLToBioModel(xmlSource);
- } else if (xmlType.equals(XMLTags.MathModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag)
- && modelXmlType.equals(XMLTags.MathModelTag))) {
- doc = XmlHelper.XMLToMathModel(xmlSource);
- } else if (xmlType.equals(XMLTags.GeometryTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag)
- && modelXmlType.equals(XMLTags.GeometryTag))) {
- doc = XmlHelper.XMLToGeometry(xmlSource);
- } else if (xmlType.equals(XMLTags.SbmlRootNodeTag)) {
- Namespace namespace = rootElement.getNamespace(XMLTags.SBML_SPATIAL_NS_PREFIX);
- isBMDB = externalDocInfo.isBioModelsNet();
- boolean bIsSpatial = (namespace == null) ? false : true;
- doc = XmlHelper.importSBML(transLogger, xmlSource, bIsSpatial);
- } else if (xmlType.equals(XMLTags.CellmlRootNodeTag)) {
- if (requester instanceof BioModelWindowManager) {
- doc = XmlHelper.importBioCellML(transLogger, xmlSource);
- } else {
- doc = XmlHelper.importMathCellML(transLogger, xmlSource);
- }
- } else if (xmlType.equals(MicroscopyXMLTags.FRAPStudyTag)) {
- doc = VFrapXmlHelper.VFRAPToBioModel(hashTable, xmlSource, getDocumentManager(),
- requester);
- } else if (xmlType.equals(XMLTags.SedMLTypeTag)) {
- File sedmlFile = xmlSource.getXmlFile();
- SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
- if (sedml == null) {
- throw new RuntimeException("Failed importing " + file.getName());
- }
- if (sedml.getModels().isEmpty()) {
- throw new RuntimeException("Unable to find any model in " + file.getName());
- }
- List sedmls = new ArrayList<>();
- sedmls.add(sedml);
- hashTable.put(SEDML_MODELS, sedmls);
-
- // default to import all tasks
- List vcdocs = XmlHelper.importSEDML(transLogger, externalDocInfo, sedml, false);
- for (VCDocument vcdoc : vcdocs) {
- docs.add(vcdoc);
- }
-
- isSEDML = true;
- } else { // unknown XML format
- throw new RuntimeException(
- "unsupported XML format, first element tag is <" + rootElement.getName() + ">");
- }
- if (externalDocInfo.getDefaultName() != null) {
- doc.setName(externalDocInfo.getDefaultName());
- }
- }
- }
- if (doc == null && docs == null) {
- File f = externalDocInfo.getFile();
- if (f != null) {
- throw new RuntimeException("Unable to determine type of file " + f.getCanonicalPath());
- }
- throw new ProgrammingException();
- }
- }
- // create biopax objects using annotation
- if (doc instanceof BioModel) {
- BioModel bioModel = (BioModel) doc;
- try {
- bioModel.getVCMetaData().createBioPaxObjects(bioModel);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- requester.prepareDocumentToLoad(doc, inNewWindow);
- hashTable.put("isBMDB", isBMDB);
- hashTable.put("isSEDML", isSEDML);
- if (!isSEDML) {
- hashTable.put("doc", doc);
- } else {
- hashTable.put("docs", docs);
- }
- }
- };
-
- AsynchClientTask task2 = new AsynchClientTask("Showing document", AsynchClientTask.TASKTYPE_SWING_BLOCKING,
- false, false) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- try {
- Throwable exc = (Throwable) hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR);
- if (exc == null) {
- boolean isSEDML = (boolean) hashTable.get("isSEDML");
- if (isSEDML) {
- List docs = (List) hashTable.get("docs");
- List windowManagers = new ArrayList();
- for (VCDocument doc : docs) {
- DocumentWindowManager windowManager = createDocumentWindowManager(doc);
- getMdiManager().createNewDocumentWindow(windowManager);
- windowManagers.add(windowManager);
- }
- hashTable.put("managers", windowManagers);
- hashTable.put("docs", docs);
- } else {
- VCDocument doc = (VCDocument) hashTable.get("doc");
- DocumentWindowManager windowManager = null;
- if (inNewWindow) {
- windowManager = createDocumentWindowManager(doc);
- // request was to create a new top-level window with this doc
- getMdiManager().createNewDocumentWindow(windowManager);
-
- } else {
- // request was to replace the document in an existing window
- windowManager = (DocumentWindowManager) requester;
- getMdiManager().setCanonicalTitle(requester.getManagerID());
- windowManager.resetDocument(doc);
- }
- hashTable.put(WIN_MGR_KEY, windowManager);
- hashTable.put("doc", doc);
- }
- }
- } catch(Exception ex) {
- ex.printStackTrace();
- // TODO: check why getMdiManager().createNewDocumentWindow(windowManager) fails sometimes
- } finally {
- if (!inNewWindow) {
- getMdiManager().unBlockWindow(requester.getManagerID());
- }
- bOpening = false;
- }
- }
- };
- AsynchClientTask task3 = new AsynchClientTask("Special Layout", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false,
- false) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- if (documentInfo instanceof ExternalDocInfo) {
- ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
- boolean isSEDML = (boolean) hashTable.get("isSEDML");
- if (externalDocInfo.isBioModelsNet() || externalDocInfo.isFromXmlFile() || (!isSEDML && !externalDocInfo.isFromVcmlFile())) {
- DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
- if (windowManager instanceof BioModelWindowManager) {
- ((BioModelWindowManager) windowManager).specialLayout();
- }
- }
- if (isSEDML) {
- List windowManagers = (List) hashTable.get("managers");
- if(windowManagers != null) {
- for (DocumentWindowManager manager : windowManagers) {
- ((BioModelWindowManager) manager).specialLayout();
- }
- }
- }
- }
- }
- };
- AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus",
- AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
-
- AsynchClientTask task6 = new AsynchClientTask("Renaming, please wait...",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, false, false) { // TASKTYPE_NONSWING_BLOCKING
- @Override
- public void run(Hashtable hashTable) throws Exception {
- VCDocument doc = (VCDocument) hashTable.get("doc");
- if(!(doc instanceof BioModel)) {
- return;
- }
- boolean isBMDB = (boolean) hashTable.get("isBMDB");
- if (documentInfo instanceof ExternalDocInfo) {
- if (isBMDB) {
- idToNameConversion(doc);
- }
- }
- if (isBMDB) {
- BioModel bioModel = (BioModel) doc;
- SimulationContext simulationContext = bioModel.getSimulationContext(0);
- simulationContext.setName(BMDB_DEFAULT_APPLICATION);
- try {
- simulationContext.updateAll(false);
- MathDescription mathDesc = simulationContext.getMathDescription();
-
- Simulation sim = new Simulation(mathDesc, simulationContext);
- sim.setName(simulationContext.getBioModel().getFreeSimulationName());
- simulationContext.addSimulation(sim);
- bioModel.refreshDependencies();
-
- } catch (MappingException e1) {
- e1.printStackTrace();
- }
- hashTable.put("doc", doc);
- }
- }
- };
- ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable,
- new AsynchClientTask[] { task0, task1, task6, task2, task3, task4 }, false);
- }
-
- private static boolean isRestrictedXYZT(String name, BioModel vcBioModel) {
-
- ReservedSymbol rs = vcBioModel.getModel().getReservedSymbolByName(name);
- if (rs == null) {
- return false;
- }
- if (rs.isX() || rs.isY() || rs.isZ() || rs.isTime()) {
- return true;
- }
- return false;
- }
-
- public static void idToNameConversion(VCDocument vcDoc) {
- if (!(vcDoc instanceof BioModel)) {
- return;
- }
- BioModel vcBioModel = (BioModel) vcDoc;
- vcBioModel.getSimulationContext(0).setbIgnoreEvents(true);
- Map entitiesToRename = new LinkedHashMap<>();
-
- for (SpeciesContext sc : vcBioModel.getModel().getSpeciesContexts()) {
- String id = sc.getName();
- String name = sc.getSbmlName();
- if (name == null || name.isEmpty()) {
- continue;
- }
- if(id.equals(name)) {
- continue;
- }
- if (isRestrictedXYZT(name, vcBioModel)) {
- continue;
- }
- name = TokenMangler.fixTokenStrict(name, 60);
- while (true) {
- if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) {
- break;
- }
- name = TokenMangler.getNextEnumeratedToken(name);
- }
- if (id.equals(name)) {
- continue;
- }
- try {
- System.out.println(name + " <-- " + id);
- sc.setName(name);
- } catch (PropertyVetoException e) {
- e.printStackTrace(); // we just keep the id rather than abort
- }
- entitiesToRename.put(id, name);
- }
-
- for (ModelParameter mp : vcBioModel.getModel().getModelParameters()) {
- String id = mp.getName();
- String name = mp.getSbmlName();
- if (name == null || name.isEmpty()) {
- continue;
- }
- if(id.equals(name)) {
- continue;
- }
- if (isRestrictedXYZT(name, vcBioModel)) {
- continue;
- }
- name = TokenMangler.fixTokenStrict(name, 60);
- while (true) {
- if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) {
- break;
- }
- name = TokenMangler.getNextEnumeratedToken(name);
- }
- if (id.equals(name)) {
- continue;
- }
- try {
- System.out.println(name + " <-- " + id);
- mp.setName(name);
- } catch (PropertyVetoException e) {
- e.printStackTrace();
- }
- entitiesToRename.put(id, name);
- }
- for(Structure struct : vcBioModel.getModel().getStructures()) {
- String id = struct.getName();
- String name = struct.getSbmlName();
- if(name == null || name.isEmpty()) {
- continue;
- }
- if(id.equals(name)) {
- continue;
- }
- if(isRestrictedXYZT(name, vcBioModel)) {
- continue;
- }
- name = TokenMangler.fixTokenStrict(name, 60);
- while (true) {
- if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) {
- break;
- }
- name = TokenMangler.getNextEnumeratedToken(name);
- }
- if(id.equals(name)) {
- continue;
- }
- try {
- System.out.println(name + " <-- " + id);
- struct.setName(name, true);
- } catch(PropertyVetoException e) {
- e.printStackTrace();
- }
- entitiesToRename.put(id, name);
- }
- vcBioModel.getSimulationContext(0).substituteChangedNamesInExpressions(entitiesToRename);
-
- for (ReactionStep rs : vcBioModel.getModel().getReactionSteps()) {
- String id = rs.getName();
- String name = rs.getSbmlName();
- if (name == null || name.isEmpty()) {
- continue;
- }
- if(id.equals(name)) {
- continue;
- }
- if (isRestrictedXYZT(name, vcBioModel)) {
- continue;
- }
+ doc = bioModel;
+ }
+ } else { // is XML
+ try (TranslationLogger transLogger = new TranslationLogger(requester)) {
+ XMLSource xmlSource = externalDocInfo.createXMLSource();
+ org.jdom.Element rootElement = xmlSource.getXmlDoc().getRootElement();
+ String xmlType = rootElement.getName();
+ String modelXmlType = null;
+ if (xmlType.equals(XMLTags.VcmlRootNodeTag)) {
+ // For now, assuming that element has only one child (biomodel, mathmodel
+ // or geometry).
+ // Will deal with multiple children of Element when we get to model
+ // composition.
+ @SuppressWarnings("unchecked")
+ List childElementList = rootElement.getChildren();
+ Element modelElement = childElementList.get(0); // assuming first child is the biomodel,
+ // mathmodel or geometry.
+ modelXmlType = modelElement.getName();
+ }
+ if (xmlType.equals(XMLTags.BioModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag)
+ && modelXmlType.equals(XMLTags.BioModelTag))) {
+ doc = XmlHelper.XMLToBioModel(xmlSource);
+ } else if (xmlType.equals(XMLTags.MathModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag)
+ && modelXmlType.equals(XMLTags.MathModelTag))) {
+ doc = XmlHelper.XMLToMathModel(xmlSource);
+ } else if (xmlType.equals(XMLTags.GeometryTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag)
+ && modelXmlType.equals(XMLTags.GeometryTag))) {
+ doc = XmlHelper.XMLToGeometry(xmlSource);
+ } else if (xmlType.equals(XMLTags.SbmlRootNodeTag)) {
+ Namespace namespace = rootElement.getNamespace(XMLTags.SBML_SPATIAL_NS_PREFIX);
+ isBMDB = externalDocInfo.isBioModelsNet();
+ boolean bIsSpatial = namespace != null;
+ doc = XmlHelper.importSBML(transLogger, xmlSource, bIsSpatial);
+ } else if (xmlType.equals(XMLTags.CellmlRootNodeTag)) {
+ if (requester instanceof BioModelWindowManager) {
+ doc = XmlHelper.importBioCellML(transLogger, xmlSource);
+ } else {
+ doc = XmlHelper.importMathCellML(transLogger, xmlSource);
+ }
+ } else if (xmlType.equals(MicroscopyXMLTags.FRAPStudyTag)) {
+ doc = VFrapXmlHelper.VFRAPToBioModel(hashTable, xmlSource, ClientRequestManager.this.getDocumentManager(),
+ requester);
+ } else if (xmlType.equals(XMLTags.SedMLTypeTag)) {
+ File sedmlFile = xmlSource.getXmlFile();
+ SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
+ if (sedml == null) {
+ throw new RuntimeException("Failed importing " + file.getName());
+ }
+ if (sedml.getModels().isEmpty()) {
+ throw new RuntimeException("Unable to find any model in " + file.getName());
+ }
+ List sedmls = new ArrayList<>();
+ sedmls.add(sedml);
+ hashTable.put(SEDML_MODELS, sedmls);
+
+ // default to import all tasks
+ List vcdocs = XmlHelper.importSEDML(transLogger, externalDocInfo, sedml, false);
+ for (VCDocument vcdoc : vcdocs) {
+ docs.add(vcdoc);
+ }
+
+ isSEDML = true;
+ } else { // unknown XML format
+ throw new RuntimeException(
+ "unsupported XML format, first element tag is <" + rootElement.getName() + ">");
+ }
+ if (externalDocInfo.getDefaultName() != null) {
+ doc.setName(externalDocInfo.getDefaultName());
+ }
+ }
+ }
+ if (doc == null && docs == null) {
+ File f = externalDocInfo.getFile();
+ if (f != null) {
+ throw new RuntimeException("Unable to determine type of file " + f.getCanonicalPath());
+ }
+ throw new ProgrammingException();
+ }
+ }
+ // create biopax objects using annotation
+ if (doc instanceof BioModel bioModel) {
+ try {
+ bioModel.getVCMetaData().createBioPaxObjects(bioModel);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ requester.prepareDocumentToLoad(doc, inNewWindow);
+ hashTable.put("isBMDB", isBMDB);
+ hashTable.put("isSEDML", isSEDML);
+ if (!isSEDML) {
+ hashTable.put("doc", doc);
+ } else {
+ hashTable.put("docs", docs);
+ }
+ }
+ };
+
+ AsynchClientTask task2 = new AsynchClientTask("Showing document", AsynchClientTask.TASKTYPE_SWING_BLOCKING,
+ false, false) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ try {
+ Throwable exc = (Throwable) hashTable.get(swingthreads.TaskEventKeys.TASK_ABORTED_BY_ERROR.toString());
+ if (exc == null) {
+ boolean isSEDML = (boolean) hashTable.get("isSEDML");
+ if (isSEDML) {
+ List docs = (List) hashTable.get("docs");
+ List windowManagers = new ArrayList();
+ for (VCDocument doc : docs) {
+ DocumentWindowManager windowManager = ClientRequestManager.this.createDocumentWindowManager(doc);
+ ClientRequestManager.this.getMdiManager().createNewDocumentWindow(windowManager);
+ windowManagers.add(windowManager);
+ }
+ hashTable.put("managers", windowManagers);
+ hashTable.put("docs", docs);
+ } else {
+ VCDocument doc = (VCDocument) hashTable.get("doc");
+ DocumentWindowManager windowManager = null;
+ if (inNewWindow) {
+ windowManager = ClientRequestManager.this.createDocumentWindowManager(doc);
+ // request was to create a new top-level window with this doc
+ ClientRequestManager.this.getMdiManager().createNewDocumentWindow(windowManager);
+
+ } else {
+ // request was to replace the document in an existing window
+ windowManager = (DocumentWindowManager) requester;
+ ClientRequestManager.this.getMdiManager().setCanonicalTitle(requester.getManagerID());
+ windowManager.resetDocument(doc);
+ }
+ hashTable.put(WIN_MGR_KEY, windowManager);
+ hashTable.put("doc", doc);
+ }
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ // TODO: check why getMdiManager().createNewDocumentWindow(windowManager) fails sometimes
+ } finally {
+ if (!inNewWindow) {
+ ClientRequestManager.this.getMdiManager().unBlockWindow(requester.getManagerID());
+ }
+ ClientRequestManager.this.bOpening = false;
+ }
+ }
+ };
+ AsynchClientTask task3 = new AsynchClientTask("Special Layout", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false,
+ false) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ if (documentInfo instanceof ExternalDocInfo externalDocInfo) {
+ boolean isSEDML = (boolean) hashTable.get("isSEDML");
+ if (externalDocInfo.isBioModelsNet() || externalDocInfo.isFromXmlFile() || (!isSEDML && !externalDocInfo.isFromVcmlFile())) {
+ DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
+ if (windowManager instanceof BioModelWindowManager) {
+ ((BioModelWindowManager) windowManager).specialLayout();
+ }
+ }
+ if (isSEDML) {
+ List windowManagers = (List) hashTable.get("managers");
+ if (windowManagers != null) {
+ for (DocumentWindowManager manager : windowManagers) {
+ ((BioModelWindowManager) manager).specialLayout();
+ }
+ }
+ }
+ }
+ }
+ };
+ AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus",
+ AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
+
+ AsynchClientTask task6 = new AsynchClientTask("Renaming, please wait...",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, false, false) { // TASKTYPE_NONSWING_BLOCKING
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ VCDocument doc = (VCDocument) hashTable.get("doc");
+ if (!(doc instanceof BioModel)) {
+ return;
+ }
+ boolean isBMDB = (boolean) hashTable.get("isBMDB");
+ if (documentInfo instanceof ExternalDocInfo) {
+ if (isBMDB) {
+ idToNameConversion(doc);
+ }
+ }
+ if (isBMDB) {
+ BioModel bioModel = (BioModel) doc;
+ SimulationContext simulationContext = bioModel.getSimulationContext(0);
+ simulationContext.setName(BMDB_DEFAULT_APPLICATION);
+ try {
+ simulationContext.updateAll(false);
+ MathDescription mathDesc = simulationContext.getMathDescription();
+
+ Simulation sim = new Simulation(mathDesc, simulationContext);
+ sim.setName(simulationContext.getBioModel().getFreeSimulationName());
+ simulationContext.addSimulation(sim);
+ bioModel.refreshDependencies();
+
+ } catch (MappingException e1) {
+ e1.printStackTrace();
+ }
+ hashTable.put("doc", doc);
+ }
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable,
+ new AsynchClientTask[]{task0, task1, task6, task2, task3, task4}, false);
+ }
+
+ private static boolean isRestrictedXYZT(String name, BioModel vcBioModel) {
+
+ ReservedSymbol rs = vcBioModel.getModel().getReservedSymbolByName(name);
+ if (rs == null) {
+ return false;
+ }
+ return rs.isX() || rs.isY() || rs.isZ() || rs.isTime();
+ }
+
+ public static void idToNameConversion(VCDocument vcDoc) {
+ if (!(vcDoc instanceof BioModel vcBioModel)) {
+ return;
+ }
+ vcBioModel.getSimulationContext(0).setbIgnoreEvents(true);
+ Map entitiesToRename = new LinkedHashMap<>();
+
+ for (SpeciesContext sc : vcBioModel.getModel().getSpeciesContexts()) {
+ String id = sc.getName();
+ String name = sc.getSbmlName();
+ if (name == null || name.isEmpty()) {
+ continue;
+ }
+ if (id.equals(name)) {
+ continue;
+ }
+ if (isRestrictedXYZT(name, vcBioModel)) {
+ continue;
+ }
+ name = TokenMangler.fixTokenStrict(name, 60);
+ while (true) {
+ if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) {
+ break;
+ }
+ name = TokenMangler.getNextEnumeratedToken(name);
+ }
+ if (id.equals(name)) {
+ continue;
+ }
+ try {
+ System.out.println(name + " <-- " + id);
+ sc.setName(name);
+ } catch (PropertyVetoException e) {
+ e.printStackTrace(); // we just keep the id rather than abort
+ }
+ entitiesToRename.put(id, name);
+ }
+
+ for (ModelParameter mp : vcBioModel.getModel().getModelParameters()) {
+ String id = mp.getName();
+ String name = mp.getSbmlName();
+ if (name == null || name.isEmpty()) {
+ continue;
+ }
+ if (id.equals(name)) {
+ continue;
+ }
+ if (isRestrictedXYZT(name, vcBioModel)) {
+ continue;
+ }
+ name = TokenMangler.fixTokenStrict(name, 60);
+ while (true) {
+ if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) {
+ break;
+ }
+ name = TokenMangler.getNextEnumeratedToken(name);
+ }
+ if (id.equals(name)) {
+ continue;
+ }
+ try {
+ System.out.println(name + " <-- " + id);
+ mp.setName(name);
+ } catch (PropertyVetoException e) {
+ e.printStackTrace();
+ }
+ entitiesToRename.put(id, name);
+ }
+ for (Structure struct : vcBioModel.getModel().getStructures()) {
+ String id = struct.getName();
+ String name = struct.getSbmlName();
+ if (name == null || name.isEmpty()) {
+ continue;
+ }
+ if (id.equals(name)) {
+ continue;
+ }
+ if (isRestrictedXYZT(name, vcBioModel)) {
+ continue;
+ }
+ name = TokenMangler.fixTokenStrict(name, 60);
+ while (true) {
+ if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) {
+ break;
+ }
+ name = TokenMangler.getNextEnumeratedToken(name);
+ }
+ if (id.equals(name)) {
+ continue;
+ }
+ try {
+ System.out.println(name + " <-- " + id);
+ struct.setName(name, true);
+ } catch (PropertyVetoException e) {
+ e.printStackTrace();
+ }
+ entitiesToRename.put(id, name);
+ }
+ vcBioModel.getSimulationContext(0).substituteChangedNamesInExpressions(entitiesToRename);
+
+ for (ReactionStep rs : vcBioModel.getModel().getReactionSteps()) {
+ String id = rs.getName();
+ String name = rs.getSbmlName();
+ if (name == null || name.isEmpty()) {
+ continue;
+ }
+ if (id.equals(name)) {
+ continue;
+ }
+ if (isRestrictedXYZT(name, vcBioModel)) {
+ continue;
+ }
// name = TokenMangler.fixTokenStrict(name, 60);
- while (true) {
- if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) {
- break;
- }
- name = TokenMangler.getNextEnumeratedToken(name);
- }
- if (id.equals(name)) {
- continue;
- }
- try {
- System.out.println(name + " <-- " + id);
- rs.setName(name);
- } catch (PropertyVetoException e) {
- e.printStackTrace();
- }
- }
- vcBioModel.getSimulationContext(0).setbIgnoreEvents(false);
- }
-
- /**
- * raise issue tab if error is present
- *
- * @param hashTable
- * @throws Exception
- */
- private static void setWindowFocus(Hashtable hashTable) throws Exception {
- DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
- if (windowManager != null) {
- DocumentEditor de = windowManager.getDocumentEditor();
- if (de != null) {
- de.setWindowFocus();
- }
- }
- }
-
- private DocumentWindowManager createDocumentWindowManager(final VCDocument doc) {
- JPanel newJPanel = new JPanel();
- if (doc instanceof BioModel) {
- return new BioModelWindowManager(newJPanel, ClientRequestManager.this, (BioModel) doc);
- } else if (doc instanceof MathModel) {
- return new MathModelWindowManager(newJPanel, ClientRequestManager.this, (MathModel) doc);
- } else if (doc instanceof Geometry) {
- return new GeometryWindowManager(newJPanel, ClientRequestManager.this, (Geometry) doc);
- }
- throw new RuntimeException("Unknown VCDocument type " + doc);
- }
-
- public void openDocument(VCDocumentType documentType, DocumentWindowManager requester) {
- /* trying to open from database; called by DocumentWindow */
- // get an info first
- VCDocumentInfo documentInfo = null;
- try {
- documentInfo = getMdiManager().getDatabaseWindowManager().selectDocument(documentType, requester);
- // check whether request comes from a blank, unchanged document window; if so,
- // open in same window, otherwise in a new window
- boolean inNewWindow = isDifferentFromBlank(documentType, requester.getVCDocument());
- openDocument(documentInfo, requester, inNewWindow);
- } catch (UserCancelException uexc) {
- System.out.println(uexc);
- return;
- } catch (Exception exc) {
- exc.printStackTrace(System.out);
- PopupGenerator.showErrorDialog(requester, "Open document failed\n" + exc.getMessage(), exc);
- }
- }
-
- public void openDocument(VCDocumentInfo documentInfo, TopLevelWindowManager requester, boolean inNewWindow) {
- // called directly from DatabaseWindow or after invoking an open dialog (see
- // openDocument(int, Component))
- // need to check whether we opened this before and we still have it open
- if (documentInfo == null) {
- return;
- }
- String documentID = null;
- if (documentInfo.getVersion() != null && documentInfo.getVersion().getVersionKey() != null) { // CLEAN UP BOGUS
- // VERSION in
- // XmlInfo !!!
- documentID = documentInfo.getVersion().getVersionKey().toString();
- }
-
- // see if we have this open
- if (documentID != null && getMdiManager().haveWindow(documentID)) {
- // already open, block it
- getMdiManager().blockWindow(documentID);
- // check for changes
- VCDocument openedDoc = ((DocumentWindowManager) getMdiManager().getWindowManager(documentID))
- .getVCDocument();
- boolean isChanged = true;
- try {
- isChanged = getDocumentManager().isChanged(openedDoc);
- } catch (DataAccessException exc) {
- // *maybe* something wrong trying to go to database, may not be able to load in
- // the end, but warn anyway and try
- String choice = PopupGenerator.showWarningDialog(requester, getUserPreferences(),
- UserMessage.warn_UnableToCheckForChanges, null);
- if (choice.equals(UserMessage.OPTION_CANCEL)) {
- // user canceled, just show existing document
- getMdiManager().unBlockWindow(documentID);
- getMdiManager().showWindow(documentID);
- return;
- }
- }
- // we managed to check
- if (isChanged) {
- // it changed, warn the user
- String choice = PopupGenerator.showWarningDialog(requester, getUserPreferences(),
- UserMessage.choice_AlreadyOpened, null);
- if (choice.equals(UserMessage.OPTION_CANCEL)) {
- // user canceled, just show existing document
- getMdiManager().unBlockWindow(documentID);
- getMdiManager().showWindow(documentID);
- return;
- } else {
- // user confirmed, close existing window first
- getMdiManager().closeWindow(documentID);
- // we are ready to try to get the new document
- }
- } else {
- // nothing changed, just show that window
- getMdiManager().unBlockWindow(documentID);
- getMdiManager().showWindow(documentID);
- return;
- }
- }
- openAfterChecking(documentInfo, requester, inNewWindow);
- }
-
- public void openPathway(DocumentWindowManager windowManager, PathwayImportOption pathwayImportOption) {
- if (windowManager instanceof BioModelWindowManager) {
- BioModelWindowManager bioModelWindowManager = (BioModelWindowManager) windowManager;
- bioModelWindowManager.importPathway(pathwayImportOption);
- } else {
- DialogUtils.showErrorDialog(windowManager.getComponent(),
- "Pathways can only be imported into a BioModel. "
- + "To import a pathway, switch to a BioModel window or open a new"
- + "one by opening a biomodel. This option should not even be available otherwise.");
- }
- }
-
- public void processComparisonResult(TMLPanel comparePanel, TopLevelWindowManager requester) {
- // this is called from the EventDispatchQueue, so take care with threading...
-
- if (comparePanel == null || requester == null) {
- throw new IllegalArgumentException("Invalid params: " + comparePanel + " " + requester);
- }
- try {
- final VCDocument vcDoc = comparePanel.processComparisonResult();
- if (requester instanceof DatabaseWindowManager) {
- final DatabaseWindowManager dataWinManager = (DatabaseWindowManager) requester;
- final VCDocumentInfo vcDocInfo = getMatchingDocumentInfo(vcDoc);
- this.openDocument(vcDocInfo, dataWinManager, true);
- Thread waiter = new Thread() {
- public void run() {
- try {
- GeneralGuiUtils.setCursorThroughout((Container) dataWinManager.getComponent(),
- Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
- while (bOpening) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- }
- }
- String ID = vcDocInfo.getVersion().getVersionKey().toString();
- DocumentWindowManager dwm = (DocumentWindowManager) ClientRequestManager.this
- .getMdiManager().getWindowManager(ID);
- dwm.resetDocument(vcDoc);
- } finally {
- GeneralGuiUtils.setCursorThroughout((Container) dataWinManager.getComponent(),
- Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
- }
- }
- };
- waiter.start();
- } else if (requester instanceof DocumentWindowManager) {
- DocumentWindowManager docWinManager = (DocumentWindowManager) requester;
- docWinManager.resetDocument(vcDoc);
- } else {
- throw new IllegalArgumentException(
- "Invalid TopLevelWindowManager instance: " + requester.getClass().getName());
- }
- System.out.println("Processing new model ..." + vcDoc.getVersion().getName());
- } catch (Exception e) {
- e.printStackTrace(System.out);
- throw new RuntimeException(e.getMessage());
- }
- }
-
- /**
- * This method gets called when a bound property is changed.
- *
- * @param evt A PropertyChangeEvent object describing the event source and the
- * property that has changed.
- */
- public void propertyChange(final PropertyChangeEvent evt) {
- if (evt.getSource() == getVcellClient().getClientServerManager()
- && evt.getPropertyName().equals("connectionStatus")) {
- // update status display
- updateStatusNow(); // this is already thread-safe
- // other updates
- AsynchGuiUpdater updater = new AsynchGuiUpdater() {
- public void guiToDo() {
- }
-
- public void guiToDo(Object params) {
- // so far just update the DatabaseWindow
- // need logic to deal with disconnection, different credentials etc.
-
- // only when NOT initializing
- if (((ConnectionStatus) evt.getNewValue()).getStatus() != ConnectionStatus.INITIALIZING) {
- getMdiManager().getDatabaseWindowManager().initializeAll();
- if (getMdiManager().getTestingFrameworkWindowManager() != null) {
- getMdiManager().getTestingFrameworkWindowManager().initializeAllPanels();
- }
- }
- }
- };
- updater.updateNow("some arg needed...");
- }
- }
-
- public void reconnect(final TopLevelWindowManager requester) {
- // asynch & nothing to do on Swing queue (updates handled by events)
- AsynchClientTask task1 = new AsynchClientTask("reconnect", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- getClientServerManager().reconnect(new VCellGuiInteractiveContext(requester));
-
- }
- };
- ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
- new AsynchClientTask[] { task1 });
- }
-
- public void revertToSaved(DocumentWindowManager documentWindowManager) {
- // make the info
- VCDocument document = documentWindowManager.getVCDocument();
- VCDocumentInfo info = null;
- try {
- KeyValue versionKey = document.getVersion().getVersionKey();
- switch (document.getDocumentType()) {
- case BIOMODEL_DOC: {
- info = getDocumentManager().getBioModelInfo(versionKey);
- break;
- }
- case MATHMODEL_DOC: {
- info = getDocumentManager().getMathModelInfo(versionKey);
- break;
- }
- case GEOMETRY_DOC: {
- info = getDocumentManager().getGeometryInfo(versionKey);
- break;
- }
- }
- } catch (DataAccessException e) {
- e.printStackTrace(System.out);
- throw new RuntimeException(e.getMessage());
- }
- // reload and reset into same window
- openAfterChecking(info, documentWindowManager, false);
- }
-
- public SimulationStatus runSimulation(final SimulationInfo simInfo, int numSimulationScanJobs)
- throws DataAccessException {
-
- SimulationStatus simStatus = getClientServerManager().getJobManager()
- .startSimulation(simInfo.getAuthoritativeVCSimulationIdentifier(), numSimulationScanJobs);
- return simStatus;
- }
-
- public void runSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations) {
- runSimulations(clientSimManager, simulations, null);
- }
-
- public void runSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations,AsynchClientTask[] endTasks) {
- DocumentWindowManager documentWindowManager = clientSimManager.getDocumentWindowManager();
- if (documentWindowManager.getUser() == null || User.isGuest(documentWindowManager.getUser().getName())) {
- DialogUtils.showErrorDialog(documentWindowManager.getComponent(),
- User.createGuestErrorMessage("runVCellServerSimulations"));
- return;
- }
-
- /* run some quick checks to see if we need to do a SaveAs */
- boolean needSaveAs = false;
- if (documentWindowManager.getVCDocument().getVersion() == null) {
- // never saved
- needSaveAs = true;
- } else if (!documentWindowManager.getVCDocument().getVersion().getOwner()
- .compareEqual(getDocumentManager().getUser())) {
- // not the owner
- // keep the user informed this time
- String choice = PopupGenerator.showWarningDialog(documentWindowManager, getUserPreferences(),
- UserMessage.warn_SaveNotOwner, null);
- if (choice.equals(UserMessage.OPTION_SAVE_AS_NEW)) {
- needSaveAs = true;
- } else {
- // user canceled, just show existing document
- getMdiManager().showWindow(documentWindowManager.getManagerID());
- throw new UserCancelException("user canceled");
- }
- }
-
- // Before running the simulation, check if all the sizes of structures are set
- if (simulations != null && simulations.length > 0) {
- VCDocument vcd = documentWindowManager.getVCDocument();
- if (vcd instanceof BioModel) {
- String stochChkMsg = null;
- // we want to check when there is stochastic application if the rate laws set in
- // model can be automatically transformed.
- for (int i = 0; i < simulations.length; i++) {
- if (simulations[i].getMathDescription().isNonSpatialStoch()
- || simulations[i].getMathDescription().isSpatialStoch()
- || simulations[i].getMathDescription().isSpatialHybrid()) {
- if (stochChkMsg == null) {
- stochChkMsg = ((BioModel) vcd).getModel().isValidForStochApp();
- }
- if (!(stochChkMsg.equals(""))) {
- DialogUtils.showErrorDialog(documentWindowManager.getComponent(),
- "Problem in simulation: " + simulations[i].getName() + ".\n" + stochChkMsg);
- throw new RuntimeException(
- "Problem in simulation: " + simulations[i].getName() + "\n" + stochChkMsg);
- }
- }
- }
- }
- }
- //
- // when we run simulations, we want to force these exact editions to be run (not
- // their older "equivalent" simulations).
- //
- // rather than trying to update immutable objects (e.g. directly clear parent
- // references), we can do two things:
- //
- // 1) if simulation already points back to a previous "equivalent" edition,
- // clear the version to force a clean save with no equivalency relationship
- // 2) and, to prevent a simulation save from creating a new equivalency
- // relationship,
- // send the list of simulations to be run to force independence (see
- // SaveDocument).
- //
- for (int i = 0; simulations != null && i < simulations.length; i++) {
- if (simulations[i].getSimulationVersion() != null
- && simulations[i].getSimulationVersion().getParentSimulationReference() != null) {
- simulations[i].clearVersion();
- }
- }
- /* now start the dirty work */
-
- /* block document window */
- JFrame currentDocumentWindow = getMdiManager().blockWindow(documentWindowManager.getManagerID());
- /* prepare hashtable for tasks */
- Hashtable hash = new Hashtable();
- hash.put("mdiManager", getMdiManager());
- hash.put(DocumentManager.IDENT, getDocumentManager());
- hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, documentWindowManager);
- hash.put("currentDocumentWindow", currentDocumentWindow);
- hash.put("clientSimManager", clientSimManager);
- hash.put("simulations", simulations);
- hash.put("jobManager", getClientServerManager().getJobManager());
- hash.put("requestManager", this);
- hash.put("CallAction", CallAction.RUN);
-
- /* create tasks */
- AsynchClientTask[] tasks = null;
- if (needSaveAs) {
- // check document consistency first
- AsynchClientTask documentValid = new DocumentValidTask();
- AsynchClientTask setMathDescription = new SetMathDescription();
- // get a new name
- AsynchClientTask newName = new NewName();
- // save it
- AsynchClientTask saveDocument = new SaveDocument(true);
- // clean up
- AsynchClientTask finishSave = new FinishSave();
- // run the simulations
- AsynchClientTask runSims = new RunSims();
- // assemble array
- tasks = new AsynchClientTask[] { documentValid, setMathDescription, newName, saveDocument, finishSave,
- runSims };
- } else {
- // check document consistency first
- AsynchClientTask documentValid = new DocumentValidTask();
- AsynchClientTask setMathDescription = new SetMathDescription();
- // check if unchanged document
- AsynchClientTask checkUnchanged = new CheckUnchanged(true);
- // save it
- AsynchClientTask saveDocument = new SaveDocument(false);
- // check for lost results
- AsynchClientTask checkBeforeDelete = new CheckBeforeDelete();
- // delete old document
- AsynchClientTask deleteOldDocument = new DeleteOldDocument();
- // clean up
- AsynchClientTask finishSave = new FinishSave();
- // run the simulations
- AsynchClientTask runSims = new RunSims();
- // assemble array
- tasks = new AsynchClientTask[] { documentValid, setMathDescription, checkUnchanged, saveDocument,
- checkBeforeDelete, CheckBeforeDelete.getLowPrecisionConstantsNewNameTask(),
- CheckBeforeDelete.getLowPrecisionConstantsSaveTask(), deleteOldDocument, finishSave,
+ while (true) {
+ if (cbit.vcell.model.Model.isNameUnused(name, vcBioModel.getModel())) {
+ break;
+ }
+ name = TokenMangler.getNextEnumeratedToken(name);
+ }
+ if (id.equals(name)) {
+ continue;
+ }
+ try {
+ System.out.println(name + " <-- " + id);
+ rs.setName(name);
+ } catch (PropertyVetoException e) {
+ e.printStackTrace();
+ }
+ }
+ vcBioModel.getSimulationContext(0).setbIgnoreEvents(false);
+ }
+
+ /**
+ * raise issue tab if error is present
+ *
+ * @param hashTable
+ * @throws Exception
+ */
+ private static void setWindowFocus(Hashtable hashTable) throws Exception {
+ DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
+ if (windowManager != null) {
+ DocumentEditor de = windowManager.getDocumentEditor();
+ if (de != null) {
+ de.setWindowFocus();
+ }
+ }
+ }
+
+ private DocumentWindowManager createDocumentWindowManager(final VCDocument doc) {
+ JPanel newJPanel = new JPanel();
+ if (doc instanceof BioModel) {
+ return new BioModelWindowManager(newJPanel, ClientRequestManager.this, (BioModel) doc);
+ } else if (doc instanceof MathModel) {
+ return new MathModelWindowManager(newJPanel, ClientRequestManager.this, (MathModel) doc);
+ } else if (doc instanceof Geometry) {
+ return new GeometryWindowManager(newJPanel, ClientRequestManager.this, (Geometry) doc);
+ }
+ throw new RuntimeException("Unknown VCDocument type " + doc);
+ }
+
+ public void openDocument(VCDocumentType documentType, DocumentWindowManager requester) {
+ /* trying to open from database; called by DocumentWindow */
+ // get an info first
+ VCDocumentInfo documentInfo = null;
+ try {
+ documentInfo = this.getMdiManager().getDatabaseWindowManager().selectDocument(documentType, requester);
+ // check whether request comes from a blank, unchanged document window; if so,
+ // open in same window, otherwise in a new window
+ boolean inNewWindow = this.isDifferentFromBlank(documentType, requester.getVCDocument());
+ this.openDocument(documentInfo, requester, inNewWindow);
+ } catch (UserCancelException uexc) {
+ System.out.println(uexc);
+ } catch (Exception exc) {
+ exc.printStackTrace(System.out);
+ PopupGenerator.showErrorDialog(requester, "Open document failed\n" + exc.getMessage(), exc);
+ }
+ }
+
+ public void openDocument(VCDocumentInfo documentInfo, TopLevelWindowManager requester, boolean inNewWindow) {
+ // called directly from DatabaseWindow or after invoking an open dialog (see
+ // openDocument(int, Component))
+ // need to check whether we opened this before and we still have it open
+ if (documentInfo == null) {
+ return;
+ }
+ String documentID = null;
+ if (documentInfo.getVersion() != null && documentInfo.getVersion().getVersionKey() != null) { // CLEAN UP BOGUS
+ // VERSION in
+ // XmlInfo !!!
+ documentID = documentInfo.getVersion().getVersionKey().toString();
+ }
+
+ // see if we have this open
+ if (documentID != null && this.getMdiManager().haveWindow(documentID)) {
+ // already open, block it
+ this.getMdiManager().blockWindow(documentID);
+ // check for changes
+ VCDocument openedDoc = ((DocumentWindowManager) this.getMdiManager().getWindowManager(documentID))
+ .getVCDocument();
+ boolean isChanged = true;
+ try {
+ isChanged = this.getDocumentManager().isChanged(openedDoc);
+ } catch (DataAccessException exc) {
+ // *maybe* something wrong trying to go to database, may not be able to load in
+ // the end, but warn anyway and try
+ String choice = PopupGenerator.showWarningDialog(requester, this.getUserPreferences(),
+ UserMessage.warn_UnableToCheckForChanges, null);
+ if (choice.equals(UserMessage.OPTION_CANCEL)) {
+ // user canceled, just show existing document
+ this.getMdiManager().unBlockWindow(documentID);
+ this.getMdiManager().showWindow(documentID);
+ return;
+ }
+ }
+ // we managed to check
+ if (isChanged) {
+ // it changed, warn the user
+ String choice = PopupGenerator.showWarningDialog(requester, this.getUserPreferences(),
+ UserMessage.choice_AlreadyOpened, null);
+ if (choice.equals(UserMessage.OPTION_CANCEL)) {
+ // user canceled, just show existing document
+ this.getMdiManager().unBlockWindow(documentID);
+ this.getMdiManager().showWindow(documentID);
+ return;
+ } else {
+ // user confirmed, close existing window first
+ this.getMdiManager().closeWindow(documentID);
+ // we are ready to try to get the new document
+ }
+ } else {
+ // nothing changed, just show that window
+ this.getMdiManager().unBlockWindow(documentID);
+ this.getMdiManager().showWindow(documentID);
+ return;
+ }
+ }
+ this.openAfterChecking(documentInfo, requester, inNewWindow);
+ }
+
+ public void openPathway(DocumentWindowManager windowManager, PathwayImportOption pathwayImportOption) {
+ if (windowManager instanceof BioModelWindowManager bioModelWindowManager) {
+ bioModelWindowManager.importPathway(pathwayImportOption);
+ } else {
+ DialogUtils.showErrorDialog(windowManager.getComponent(),
+ "Pathways can only be imported into a BioModel. "
+ + "To import a pathway, switch to a BioModel window or open a new"
+ + "one by opening a biomodel. This option should not even be available otherwise.");
+ }
+ }
+
+ public void processComparisonResult(TMLPanel comparePanel, TopLevelWindowManager requester) {
+ // this is called from the EventDispatchQueue, so take care with threading...
+
+ if (comparePanel == null || requester == null) {
+ throw new IllegalArgumentException("Invalid params: " + comparePanel + " " + requester);
+ }
+ try {
+ final VCDocument vcDoc = comparePanel.processComparisonResult();
+ if (requester instanceof DatabaseWindowManager dataWinManager) {
+ final VCDocumentInfo vcDocInfo = this.getMatchingDocumentInfo(vcDoc);
+ this.openDocument(vcDocInfo, dataWinManager, true);
+ Thread waiter = new Thread() {
+ public void run() {
+ try {
+ GeneralGuiUtils.setCursorThroughout((Container) dataWinManager.getComponent(),
+ Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ while (ClientRequestManager.this.bOpening) {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ }
+ }
+ String ID = vcDocInfo.getVersion().getVersionKey().toString();
+ DocumentWindowManager dwm = (DocumentWindowManager) ClientRequestManager.this
+ .getMdiManager().getWindowManager(ID);
+ dwm.resetDocument(vcDoc);
+ } finally {
+ GeneralGuiUtils.setCursorThroughout((Container) dataWinManager.getComponent(),
+ Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
+ }
+ }
+ };
+ waiter.start();
+ } else if (requester instanceof DocumentWindowManager docWinManager) {
+ docWinManager.resetDocument(vcDoc);
+ } else {
+ throw new IllegalArgumentException(
+ "Invalid TopLevelWindowManager instance: " + requester.getClass().getName());
+ }
+ System.out.println("Processing new model ..." + vcDoc.getVersion().getName());
+ } catch (Exception e) {
+ e.printStackTrace(System.out);
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ /**
+ * This method gets called when a bound property is changed.
+ *
+ * @param evt A PropertyChangeEvent object describing the event source and the
+ * property that has changed.
+ */
+ public void propertyChange(final PropertyChangeEvent evt) {
+ if (evt.getSource() == this.getVcellClient().getClientServerManager()
+ && evt.getPropertyName().equals("connectionStatus")) {
+ // update status display
+ this.updateStatusNow(); // this is already thread-safe
+ // other updates
+ AsynchGuiUpdater updater = new AsynchGuiUpdater() {
+ public void guiToDo() {
+ }
+
+ public void guiToDo(Object params) {
+ // so far just update the DatabaseWindow
+ // need logic to deal with disconnection, different credentials etc.
+
+ // only when NOT initializing
+ if (((ConnectionStatus) evt.getNewValue()).getStatus() != ConnectionStatus.INITIALIZING) {
+ ClientRequestManager.this.getMdiManager().getDatabaseWindowManager().initializeAll();
+ if (ClientRequestManager.this.getMdiManager().getTestingFrameworkWindowManager() != null) {
+ ClientRequestManager.this.getMdiManager().getTestingFrameworkWindowManager().initializeAllPanels();
+ }
+ }
+ }
+ };
+ updater.updateNow("some arg needed...");
+ }
+ }
+
+ public void reconnect(final TopLevelWindowManager requester) {
+ // asynch & nothing to do on Swing queue (updates handled by events)
+ AsynchClientTask task1 = new AsynchClientTask("reconnect", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ ClientRequestManager.this.getClientServerManager().reconnect(new VCellGuiInteractiveContext(requester));
+
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable(),
+ new AsynchClientTask[]{task1});
+ }
+
+ public void revertToSaved(DocumentWindowManager documentWindowManager) {
+ // make the info
+ VCDocument document = documentWindowManager.getVCDocument();
+ VCDocumentInfo info = null;
+ try {
+ KeyValue versionKey = document.getVersion().getVersionKey();
+ switch (document.getDocumentType()) {
+ case BIOMODEL_DOC: {
+ info = this.getDocumentManager().getBioModelInfo(versionKey);
+ break;
+ }
+ case MATHMODEL_DOC: {
+ info = this.getDocumentManager().getMathModelInfo(versionKey);
+ break;
+ }
+ case GEOMETRY_DOC: {
+ info = this.getDocumentManager().getGeometryInfo(versionKey);
+ break;
+ }
+ }
+ } catch (DataAccessException e) {
+ e.printStackTrace(System.out);
+ throw new RuntimeException(e.getMessage());
+ }
+ // reload and reset into same window
+ this.openAfterChecking(info, documentWindowManager, false);
+ }
+
+ public SimulationStatus runSimulation(final SimulationInfo simInfo, int numSimulationScanJobs)
+ throws DataAccessException {
+
+ SimulationStatus simStatus = this.getClientServerManager().getJobManager()
+ .startSimulation(simInfo.getAuthoritativeVCSimulationIdentifier(), numSimulationScanJobs);
+ return simStatus;
+ }
+
+ public void runSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations) {
+ this.runSimulations(clientSimManager, simulations, null);
+ }
+
+ public void runSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations, AsynchClientTask[] endTasks) {
+ DocumentWindowManager documentWindowManager = clientSimManager.getDocumentWindowManager();
+ if (documentWindowManager.getUser() == null || User.isGuest(documentWindowManager.getUser().getName())) {
+ DialogUtils.showErrorDialog(documentWindowManager.getComponent(),
+ User.createGuestErrorMessage("runVCellServerSimulations"));
+ return;
+ }
+
+ /* run some quick checks to see if we need to do a SaveAs */
+ boolean needSaveAs = false;
+ if (documentWindowManager.getVCDocument().getVersion() == null) {
+ // never saved
+ needSaveAs = true;
+ } else if (!documentWindowManager.getVCDocument().getVersion().getOwner()
+ .compareEqual(this.getDocumentManager().getUser())) {
+ // not the owner
+ // keep the user informed this time
+ String choice = PopupGenerator.showWarningDialog(documentWindowManager, this.getUserPreferences(),
+ UserMessage.warn_SaveNotOwner, null);
+ if (choice.equals(UserMessage.OPTION_SAVE_AS_NEW)) {
+ needSaveAs = true;
+ } else {
+ // user canceled, just show existing document
+ this.getMdiManager().showWindow(documentWindowManager.getManagerID());
+ throw new UserCancelException("user canceled");
+ }
+ }
+
+ // Before running the simulation, check if all the sizes of structures are set
+ if (simulations != null && simulations.length > 0) {
+ VCDocument vcd = documentWindowManager.getVCDocument();
+ if (vcd instanceof BioModel) {
+ String stochChkMsg = null;
+ // we want to check when there is stochastic application if the rate laws set in
+ // model can be automatically transformed.
+ for (int i = 0; i < simulations.length; i++) {
+ if (simulations[i].getMathDescription().isNonSpatialStoch()
+ || simulations[i].getMathDescription().isSpatialStoch()
+ || simulations[i].getMathDescription().isSpatialHybrid()) {
+ if (stochChkMsg == null) {
+ stochChkMsg = ((BioModel) vcd).getModel().isValidForStochApp();
+ }
+ if (!(stochChkMsg.equals(""))) {
+ DialogUtils.showErrorDialog(documentWindowManager.getComponent(),
+ "Problem in simulation: " + simulations[i].getName() + ".\n" + stochChkMsg);
+ throw new RuntimeException(
+ "Problem in simulation: " + simulations[i].getName() + "\n" + stochChkMsg);
+ }
+ }
+ }
+ }
+ }
+ //
+ // when we run simulations, we want to force these exact editions to be run (not
+ // their older "equivalent" simulations).
+ //
+ // rather than trying to update immutable objects (e.g. directly clear parent
+ // references), we can do two things:
+ //
+ // 1) if simulation already points back to a previous "equivalent" edition,
+ // clear the version to force a clean save with no equivalency relationship
+ // 2) and, to prevent a simulation save from creating a new equivalency
+ // relationship,
+ // send the list of simulations to be run to force independence (see
+ // SaveDocument).
+ //
+ for (int i = 0; simulations != null && i < simulations.length; i++) {
+ if (simulations[i].getSimulationVersion() != null
+ && simulations[i].getSimulationVersion().getParentSimulationReference() != null) {
+ simulations[i].clearVersion();
+ }
+ }
+ /* now start the dirty work */
+
+ /* block document window */
+ JFrame currentDocumentWindow = this.getMdiManager().blockWindow(documentWindowManager.getManagerID());
+ /* prepare hashtable for tasks */
+ Hashtable hash = new Hashtable();
+ hash.put("mdiManager", this.getMdiManager());
+ hash.put(DocumentManager.IDENT, this.getDocumentManager());
+ hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, documentWindowManager);
+ hash.put("currentDocumentWindow", currentDocumentWindow);
+ hash.put("clientSimManager", clientSimManager);
+ hash.put("simulations", simulations);
+ hash.put("jobManager", this.getClientServerManager().getJobManager());
+ hash.put("requestManager", this);
+ hash.put("CallAction", CallAction.RUN);
+
+ /* create tasks */
+ AsynchClientTask[] tasks = null;
+ if (needSaveAs) {
+ // check document consistency first
+ AsynchClientTask documentValid = new DocumentValidTask();
+ AsynchClientTask setMathDescription = new SetMathDescription();
+ // get a new name
+ AsynchClientTask newName = new NewName();
+ // save it
+ AsynchClientTask saveDocument = new SaveDocument(true);
+ // clean up
+ AsynchClientTask finishSave = new FinishSave();
+ // run the simulations
+ AsynchClientTask runSims = new RunSims();
+ // assemble array
+ tasks = new AsynchClientTask[]{documentValid, setMathDescription, newName, saveDocument, finishSave,
+ runSims};
+ } else {
+ // check document consistency first
+ AsynchClientTask documentValid = new DocumentValidTask();
+ AsynchClientTask setMathDescription = new SetMathDescription();
+ // check if unchanged document
+ AsynchClientTask checkUnchanged = new CheckUnchanged(true);
+ // save it
+ AsynchClientTask saveDocument = new SaveDocument(false);
+ // check for lost results
+ AsynchClientTask checkBeforeDelete = new CheckBeforeDelete();
+ // delete old document
+ AsynchClientTask deleteOldDocument = new DeleteOldDocument();
+ // clean up
+ AsynchClientTask finishSave = new FinishSave();
+ // run the simulations
+ AsynchClientTask runSims = new RunSims();
+ // assemble array
+ tasks = new AsynchClientTask[]{documentValid, setMathDescription, checkUnchanged, saveDocument,
+ checkBeforeDelete, CheckBeforeDelete.getLowPrecisionConstantsNewNameTask(),
+ CheckBeforeDelete.getLowPrecisionConstantsSaveTask(), deleteOldDocument, finishSave,
// lowPrecisionConstantsWaitSave,
- runSims };
- if(endTasks != null && endTasks.length > 0) {
- AsynchClientTask[] temp = Arrays.copyOf(tasks, tasks.length+endTasks.length);
- System.arraycopy(endTasks, 0, temp, tasks.length, endTasks.length);
- tasks = temp;
- }
- }
- /* run the tasks */
- ClientTaskDispatcher.dispatch(currentDocumentWindow, hash, tasks, true);
- }
-
- public void saveDocument(DocumentWindowManager documentWindowManager, boolean replace) {
- saveDocument(documentWindowManager, replace, null);
- }
-
- public void saveDocument(final DocumentWindowManager documentWindowManager, boolean replace,
- AsynchClientTask closeWindowTask) {
- if (documentWindowManager.getUser() == null || User.isGuest(documentWindowManager.getUser().getName())) {
- DialogUtils.showErrorDialog(documentWindowManager.getComponent(),
- User.createGuestErrorMessage("saveDocument"));
- return;
- }
-
- /* run some quick checks first to validate request to save or save edition */
- if (documentWindowManager.getVCDocument().getVersion() == null) {
- // it can never see this happening before, but check anyway and default to save
- // as
- // but since we can allow user to save during closing, now it can happen
- // (save/save edition buttons should have not been enabled upon document window
- // creation)
- System.out.println(
- "\nIGNORED ERROR: should not have been able to use save/save edition on doc with no version key\n");
- saveDocumentAsNew(documentWindowManager, closeWindowTask);
- return;
- }
- if (!documentWindowManager.getVCDocument().getVersion().getOwner()
- .compareEqual(getDocumentManager().getUser())) {
- // not the owner - this should also not happen, but check anyway...
- // keep the user informed this time
- System.out.println(
- "\nIGNORED ERROR: should not have been able to use save/save edition on doc with different owner\n");
- String choice = PopupGenerator.showWarningDialog(documentWindowManager, getUserPreferences(),
- UserMessage.warn_SaveNotOwner, null);
- if (choice.equals(UserMessage.OPTION_SAVE_AS_NEW)) {
- // user chose to Save As
- saveDocumentAsNew(documentWindowManager, closeWindowTask);
- return;
- } else {
- if (closeWindowTask == null) {
- // user canceled, just show existing document
- getMdiManager().showWindow(documentWindowManager.getManagerID());
- return;
- } else {
- ClientTaskDispatcher.dispatch(documentWindowManager.getComponent(), new Hashtable(),
- new AsynchClientTask[] { closeWindowTask }, false);
- }
- }
- }
-
- /* request is valid, go ahead with save */
-
- /* block document window */
- JFrame currentDocumentWindow = getMdiManager().blockWindow(documentWindowManager.getManagerID());
- /* prepare hashtable for tasks */
- Hashtable hash = new Hashtable();
- hash.put("mdiManager", getMdiManager());
- hash.put(DocumentManager.IDENT, getDocumentManager());
- hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, documentWindowManager);
- hash.put("currentDocumentWindow", currentDocumentWindow);
- hash.put("requestManager", this);
- hash.put("CallAction", CallAction.RUN);
-
- /* create tasks */
- // check document consistency first
- AsynchClientTask documentValid = new DocumentValidTask();
- AsynchClientTask setMathDescription = new SetMathDescription();
- // check if unchanged document
- AsynchClientTask checkUnchanged = new CheckUnchanged(false);
- // clean up
- AsynchClientTask finishSave = new FinishSave();
- // assemble array
- AsynchClientTask[] tasks = null;
- if (replace) {
- // save it
- AsynchClientTask saveDocument = new SaveDocument(false);
- // check for lost results
- AsynchClientTask checkBeforeDelete = new CheckBeforeDelete();
- // delete old document
- AsynchClientTask deleteOldDocument = new DeleteOldDocument();
- tasks = new AsynchClientTask[] { documentValid, setMathDescription, checkUnchanged, saveDocument,
- checkBeforeDelete, CheckBeforeDelete.getLowPrecisionConstantsNewNameTask(),
- CheckBeforeDelete.getLowPrecisionConstantsSaveTask(), deleteOldDocument, finishSave };
- } else {
- // save it
- AsynchClientTask saveDocument = new SaveDocument(true);
- tasks = new AsynchClientTask[] { documentValid, setMathDescription, checkUnchanged, saveDocument,
- finishSave };
- }
- if (closeWindowTask != null) {
- // replace finishSave
- tasks[tasks.length - 1] = closeWindowTask;
- }
- /* run tasks */
- ClientTaskDispatcher.dispatch(currentDocumentWindow, hash, tasks, false);
- }
-
- public void saveDocumentAsNew(DocumentWindowManager documentWindowManager) {
- saveDocumentAsNew(documentWindowManager, null);
- }
-
- public void saveDocumentAsNew(DocumentWindowManager documentWindowManager, AsynchClientTask closeWindowTask) {
- if (documentWindowManager.getUser() == null || User.isGuest(documentWindowManager.getUser().getName())) {
- DialogUtils.showErrorDialog(documentWindowManager.getComponent(),
- User.createGuestErrorMessage("saveDocument"));
- return;
- }
-
- /* block document window */
- JFrame currentDocumentWindow = getMdiManager().blockWindow(documentWindowManager.getManagerID());
- /* prepare hashtable for tasks */
- Hashtable hash = new Hashtable();
- hash.put("mdiManager", getMdiManager());
- hash.put(DocumentManager.IDENT, getDocumentManager());
- hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, documentWindowManager);
- hash.put("currentDocumentWindow", currentDocumentWindow);
- hash.put("requestManager", this);
- hash.put("CallAction", CallAction.SAVEASNEW);
-
-
- /* create tasks */
- // check document consistency first
- AsynchClientTask documentValid = new DocumentValidTask();
- AsynchClientTask setMathDescription = new SetMathDescription();
- // get a new name
- AsynchClientTask newName = new NewName();
- // save it
- AsynchClientTask saveDocument = new SaveDocument(true);
- // clean up
- AsynchClientTask finishSave = new FinishSave();
- // assemble array
- AsynchClientTask[] tasks = new AsynchClientTask[] { documentValid, setMathDescription, newName, saveDocument,
- finishSave };
-
- if (closeWindowTask != null) {
- // replace finishSave
- tasks[tasks.length - 1] = closeWindowTask;
- }
- /* run tasks */
- ClientTaskDispatcher.dispatch(currentDocumentWindow, hash, tasks, false);
- }
-
- public BioModelInfo selectBioModelInfo(TopLevelWindowManager requester) {
- VCDocumentInfo documentInfo = null;
- try {
- documentInfo = getMdiManager().getDatabaseWindowManager().selectDocument(VCDocumentType.BIOMODEL_DOC,
- requester);
- } catch (UserCancelException uexc) {
- System.out.println(uexc);
- return null;
- } catch (Exception exc) {
- exc.printStackTrace(System.out);
- PopupGenerator.showErrorDialog(requester, "Selection of BioModel failed\n" + exc.getMessage(), exc);
- }
- return (BioModelInfo) documentInfo;
- }
-
- public MathModelInfo selectMathModelInfo(TopLevelWindowManager requester) {
- VCDocumentInfo documentInfo = null;
- try {
- documentInfo = getMdiManager().getDatabaseWindowManager().selectDocument(VCDocumentType.MATHMODEL_DOC,
- requester);
- } catch (UserCancelException uexc) {
- System.out.println(uexc);
- return null;
- } catch (Exception exc) {
- exc.printStackTrace(System.out);
- PopupGenerator.showErrorDialog(requester, "Selection of MathModel failed\n" + exc.getMessage(), exc);
- }
- return (MathModelInfo) documentInfo;
- }
-
- private void setBExiting(boolean newBExiting) {
- bExiting = newBExiting;
- }
-
- private void setVcellClient(VCellClient newVcellClient) {
- vcellClient = newVcellClient;
- }
-
- public void showFieldDataWindow(FieldDataWindowManager.DataSymbolCallBack dataSymbolCallBack) {
- FieldDataWindowManager fdwm = (FieldDataWindowManager) getMdiManager()
- .getWindowManager(ClientMDIManager.FIELDDATA_WINDOW_ID);
- fdwm.getFieldDataGUIPanel().setCreateDataSymbolCallBack(dataSymbolCallBack);
- Window win = (Window) GeneralGuiUtils.findTypeParentOfComponent(fdwm.getFieldDataGUIPanel(), Window.class);
- if (win != null) {
- win.setVisible(false);
- }
- getMdiManager().showWindow(ClientMDIManager.FIELDDATA_WINDOW_ID);
-
- }
-
- public void showTestingFrameworkWindow() {
- getMdiManager().showWindow(ClientMDIManager.TESTING_FRAMEWORK_WINDOW_ID);
- }
-
- public void startExport(final OutputContext outputContext, Component requester, final ExportSpecs exportSpecs) {
- // start a thread to get it; not blocking any window/frame
- AsynchClientTask task1 = new AsynchClientTask("starting exporting",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- getClientServerManager().getJobManager().startExport(outputContext, exportSpecs);
- }
- };
- ClientTaskDispatcher.dispatch(requester, new Hashtable(), new AsynchClientTask[] { task1 });
- }
-
- public void stopSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations) {
- // stop is single step operation, don't bother with tasks, thread inline
- AsynchClientTask task1 = new AsynchClientTask("stopping simulations",
- AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- Hashtable failures = new Hashtable();
- if (simulations != null && simulations.length > 0) {
- for (int i = 0; i < simulations.length; i++) {
- try {
- SimulationInfo simInfo = simulations[i].getSimulationInfo();
- if (simInfo != null) {
- // check for running once more... directly from job status
- SimulationStatus serverSimulationStatus = getServerSimulationStatus(simInfo);
- if (serverSimulationStatus != null
- && serverSimulationStatus.numberOfJobsDone() < simulations[i].getScanCount()) {
- SimulationStatus simStatus = getClientServerManager().getJobManager()
- .stopSimulation(simInfo.getAuthoritativeVCSimulationIdentifier());
- // updateStatus
- clientSimManager.updateStatusFromStopRequest(simulations[i], simStatus);
- }
- } else {
- // this should really not happen...
- throw new RuntimeException(">>>>>>>>>> trying to stop an unsaved simulation...");
- }
- } catch (Throwable exc) {
- exc.printStackTrace(System.out);
- failures.put(simulations[i], exc);
- }
- }
- hashTable.put("failures", failures);
- }
- }
- };
-
- AsynchClientTask task2 = new AsynchClientTask("stopping simulations", AsynchClientTask.TASKTYPE_SWING_BLOCKING,
- false, false) {
-
- @Override
- public void run(Hashtable hashTable) throws Exception {
- @SuppressWarnings("unchecked")
- Hashtable failures = (Hashtable) hashTable
- .get("failures");
- if (failures != null && !failures.isEmpty()) {
- Enumeration en = failures.keys();
- while (en.hasMoreElements()) {
- Simulation sim = (Simulation) en.nextElement();
- Throwable exc = (Throwable) failures.get(sim);
- // notify user
- PopupGenerator.showErrorDialog(clientSimManager.getDocumentWindowManager(),
- "Failed to dispatch stop request for simulation'" + sim.getName() + "'\n"
- + exc.getMessage(),
- exc);
- }
- }
- }
- };
- ClientTaskDispatcher.dispatch(clientSimManager.getDocumentWindowManager().getComponent(),
- new Hashtable(), new AsynchClientTask[] { task1, task2 });
- }
-
- public void updateStatusNow() {
- // thread safe update of gui
- AsynchClientTask task1 = new AsynchClientTask("updateStatusNow", AsynchClientTask.TASKTYPE_SWING_NONBLOCKING) {
- @Override
- public void run(Hashtable hashTable) throws Exception {
- getVcellClient().getStatusUpdater()
- .updateNow(getVcellClient().getClientServerManager().getConnectionStatus());
-
- }
- };
- ClientTaskDispatcher.dispatch(null, new Hashtable(), new AsynchClientTask[] { task1 });
- }
-
- public OpenModelInfoHolder[] getOpenDesktopDocumentInfos(boolean bIncludeSimulations) throws DataAccessException {
- Vector simInfoHolderV = new Vector();
- for (TopLevelWindowManager tlwm : getMdiManager().getWindowManagers()) {
- if (tlwm instanceof DocumentWindowManager) {
- DocumentWindowManager dwm = (DocumentWindowManager) tlwm;
- VCDocument vcDoc = dwm.getVCDocument();
- // if(vcDoc.getVersion() != null){
- if (vcDoc.getDocumentType() == VCDocumentType.BIOMODEL_DOC) {
- BioModel bioModel = (BioModel) vcDoc;
- // getDocumentManager().getBioModel(vcDoc.getVersion().getVersionKey());
- SimulationContext[] simContexts = bioModel.getSimulationContexts();
- for (int i = 0; i < simContexts.length; i += 1) {
- if (bIncludeSimulations) {
- if (simContexts[i].getGeometry() == null) {
- throw new DataAccessException(
- "Error gathering document info (isCompartmental check failed):\nOpen BioModel document "
- + bioModel.getName() + " has no Geometry");
- }
- Simulation[] sims = simContexts[i].getSimulations();
- for (int j = 0; j < sims.length; j += 1) {
- for (int k = 0; k < sims[j].getScanCount(); k += 1) {
- FieldDataWindowManager.OpenModelInfoHolder simInfoHolder = new FieldDataWindowManager.FDSimBioModelInfo(
- sims[j].getName(), bioModel.getVersion(), simContexts[i],
- sims[j].getSimulationInfo(), k,
- // !sims[j].getSolverTaskDescription().getSolverDescription().hasVariableTimestep(),
- simContexts[i].getGeometry().getDimension() == 0);
- simInfoHolderV.add(simInfoHolder);
- }
- }
- } else {
- FieldDataWindowManager.OpenModelInfoHolder simInfoHolder = new FieldDataWindowManager.FDSimBioModelInfo(
- null, bioModel.getVersion(), simContexts[i], null, -1,
- simContexts[i].getGeometry().getDimension() == 0);
- simInfoHolderV.add(simInfoHolder);
- }
- }
- } else if (vcDoc.getDocumentType() == VCDocumentType.MATHMODEL_DOC) {
- MathModel mathModel = (MathModel) vcDoc;
- // getDocumentManager().getMathModel(vcDoc.getVersion().getVersionKey());
- if (bIncludeSimulations) {
- if (mathModel.getMathDescription() == null
- || mathModel.getMathDescription().getGeometry() == null) {
- throw new DataAccessException(
- "Error gathering document info (isCompartmental check failed):\nOpen MathModel document "
- + mathModel.getName() + " has either no MathDescription or no Geometry");
- }
- Simulation[] sims = mathModel.getSimulations();
- for (int i = 0; i < sims.length; i += 1) {
- for (int k = 0; k < sims[i].getScanCount(); k += 1) {
- FieldDataWindowManager.OpenModelInfoHolder simInfoHolder = new FieldDataWindowManager.FDSimMathModelInfo(
- sims[i].getName(), mathModel.getVersion(), mathModel.getMathDescription(),
- sims[i].getSimulationInfo(), k,
- // !sims[i].getSolverTaskDescription().getSolverDescription().hasVariableTimestep(),
- mathModel.getMathDescription().getGeometry().getDimension() == 0);
- simInfoHolderV.add(simInfoHolder);
- }
- }
- } else {
- FieldDataWindowManager.OpenModelInfoHolder simInfoHolder = new FieldDataWindowManager.FDSimMathModelInfo(
- null, mathModel.getVersion(), mathModel.getMathDescription(), null, -1,
- mathModel.getMathDescription().getGeometry().getDimension() == 0);
- simInfoHolderV.add(simInfoHolder);
- }
- }
- // }
- }
-
- }
- OpenModelInfoHolder[] simInfoHolderArr = new OpenModelInfoHolder[simInfoHolderV.size()];
- simInfoHolderV.copyInto(simInfoHolderArr);
- return simInfoHolderArr;
- }
-
- public void showComparisonResults(TopLevelWindowManager requester, XmlTreeDiff diffTree, String baselineDesc,
- String modifiedDesc) {
- TMLPanel comparePanel = new TMLPanel();
- comparePanel.setXmlTreeDiff(diffTree);
- comparePanel.setBaselineVersionDescription(baselineDesc);
- comparePanel.setModifiedVersionDescription(modifiedDesc);
-
- JOptionPane comparePane = new JOptionPane(null, JOptionPane.PLAIN_MESSAGE, 0, null,
- new Object[] { /* "Apply Changes", */"Close" });
- comparePane.setMessage(comparePanel);
- JDialog compareDialog = comparePane.createDialog(requester.getComponent(), "Compare Models");
- compareDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
- compareDialog.setResizable(true);
- compareDialog.pack();
- compareDialog.setVisible(true);
- // ZEnforcer.showModalDialogOnTop(compareDialog,JOptionPane.getFrameForComponent(requester.getComponent()));
- if ("Apply Changes".equals(comparePane.getValue())) {
- if (!comparePanel.tagsResolved()) {
- DialogUtils.showErrorDialog(comparePanel,
- "Please resolve all tagged elements/attributes before proceeding.");
- } else {
- GeneralGuiUtils.setCursorThroughout((Container) requester.getComponent(),
- Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
- try {
- processComparisonResult(comparePanel, requester);
- } catch (RuntimeException e) {
- throw e;
- } finally {
- GeneralGuiUtils.setCursorThroughout((Container) requester.getComponent(),
- Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
- }
- }
- }
- }
+ runSims};
+ if (endTasks != null && endTasks.length > 0) {
+ AsynchClientTask[] temp = Arrays.copyOf(tasks, tasks.length + endTasks.length);
+ System.arraycopy(endTasks, 0, temp, tasks.length, endTasks.length);
+ tasks = temp;
+ }
+ }
+ /* run the tasks */
+ ClientTaskDispatcher.dispatch(currentDocumentWindow, hash, tasks, true);
+ }
+
+ public void saveDocument(DocumentWindowManager documentWindowManager, boolean replace) {
+ this.saveDocument(documentWindowManager, replace, null);
+ }
+
+ public void saveDocument(final DocumentWindowManager documentWindowManager, boolean replace,
+ AsynchClientTask closeWindowTask) {
+ if (documentWindowManager.getUser() == null || User.isGuest(documentWindowManager.getUser().getName())) {
+ DialogUtils.showErrorDialog(documentWindowManager.getComponent(),
+ User.createGuestErrorMessage("saveDocument"));
+ return;
+ }
+
+ /* run some quick checks first to validate request to save or save edition */
+ if (documentWindowManager.getVCDocument().getVersion() == null) {
+ // it can never see this happening before, but check anyway and default to save
+ // as
+ // but since we can allow user to save during closing, now it can happen
+ // (save/save edition buttons should have not been enabled upon document window
+ // creation)
+ System.out.println(
+ "\nIGNORED ERROR: should not have been able to use save/save edition on doc with no version key\n");
+ this.saveDocumentAsNew(documentWindowManager, closeWindowTask);
+ return;
+ }
+ if (!documentWindowManager.getVCDocument().getVersion().getOwner()
+ .compareEqual(this.getDocumentManager().getUser())) {
+ // not the owner - this should also not happen, but check anyway...
+ // keep the user informed this time
+ System.out.println(
+ "\nIGNORED ERROR: should not have been able to use save/save edition on doc with different owner\n");
+ String choice = PopupGenerator.showWarningDialog(documentWindowManager, this.getUserPreferences(),
+ UserMessage.warn_SaveNotOwner, null);
+ if (choice.equals(UserMessage.OPTION_SAVE_AS_NEW)) {
+ // user chose to Save As
+ this.saveDocumentAsNew(documentWindowManager, closeWindowTask);
+ return;
+ } else {
+ if (closeWindowTask == null) {
+ // user canceled, just show existing document
+ this.getMdiManager().showWindow(documentWindowManager.getManagerID());
+ return;
+ } else {
+ ClientTaskDispatcher.dispatch(documentWindowManager.getComponent(), new Hashtable(),
+ new AsynchClientTask[]{closeWindowTask}, false);
+ }
+ }
+ }
+
+ /* request is valid, go ahead with save */
+
+ /* block document window */
+ JFrame currentDocumentWindow = this.getMdiManager().blockWindow(documentWindowManager.getManagerID());
+ /* prepare hashtable for tasks */
+ Hashtable hash = new Hashtable();
+ hash.put("mdiManager", this.getMdiManager());
+ hash.put(DocumentManager.IDENT, this.getDocumentManager());
+ hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, documentWindowManager);
+ hash.put("currentDocumentWindow", currentDocumentWindow);
+ hash.put("requestManager", this);
+ hash.put("CallAction", CallAction.RUN);
+
+ /* create tasks */
+ // check document consistency first
+ AsynchClientTask documentValid = new DocumentValidTask();
+ AsynchClientTask setMathDescription = new SetMathDescription();
+ // check if unchanged document
+ AsynchClientTask checkUnchanged = new CheckUnchanged(false);
+ // clean up
+ AsynchClientTask finishSave = new FinishSave();
+ // assemble array
+ AsynchClientTask[] tasks = null;
+ if (replace) {
+ // save it
+ AsynchClientTask saveDocument = new SaveDocument(false);
+ // check for lost results
+ AsynchClientTask checkBeforeDelete = new CheckBeforeDelete();
+ // delete old document
+ AsynchClientTask deleteOldDocument = new DeleteOldDocument();
+ tasks = new AsynchClientTask[]{documentValid, setMathDescription, checkUnchanged, saveDocument,
+ checkBeforeDelete, CheckBeforeDelete.getLowPrecisionConstantsNewNameTask(),
+ CheckBeforeDelete.getLowPrecisionConstantsSaveTask(), deleteOldDocument, finishSave};
+ } else {
+ // save it
+ AsynchClientTask saveDocument = new SaveDocument(true);
+ tasks = new AsynchClientTask[]{documentValid, setMathDescription, checkUnchanged, saveDocument,
+ finishSave};
+ }
+ if (closeWindowTask != null) {
+ // replace finishSave
+ tasks[tasks.length - 1] = closeWindowTask;
+ }
+ /* run tasks */
+ ClientTaskDispatcher.dispatch(currentDocumentWindow, hash, tasks, false);
+ }
+
+ public void saveDocumentAsNew(DocumentWindowManager documentWindowManager) {
+ this.saveDocumentAsNew(documentWindowManager, null);
+ }
+
+ public void saveDocumentAsNew(DocumentWindowManager documentWindowManager, AsynchClientTask closeWindowTask) {
+ if (documentWindowManager.getUser() == null || User.isGuest(documentWindowManager.getUser().getName())) {
+ DialogUtils.showErrorDialog(documentWindowManager.getComponent(),
+ User.createGuestErrorMessage("saveDocument"));
+ return;
+ }
+
+ /* block document window */
+ JFrame currentDocumentWindow = this.getMdiManager().blockWindow(documentWindowManager.getManagerID());
+ /* prepare hashtable for tasks */
+ Hashtable hash = new Hashtable();
+ hash.put("mdiManager", this.getMdiManager());
+ hash.put(DocumentManager.IDENT, this.getDocumentManager());
+ hash.put(CommonTask.DOCUMENT_WINDOW_MANAGER.name, documentWindowManager);
+ hash.put("currentDocumentWindow", currentDocumentWindow);
+ hash.put("requestManager", this);
+ hash.put("CallAction", CallAction.SAVEASNEW);
+
+
+ /* create tasks */
+ // check document consistency first
+ AsynchClientTask documentValid = new DocumentValidTask();
+ AsynchClientTask setMathDescription = new SetMathDescription();
+ // get a new name
+ AsynchClientTask newName = new NewName();
+ // save it
+ AsynchClientTask saveDocument = new SaveDocument(true);
+ // clean up
+ AsynchClientTask finishSave = new FinishSave();
+ // assemble array
+ AsynchClientTask[] tasks = new AsynchClientTask[]{documentValid, setMathDescription, newName, saveDocument,
+ finishSave};
+
+ if (closeWindowTask != null) {
+ // replace finishSave
+ tasks[tasks.length - 1] = closeWindowTask;
+ }
+ /* run tasks */
+ ClientTaskDispatcher.dispatch(currentDocumentWindow, hash, tasks, false);
+ }
+
+ public BioModelInfo selectBioModelInfo(TopLevelWindowManager requester) {
+ VCDocumentInfo documentInfo = null;
+ try {
+ documentInfo = this.getMdiManager().getDatabaseWindowManager().selectDocument(VCDocumentType.BIOMODEL_DOC,
+ requester);
+ } catch (UserCancelException uexc) {
+ System.out.println(uexc);
+ return null;
+ } catch (Exception exc) {
+ exc.printStackTrace(System.out);
+ PopupGenerator.showErrorDialog(requester, "Selection of BioModel failed\n" + exc.getMessage(), exc);
+ }
+ return (BioModelInfo) documentInfo;
+ }
+
+ public MathModelInfo selectMathModelInfo(TopLevelWindowManager requester) {
+ VCDocumentInfo documentInfo = null;
+ try {
+ documentInfo = this.getMdiManager().getDatabaseWindowManager().selectDocument(VCDocumentType.MATHMODEL_DOC,
+ requester);
+ } catch (UserCancelException uexc) {
+ System.out.println(uexc);
+ return null;
+ } catch (Exception exc) {
+ exc.printStackTrace(System.out);
+ PopupGenerator.showErrorDialog(requester, "Selection of MathModel failed\n" + exc.getMessage(), exc);
+ }
+ return (MathModelInfo) documentInfo;
+ }
+
+ private void setBExiting(boolean newBExiting) {
+ this.bExiting = newBExiting;
+ }
+
+ private void setVcellClient(VCellClient newVcellClient) {
+ this.vcellClient = newVcellClient;
+ }
+
+ public void showFieldDataWindow(FieldDataWindowManager.DataSymbolCallBack dataSymbolCallBack) {
+ FieldDataWindowManager fdwm = (FieldDataWindowManager) this.getMdiManager()
+ .getWindowManager(ClientMDIManager.FIELDDATA_WINDOW_ID);
+ fdwm.getFieldDataGUIPanel().setCreateDataSymbolCallBack(dataSymbolCallBack);
+ Window win = (Window) GeneralGuiUtils.findTypeParentOfComponent(fdwm.getFieldDataGUIPanel(), Window.class);
+ if (win != null) {
+ win.setVisible(false);
+ }
+ this.getMdiManager().showWindow(ClientMDIManager.FIELDDATA_WINDOW_ID);
+
+ }
+
+ public void showTestingFrameworkWindow() {
+ this.getMdiManager().showWindow(ClientMDIManager.TESTING_FRAMEWORK_WINDOW_ID);
+ }
+
+ public void startExport(final OutputContext outputContext, Component requester, final ExportSpecs exportSpecs) {
+ // start a thread to get it; not blocking any window/frame
+ AsynchClientTask task1 = new AsynchClientTask("starting exporting",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ ClientRequestManager.this.getClientServerManager().getJobManager().startExport(outputContext, exportSpecs);
+ }
+ };
+ ClientTaskDispatcher.dispatch(requester, new Hashtable(), new AsynchClientTask[]{task1});
+ }
+
+ public void stopSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations) {
+ // stop is single step operation, don't bother with tasks, thread inline
+ AsynchClientTask task1 = new AsynchClientTask("stopping simulations",
+ AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ Hashtable failures = new Hashtable();
+ if (simulations != null && simulations.length > 0) {
+ for (int i = 0; i < simulations.length; i++) {
+ try {
+ SimulationInfo simInfo = simulations[i].getSimulationInfo();
+ if (simInfo != null) {
+ // check for running once more... directly from job status
+ SimulationStatus serverSimulationStatus = ClientRequestManager.this.getServerSimulationStatus(simInfo);
+ if (serverSimulationStatus != null
+ && serverSimulationStatus.numberOfJobsDone() < simulations[i].getScanCount()) {
+ SimulationStatus simStatus = ClientRequestManager.this.getClientServerManager().getJobManager()
+ .stopSimulation(simInfo.getAuthoritativeVCSimulationIdentifier());
+ // updateStatus
+ clientSimManager.updateStatusFromStopRequest(simulations[i], simStatus);
+ }
+ } else {
+ // this should really not happen...
+ throw new RuntimeException(">>>>>>>>>> trying to stop an unsaved simulation...");
+ }
+ } catch (Throwable exc) {
+ exc.printStackTrace(System.out);
+ failures.put(simulations[i], exc);
+ }
+ }
+ hashTable.put("failures", failures);
+ }
+ }
+ };
+
+ AsynchClientTask task2 = new AsynchClientTask("stopping simulations", AsynchClientTask.TASKTYPE_SWING_BLOCKING,
+ false, false) {
+
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ @SuppressWarnings("unchecked")
+ Hashtable failures = (Hashtable) hashTable
+ .get("failures");
+ if (failures != null && !failures.isEmpty()) {
+ Enumeration en = failures.keys();
+ while (en.hasMoreElements()) {
+ Simulation sim = en.nextElement();
+ Throwable exc = failures.get(sim);
+ // notify user
+ PopupGenerator.showErrorDialog(clientSimManager.getDocumentWindowManager(),
+ "Failed to dispatch stop request for simulation'" + sim.getName() + "'\n"
+ + exc.getMessage(),
+ exc);
+ }
+ }
+ }
+ };
+ ClientTaskDispatcher.dispatch(clientSimManager.getDocumentWindowManager().getComponent(),
+ new Hashtable(), new AsynchClientTask[]{task1, task2});
+ }
+
+ public void updateStatusNow() {
+ // thread safe update of gui
+ AsynchClientTask task1 = new AsynchClientTask("updateStatusNow", AsynchClientTask.TASKTYPE_SWING_NONBLOCKING) {
+ @Override
+ public void run(Hashtable hashTable) throws Exception {
+ ClientRequestManager.this.getVcellClient().getStatusUpdater()
+ .updateNow(ClientRequestManager.this.getVcellClient().getClientServerManager().getConnectionStatus());
+
+ }
+ };
+ ClientTaskDispatcher.dispatch(null, new Hashtable(), new AsynchClientTask[]{task1});
+ }
+
+ public OpenModelInfoHolder[] getOpenDesktopDocumentInfos(boolean bIncludeSimulations) throws DataAccessException {
+ Vector simInfoHolderV = new Vector();
+ for (TopLevelWindowManager tlwm : this.getMdiManager().getWindowManagers()) {
+ if (tlwm instanceof DocumentWindowManager dwm) {
+ VCDocument vcDoc = dwm.getVCDocument();
+ // if(vcDoc.getVersion() != null){
+ if (vcDoc.getDocumentType() == VCDocumentType.BIOMODEL_DOC) {
+ BioModel bioModel = (BioModel) vcDoc;
+ // getDocumentManager().getBioModel(vcDoc.getVersion().getVersionKey());
+ SimulationContext[] simContexts = bioModel.getSimulationContexts();
+ for (int i = 0; i < simContexts.length; i += 1) {
+ if (bIncludeSimulations) {
+ if (simContexts[i].getGeometry() == null) {
+ throw new DataAccessException(
+ "Error gathering document info (isCompartmental check failed):\nOpen BioModel document "
+ + bioModel.getName() + " has no Geometry");
+ }
+ Simulation[] sims = simContexts[i].getSimulations();
+ for (int j = 0; j < sims.length; j += 1) {
+ for (int k = 0; k < sims[j].getScanCount(); k += 1) {
+ FieldDataWindowManager.OpenModelInfoHolder simInfoHolder = new FieldDataWindowManager.FDSimBioModelInfo(
+ sims[j].getName(), bioModel.getVersion(), simContexts[i],
+ sims[j].getSimulationInfo(), k,
+ // !sims[j].getSolverTaskDescription().getSolverDescription().hasVariableTimestep(),
+ simContexts[i].getGeometry().getDimension() == 0);
+ simInfoHolderV.add(simInfoHolder);
+ }
+ }
+ } else {
+ FieldDataWindowManager.OpenModelInfoHolder simInfoHolder = new FieldDataWindowManager.FDSimBioModelInfo(
+ null, bioModel.getVersion(), simContexts[i], null, -1,
+ simContexts[i].getGeometry().getDimension() == 0);
+ simInfoHolderV.add(simInfoHolder);
+ }
+ }
+ } else if (vcDoc.getDocumentType() == VCDocumentType.MATHMODEL_DOC) {
+ MathModel mathModel = (MathModel) vcDoc;
+ // getDocumentManager().getMathModel(vcDoc.getVersion().getVersionKey());
+ if (bIncludeSimulations) {
+ if (mathModel.getMathDescription() == null
+ || mathModel.getMathDescription().getGeometry() == null) {
+ throw new DataAccessException(
+ "Error gathering document info (isCompartmental check failed):\nOpen MathModel document "
+ + mathModel.getName() + " has either no MathDescription or no Geometry");
+ }
+ Simulation[] sims = mathModel.getSimulations();
+ for (int i = 0; i < sims.length; i += 1) {
+ for (int k = 0; k < sims[i].getScanCount(); k += 1) {
+ FieldDataWindowManager.OpenModelInfoHolder simInfoHolder = new FieldDataWindowManager.FDSimMathModelInfo(
+ sims[i].getName(), mathModel.getVersion(), mathModel.getMathDescription(),
+ sims[i].getSimulationInfo(), k,
+ // !sims[i].getSolverTaskDescription().getSolverDescription().hasVariableTimestep(),
+ mathModel.getMathDescription().getGeometry().getDimension() == 0);
+ simInfoHolderV.add(simInfoHolder);
+ }
+ }
+ } else {
+ FieldDataWindowManager.OpenModelInfoHolder simInfoHolder = new FieldDataWindowManager.FDSimMathModelInfo(
+ null, mathModel.getVersion(), mathModel.getMathDescription(), null, -1,
+ mathModel.getMathDescription().getGeometry().getDimension() == 0);
+ simInfoHolderV.add(simInfoHolder);
+ }
+ }
+ // }
+ }
+
+ }
+ OpenModelInfoHolder[] simInfoHolderArr = new OpenModelInfoHolder[simInfoHolderV.size()];
+ simInfoHolderV.copyInto(simInfoHolderArr);
+ return simInfoHolderArr;
+ }
+
+ public void showComparisonResults(TopLevelWindowManager requester, XmlTreeDiff diffTree, String baselineDesc,
+ String modifiedDesc) {
+ TMLPanel comparePanel = new TMLPanel();
+ comparePanel.setXmlTreeDiff(diffTree);
+ comparePanel.setBaselineVersionDescription(baselineDesc);
+ comparePanel.setModifiedVersionDescription(modifiedDesc);
+
+ JOptionPane comparePane = new JOptionPane(null, JOptionPane.PLAIN_MESSAGE, 0, null,
+ new Object[]{ /* "Apply Changes", */"Close"});
+ comparePane.setMessage(comparePanel);
+ JDialog compareDialog = comparePane.createDialog(requester.getComponent(), "Compare Models");
+ compareDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+ compareDialog.setResizable(true);
+ compareDialog.pack();
+ compareDialog.setVisible(true);
+ // ZEnforcer.showModalDialogOnTop(compareDialog,JOptionPane.getFrameForComponent(requester.getComponent()));
+ if ("Apply Changes".equals(comparePane.getValue())) {
+ if (!comparePanel.tagsResolved()) {
+ DialogUtils.showErrorDialog(comparePanel,
+ "Please resolve all tagged elements/attributes before proceeding.");
+ } else {
+ GeneralGuiUtils.setCursorThroughout((Container) requester.getComponent(),
+ Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ try {
+ this.processComparisonResult(comparePanel, requester);
+ } catch (RuntimeException e) {
+ throw e;
+ } finally {
+ GeneralGuiUtils.setCursorThroughout((Container) requester.getComponent(),
+ Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
+ }
+ }
+ }
+ }
//public void prepareDocumentToLoad(VCDocument doc) throws Exception {
// Simulation[] simulations = null;
@@ -4583,254 +4568,254 @@ public void showComparisonResults(TopLevelWindowManager requester, XmlTreeDiff d
// }
//}
- public static FieldDataFileOperationSpec createFDOSFromImageFile(File imageFile, boolean bCropOutBlack,
- Integer saveOnlyThisTimePointIndex) throws DataFormatException, ImageException {
- try {
- ImageDatasetReader imageDatasetReader = ImageDatasetReaderService.getInstance().getImageDatasetReader();
- ImageDataset[] imagedataSets = imageDatasetReader.readImageDatasetChannels(imageFile.getAbsolutePath(),
- null, false, saveOnlyThisTimePointIndex, null);
- if (imagedataSets != null && bCropOutBlack) {
- for (int i = 0; i < imagedataSets.length; i++) {
- Rectangle nonZeroRect = imagedataSets[i].getNonzeroBoundingRectangle();
- if (nonZeroRect != null) {
- imagedataSets[i] = imagedataSets[i].crop(nonZeroRect);
- }
- }
- }
- return createFDOSWithChannels(imagedataSets, null);
- } catch (Exception e) {
- e.printStackTrace(System.out);
- throw new DataFormatException(e.getMessage());
- }
- }
-
- public static FieldDataFileOperationSpec createFDOSWithChannels(ImageDataset[] imagedataSets,
- Integer saveOnlyThisTimePointIndex) {
- final FieldDataFileOperationSpec fdos = new FieldDataFileOperationSpec();
-
- // [time][var][data]
- int numXY = imagedataSets[0].getISize().getX() * imagedataSets[0].getISize().getY();
- int numXYZ = imagedataSets[0].getSizeZ() * numXY;
- fdos.variableTypes = new VariableType[imagedataSets.length];
- fdos.varNames = new String[imagedataSets.length];
- short[][][] shortData = new short[(saveOnlyThisTimePointIndex != null ? 1
- : imagedataSets[0].getSizeT())][imagedataSets.length][numXYZ];
- for (int c = 0; c < imagedataSets.length; c += 1) {
- fdos.variableTypes[c] = VariableType.VOLUME;
- fdos.varNames[c] = "Channel" + c;
- for (int t = 0; t < imagedataSets[c].getSizeT(); t += 1) {
- if (saveOnlyThisTimePointIndex != null && saveOnlyThisTimePointIndex.intValue() != t) {
- continue;
- }
- int zOffset = 0;
- for (int z = 0; z < imagedataSets[c].getSizeZ(); z += 1) {
- UShortImage ushortImage = imagedataSets[c].getImage(z, 0, t);
- System.arraycopy(ushortImage.getPixels(), 0,
- shortData[(saveOnlyThisTimePointIndex != null ? 0 : t)][c], zOffset, numXY);
+ public static FieldDataFileOperationSpec createFDOSFromImageFile(File imageFile, boolean bCropOutBlack,
+ Integer saveOnlyThisTimePointIndex) throws DataFormatException, ImageException {
+ try {
+ ImageDatasetReader imageDatasetReader = ImageDatasetReaderService.getInstance().getImageDatasetReader();
+ ImageDataset[] imagedataSets = imageDatasetReader.readImageDatasetChannels(imageFile.getAbsolutePath(),
+ null, false, saveOnlyThisTimePointIndex, null);
+ if (imagedataSets != null && bCropOutBlack) {
+ for (int i = 0; i < imagedataSets.length; i++) {
+ Rectangle nonZeroRect = imagedataSets[i].getNonzeroBoundingRectangle();
+ if (nonZeroRect != null) {
+ imagedataSets[i] = imagedataSets[i].crop(nonZeroRect);
+ }
+ }
+ }
+ return createFDOSWithChannels(imagedataSets, null);
+ } catch (Exception e) {
+ e.printStackTrace(System.out);
+ throw new DataFormatException(e.getMessage());
+ }
+ }
+
+ public static FieldDataFileOperationSpec createFDOSWithChannels(ImageDataset[] imagedataSets,
+ Integer saveOnlyThisTimePointIndex) {
+ final FieldDataFileOperationSpec fdos = new FieldDataFileOperationSpec();
+
+ // [time][var][data]
+ int numXY = imagedataSets[0].getISize().getX() * imagedataSets[0].getISize().getY();
+ int numXYZ = imagedataSets[0].getSizeZ() * numXY;
+ fdos.variableTypes = new VariableType[imagedataSets.length];
+ fdos.varNames = new String[imagedataSets.length];
+ short[][][] shortData = new short[(saveOnlyThisTimePointIndex != null ? 1
+ : imagedataSets[0].getSizeT())][imagedataSets.length][numXYZ];
+ for (int c = 0; c < imagedataSets.length; c += 1) {
+ fdos.variableTypes[c] = VariableType.VOLUME;
+ fdos.varNames[c] = "Channel" + c;
+ for (int t = 0; t < imagedataSets[c].getSizeT(); t += 1) {
+ if (saveOnlyThisTimePointIndex != null && saveOnlyThisTimePointIndex.intValue() != t) {
+ continue;
+ }
+ int zOffset = 0;
+ for (int z = 0; z < imagedataSets[c].getSizeZ(); z += 1) {
+ UShortImage ushortImage = imagedataSets[c].getImage(z, 0, t);
+ System.arraycopy(ushortImage.getPixels(), 0,
+ shortData[(saveOnlyThisTimePointIndex != null ? 0 : t)][c], zOffset, numXY);
// shortData[t][c] = ushortImage.getPixels();
- zOffset += numXY;
- }
- }
- }
- fdos.shortSpecData = shortData;
- fdos.times = imagedataSets[0].getImageTimeStamps();
- if (fdos.times == null) {
- fdos.times = new double[imagedataSets[0].getSizeT()];
- for (int i = 0; i < fdos.times.length; i += 1) {
- fdos.times[i] = i;
- }
- }
-
- fdos.origin = (imagedataSets[0].getAllImages()[0].getOrigin() != null
- ? imagedataSets[0].getAllImages()[0].getOrigin()
- : new Origin(0, 0, 0));
- fdos.extent = (imagedataSets[0].getExtent() != null) ? (imagedataSets[0].getExtent()) : (new Extent(1, 1, 1));
- fdos.isize = imagedataSets[0].getISize();
-
- return fdos;
-
- }
-
- public void accessPermissions(Component requester, VCDocument vcDoc) {
- VersionInfo selectedVersionInfo = null;
- switch (vcDoc.getDocumentType()) {
- case BIOMODEL_DOC:
- BioModelInfo[] bioModelInfos = getDocumentManager().getBioModelInfos();
- for (BioModelInfo bioModelInfo : bioModelInfos) {
- if (bioModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
- selectedVersionInfo = bioModelInfo;
- break;
- }
- }
- break;
- case MATHMODEL_DOC:
- MathModelInfo[] mathModelInfos = getDocumentManager().getMathModelInfos();
- for (MathModelInfo mathModelInfo : mathModelInfos) {
- if (mathModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
- selectedVersionInfo = mathModelInfo;
- break;
- }
- }
- break;
- case GEOMETRY_DOC:
- GeometryInfo[] geoInfos = getDocumentManager().getGeometryInfos();
- for (GeometryInfo geoInfo : geoInfos) {
- if (geoInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
- selectedVersionInfo = geoInfo;
- break;
- }
- }
- break;
- }
- getMdiManager().getDatabaseWindowManager().accessPermissions(requester, selectedVersionInfo, false);
-
- }
-
- public void accessPermissionsEx(Component requester, VCDocument vcDoc, boolean bGrantSupportPermissions) {
- VersionInfo selectedVersionInfo = null;
- switch (vcDoc.getDocumentType()) {
- case BIOMODEL_DOC:
- BioModelInfo[] bioModelInfos = getDocumentManager().getBioModelInfos();
- for (BioModelInfo bioModelInfo : bioModelInfos) {
- if (bioModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
- selectedVersionInfo = bioModelInfo;
- break;
- }
- }
- break;
- case MATHMODEL_DOC:
- MathModelInfo[] mathModelInfos = getDocumentManager().getMathModelInfos();
- for (MathModelInfo mathModelInfo : mathModelInfos) {
- if (mathModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
- selectedVersionInfo = mathModelInfo;
- break;
- }
- }
- break;
- case GEOMETRY_DOC:
- GeometryInfo[] geoInfos = getDocumentManager().getGeometryInfos();
- for (GeometryInfo geoInfo : geoInfos) {
- if (geoInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
- selectedVersionInfo = geoInfo;
- break;
- }
- }
- break;
- }
- getMdiManager().getDatabaseWindowManager().accessPermissions(requester, selectedVersionInfo, true);
-
- }
-
- public static Collection updateMath(final Component requester,
- final SimulationContext simulationContext, final boolean bShowWarning,
- final NetworkGenerationRequirements networkGenerationRequirements) {
- ArrayList rval = new ArrayList<>();
- AsynchClientTask task1 = new AsynchClientTask("generating math", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
-
- @Override
- public void run(Hashtable