From c4f83777fc321493bfbe75f5ac643c435a112d75 Mon Sep 17 00:00:00 2001 From: Alejandro De Maria Antolinos Date: Tue, 31 Oct 2017 10:24:22 +0100 Subject: [PATCH] Added security cheks for downloads --- .../services/sessions/Session3Service.java | 4 + .../sessions/Session3ServiceBean.java | 41 + .../src/main/webapp/js/ispyb/min/ispyb-bx.js | 24046 ++++++++-------- .../mx/AutoprocintegrationRestWebService.java | 62 +- 4 files changed, 12115 insertions(+), 12038 deletions(-) diff --git a/ispyb-ejb/src/main/java/ispyb/server/common/services/sessions/Session3Service.java b/ispyb-ejb/src/main/java/ispyb/server/common/services/sessions/Session3Service.java index a3fe103c2..472d285e6 100644 --- a/ispyb-ejb/src/main/java/ispyb/server/common/services/sessions/Session3Service.java +++ b/ispyb-ejb/src/main/java/ispyb/server/common/services/sessions/Session3Service.java @@ -175,6 +175,8 @@ public List findByStartDateAndBeamLineNameAndNbShifts(final Integer */ public Session3VO findByAutoProcScalingId(final Integer autoProcScalingId) throws Exception; + public Session3VO findByAutoProcProgramAttachmentId(final Integer autoProcProgramAttachmentId) throws Exception; + public void protectSession(Integer sessionId) throws Exception; /** @@ -195,6 +197,8 @@ public List findByStartDateAndBeamLineNameAndNbShifts(final Integer */ public Integer getNbOfTests(final Integer sesId) throws Exception; + public Session3VO findByAutoProcProgramId(int autoProcProgramId); + } \ No newline at end of file diff --git a/ispyb-ejb/src/main/java/ispyb/server/common/services/sessions/Session3ServiceBean.java b/ispyb-ejb/src/main/java/ispyb/server/common/services/sessions/Session3ServiceBean.java index 401f24495..27b4debdc 100644 --- a/ispyb-ejb/src/main/java/ispyb/server/common/services/sessions/Session3ServiceBean.java +++ b/ispyb-ejb/src/main/java/ispyb/server/common/services/sessions/Session3ServiceBean.java @@ -111,6 +111,19 @@ private static final String FIND_ALL(boolean fetchDataCollectionGroup, boolean f + " where s.sessionId = g.sessionId and " + " g.dataCollectionGroupId = c.dataCollectionGroupId and " + " c.dataCollectionId = api.dataCollectionId and " + " api.autoProcIntegrationId = apshi.autoProcIntegrationId and " + " apshi.autoProcScalingId = aps.autoProcScalingId and " + " aps.autoProcScalingId = :autoProcScalingId "; + + private static final String FIND_BY_AUTOPROCPROGRAMATTACHMENT_ID = "select s.* from BLSession s, " + + " DataCollectionGroup g, DataCollection c, AutoProcIntegration api, AutoProcProgram autoprocProgram, AutoProcProgramAttachment autoProcProgramAttachment" + + " where s.sessionId = g.sessionId and g.dataCollectionGroupId = c.dataCollectionGroupId and autoprocProgram.autoProcProgramId = api.autoProcProgramId" + + " and c.dataCollectionId = api.dataCollectionId and autoprocProgram.autoProcProgramId = autoProcProgramAttachment.autoProcProgramId " + + " and autoProcProgramAttachment.autoProcProgramAttachmentId = :autoProcProgramAttachmentId "; + + + private static final String FIND_BY_AUTOPROCPROGRAM_ID = "select s.* from BLSession s, " + + " DataCollectionGroup g, DataCollection c, AutoProcIntegration api, AutoProcProgram autoprocProgram " + + " where s.sessionId = g.sessionId and g.dataCollectionGroupId = c.dataCollectionGroupId and autoprocProgram.autoProcProgramId = api.autoProcProgramId" + + " and c.dataCollectionId = api.dataCollectionId and autoprocProgram.autoProcProgramId = :autoProcProgramId "; + private static String getProposalCodeNumberQuery() { String query = "select * " + " FROM BLSession ses, Proposal pro " @@ -525,6 +538,32 @@ public Session3VO findByAutoProcScalingId(final Integer autoProcScalingId) throw } return null; } + + + @SuppressWarnings("unchecked") + public Session3VO findByAutoProcProgramAttachmentId(final Integer autoProcProgramAttachmentId) throws Exception { + String query = FIND_BY_AUTOPROCPROGRAMATTACHMENT_ID; + List col = this.entityManager.createNativeQuery(query, "sessionNativeQuery") + .setParameter("autoProcProgramAttachmentId", autoProcProgramAttachmentId).getResultList(); + if (col != null && col.size() > 0) { + return col.get(0); + } + return null; + } + + + @Override + public Session3VO findByAutoProcProgramId(int autoProcProgramId) { + String query = FIND_BY_AUTOPROCPROGRAM_ID; + @SuppressWarnings("unchecked") + List col = this.entityManager.createNativeQuery(query, "sessionNativeQuery") + .setParameter("autoProcProgramId", autoProcProgramId).getResultList(); + if (col != null && col.size() > 0) { + return col.get(0); + } + return null; + } + /** @@ -818,4 +857,6 @@ private void checkChangeRemoveAccess(Session3VO vo) throws AccessDeniedException + + } \ No newline at end of file diff --git a/ispyb-ui/src/main/webapp/js/ispyb/min/ispyb-bx.js b/ispyb-ui/src/main/webapp/js/ispyb/min/ispyb-bx.js index 23e07209a..a98a06520 100644 --- a/ispyb-ui/src/main/webapp/js/ispyb/min/ispyb-bx.js +++ b/ispyb-ui/src/main/webapp/js/ispyb/min/ispyb-bx.js @@ -38,321 +38,321 @@ Event.prototype = { } }; -function GenericGraph(args) { - this.width = 600; - this.height = 400; - - this.targetId = null; - /** Free spaces in the borders * */ - this.top = 10; - this.left = 10; - this.bottom = 50; - this.right = 40; - - /** Ruler * */ - this.rulerHeight = 50; - this.rulerWidth = 50; - this.rulerStroke = 2; - this.rulerVerticalMarksNumber = 5; - - this.rulerMaxValue = null; - this.rulerMinValue = null; - - /** plot options * */ - this.plotPoints = true; - this.pointRadius = 2; - this.fillOpacityPoint = 0.2; - this.strokeOpacityPoint = 0.2; - - /** Cluster titles * */ - this.clusterTitleHeight = 20; - this.interClassesSpace = 2; - this.interClustersSpace = 4; - this.fontSize = 7; - - /** - * If true classes and title will be rendender in the rule otherwise will be - * integer values - */ - this.plotHorizontalByCluster = true; - - if (args != null) { - if (args.targetId != null) { - this.targetId = args.targetId; - } - if (args.plotHorizontalByCluster != null) { - this.plotHorizontalByCluster = args.plotHorizontalByCluster; - } - if (args.height != null) { - this.height = args.height; - } - if (args.width != null) { - this.width = args.width; - } - if (args.rulerMinValue != null) { - this.rulerMinValue = args.rulerMinValue; - } - if (args.rulerMaxValue != null) { - this.rulerMaxValue = args.rulerMaxValue; - } - if (args.rulerHeight != null) { - this.rulerHeight = args.rulerHeight; - } - - } -} - -GenericGraph.prototype.calculate = function(data) { - var result = {}; - - var checked = this.cleanArray(data); - - /** sorting array * */ - checked.sort(function(a, b) { - return a - b; - }); - - var median = this.getMedian(checked); - - result.median = median; - result.Q1 = Number(this.getQ1(checked)); - result.Q2 = Number(this.getQ2(checked)); - result.Q3 = Number(this.getQ3(checked)); - result.population = checked; - - result.IQR = Number(result.Q3 - result.Q1); - result.outlier_below_limit = result.Q1 - (1.5 * result.IQR); - result.outlier_above_limit = result.Q3 + (1.5 * result.IQR); - result.below_outliers = this.getBelowOutliers(result.outlier_below_limit, checked); - result.above_outliers = this.getAboveOutliers(result.outlier_above_limit, checked); - - result.min_whisker = this.minValueWhisker(result.outlier_below_limit, result.Q1, checked); - result.max_whisker = this.maxValueWhisker(result.outlier_above_limit, result.Q3, checked); - - return result; -}; - -GenericGraph.prototype.drawSVGVerticalText = function(x, y, text, properties) { - var transform = [ "transform", "translate(" + x + ", " + y + "), rotate(-90) " ]; - properties.push(transform); - SVG.drawText(0, 0, text, this.svg, properties); -}; - -/** Plot the numbers on the axis * */ -GenericGraph.prototype.plotRuler = function(rulerProperties) { - - SVG.drawRectangle(rulerProperties.vertical.x, rulerProperties.vertical.y, rulerProperties.vertical.width, rulerProperties.vertical.height, - this.svg, [ [ "fill", "black" ] ]); - var distance = rulerProperties.vertical.height / (this.rulerVerticalMarksNumber + 1); - for ( var i = 0; i <= this.rulerVerticalMarksNumber + 1; i++) { - var deltaHeight = distance * i; - var aux = rulerProperties.vertical.height - deltaHeight; - - var text = Number((aux / rulerProperties.vertical.height) * (rulerProperties.maxPoint - rulerProperties.minPoint) + rulerProperties.minPoint) - .toFixed(3); - - SVG.drawLine(rulerProperties.horizontal.x, this.top + deltaHeight, rulerProperties.horizontal.x - rulerProperties.markWidth, - this.top + deltaHeight, this.svg, [ [ "stroke", "black" ] ]); - SVG.drawText(this.left, this.top + distance * i + 5, text, this.svg, [ [ "style", "font-size:xx-small" ] ]); - /** Drawing the mark up to the end * */ - SVG.drawLine(rulerProperties.horizontal.x, this.top + deltaHeight, this.width - this.right, this.top + deltaHeight, this.svg, [ - [ "stroke", rulerProperties.markColor ], [ "stroke-width", "0.3" ] ]); - - if (i == this.rulerVerticalMarksNumber + 1) { - SVG.drawLine(rulerProperties.horizontal.x, this.top + deltaHeight, this.width - this.right, this.top + deltaHeight, this.svg, [ [ - "stroke", rulerProperties.markColor ] ]); - } - } - - /** Drawing horizontal rulers * */ - if (!this.plotHorizontalByCluster) { - var width = rulerProperties.horizontal.width; - var ratio = width / (rulerProperties.horizontal.xValues.range); - for ( i = 0; i < rulerProperties.horizontal.xValues.values.length; i++) { - var coorX = rulerProperties.horizontal.xValues.values[i] - rulerProperties.horizontal.xValues.min; - SVG.drawText(rulerProperties.horizontal.x + coorX * ratio, this.height - (this.bottom + (this.clusterTitleHeight)), - rulerProperties.horizontal.xValues.values[i], this.svg, [ [ "style", "font-size:small" ] ]); - } - } -}; - -GenericGraph.prototype.plotAxes = function(properties) { - /** - * Drawing canvas plot-free spaces SVG.drawRectangle(0, this.top, this.left, - * this.height, this.svg, [["fill", "pink"]]); SVG.drawRectangle(this.width - - * this.right, this.top, plot.width, plot.height, this.svg, [["fill", - * "pink"]]); SVG.drawRectangle(0, 0, this.width, this.top, this.svg, - * [["fill", "red"]]); SVG.drawRectangle(0, this.height - this.bottom, - * this.width, this.bottom, this.svg, [["fill", "red"]]); - */ - - /** Drawing ruler Space * */ - this.plotRuler({ - minPoint : Number(properties.minPoint), - maxPoint : Number(properties.maxPoint), - markColor : "black", - markWidth : 20, - vertical : { - x : this.left + this.rulerWidth - this.rulerStroke, - y : this.top, - width : this.rulerStroke, - height : this.height - (this.top + this.bottom + this.clusterTitleHeight) - this.rulerHeight - }, - horizontal : { - x : this.left + this.rulerWidth - this.rulerStroke, - y : this.height - (this.bottom + this.clusterTitleHeight + this.rulerHeight), - width : properties.width, - height : this.rulerStroke, - xValues : properties.xValues - } - }); - -}; - -/** Remove nulls and NaN elements in the array * */ -GenericGraph.prototype.cleanArray = function(data) { - var checked = []; - - /** checking data are numbers * */ - for ( var i = 0; i < data.length; i++) { - if (data[i] != null) { - if (!isNaN(data[i])) { - checked.push(data[i]); - } - } - } - return checked; -}; - -GenericGraph.prototype.refresh = function(data) { - document.getElementById(this.targetId).innerHTML = ""; - this.draw(this.targetId, data); -}; - -GenericGraph.prototype.getClassColor = function(className) { - for ( var i = 0; i < this.data.clusters.length; i++) { - var cluster = this.data.clusters[i]; - for ( var j = 0; j < cluster.classes.length; j++) { - var classes = cluster.classes[j]; - if (classes.name == className) { - if (classes.color != null) { - return classes.color; - } - } - } - } - return "black"; -}; - -GenericGraph.prototype.getDimensions = function(data) { - var results = {}; - var points = []; - - this.data = data; - var classesNumber = 0; - var xValues = []; - - for ( var i = 0; i < data.clusters.length; i++) { - var cluster = data.clusters[i]; - if (!this.plotHorizontalByCluster) { - xValues.push(data.clusters[i].x); - } - for ( var j = 0; j < cluster.classes.length; j++) { - var classes = cluster.classes[j]; - points = points.concat(classes.values); - classesNumber = classesNumber + 1; - } - } - - var checked = this.cleanArray(points); - - checked.sort(function(a, b) { - return a - b; - }); - - results.minPoint = checked[0]; - if (this.rulerMinValue != null) { - results.minPoint = this.rulerMinValue; - } - results.maxPoint = checked[checked.length - 1]; - if (this.rulerMaxValue != null) { - results.maxPoint = this.rulerMaxValue; - } - - results.classesNumber = classesNumber; - results.clusterNumber = data.clusters.length; - - var totalInterClassesFreeSpace = (classesNumber - data.clusters.length) * this.interClassesSpace; - var totalInterClusterFreeSpace = (data.clusters.length) * this.interClustersSpace; - results.classWidth = (this.width - (this.rulerWidth + this.left + this.right + totalInterClassesFreeSpace + totalInterClusterFreeSpace))/ classesNumber; - results.width = this.width - (this.right + this.left) - this.rulerWidth + this.rulerStroke; - - results.xValues = {}; - - xValues.sort(function(a, b) { - return a - b; - }); - results.xValues.values = xValues; - if (xValues.length > 0) { - results.xValues.min = xValues[0]; - results.xValues.max = xValues[xValues.length - 1]; - results.xValues.range = results.xValues.max - results.xValues.min; - } - return results; - -}; - -GenericGraph.prototype.draw = function(targetId, data) { - this.targetId = targetId; - var properties = (this.getDimensions(data)); - this.svg = SVG.createSVGCanvas(document.getElementById(this.targetId), [ [ "width", this.width ], [ "height", this.height ] ]); - this.plotAxes(properties); -}; - -GenericGraph.prototype.getMedian = function(checked) { - /** Calculating median * */ - if (checked.length % 2 == 1) { - return checked[Math.floor(checked.length / 2)]; - } else { - return (Number(checked[(checked.length / 2) - 1]) + Number(checked[checked.length / 2])) / 2; - } -}; - -GenericGraph.prototype.pointToPixel = function(value, boxProperties) { - var ratio = (value - boxProperties.minPoint) / (boxProperties.maxPoint - boxProperties.minPoint); - var pixelLength = boxProperties.height - boxProperties.y + this.top; - return (-1 * ratio) * (pixelLength) + (boxProperties.y + boxProperties.height); -}; - -GenericGraph.prototype.maxValueWhisker = function(aboveLimit, q3, array) { - var points = []; - for ( var i = 0; i < array.length; i++) { - if ((array[i] > q3) && (array[i]) <= aboveLimit) { - points.push(array[i]); - } - } - if (points.length > 0) { - points.sort(function(a, b) { - return a - b; - }); - return points[points.length - 1]; - } - return null; -}; - -GenericGraph.prototype.input = function() { - return DATADOC.getBoxWhikerData(); -}; - -GenericGraph.prototype.test = function(targetId) { - var plot = new GenericGraph({ - targetId : targetId, - height : 350, - width : 450, - maxBoxWidth : 25 - }); - plot.refresh(this.input()); -}; +function GenericGraph(args) { + this.width = 600; + this.height = 400; + + this.targetId = null; + /** Free spaces in the borders * */ + this.top = 10; + this.left = 10; + this.bottom = 50; + this.right = 40; + + /** Ruler * */ + this.rulerHeight = 50; + this.rulerWidth = 50; + this.rulerStroke = 2; + this.rulerVerticalMarksNumber = 5; + + this.rulerMaxValue = null; + this.rulerMinValue = null; + + /** plot options * */ + this.plotPoints = true; + this.pointRadius = 2; + this.fillOpacityPoint = 0.2; + this.strokeOpacityPoint = 0.2; + + /** Cluster titles * */ + this.clusterTitleHeight = 20; + this.interClassesSpace = 2; + this.interClustersSpace = 4; + this.fontSize = 7; + + /** + * If true classes and title will be rendender in the rule otherwise will be + * integer values + */ + this.plotHorizontalByCluster = true; + + if (args != null) { + if (args.targetId != null) { + this.targetId = args.targetId; + } + if (args.plotHorizontalByCluster != null) { + this.plotHorizontalByCluster = args.plotHorizontalByCluster; + } + if (args.height != null) { + this.height = args.height; + } + if (args.width != null) { + this.width = args.width; + } + if (args.rulerMinValue != null) { + this.rulerMinValue = args.rulerMinValue; + } + if (args.rulerMaxValue != null) { + this.rulerMaxValue = args.rulerMaxValue; + } + if (args.rulerHeight != null) { + this.rulerHeight = args.rulerHeight; + } + + } +} + +GenericGraph.prototype.calculate = function(data) { + var result = {}; + + var checked = this.cleanArray(data); + + /** sorting array * */ + checked.sort(function(a, b) { + return a - b; + }); + + var median = this.getMedian(checked); + + result.median = median; + result.Q1 = Number(this.getQ1(checked)); + result.Q2 = Number(this.getQ2(checked)); + result.Q3 = Number(this.getQ3(checked)); + result.population = checked; + + result.IQR = Number(result.Q3 - result.Q1); + result.outlier_below_limit = result.Q1 - (1.5 * result.IQR); + result.outlier_above_limit = result.Q3 + (1.5 * result.IQR); + result.below_outliers = this.getBelowOutliers(result.outlier_below_limit, checked); + result.above_outliers = this.getAboveOutliers(result.outlier_above_limit, checked); + + result.min_whisker = this.minValueWhisker(result.outlier_below_limit, result.Q1, checked); + result.max_whisker = this.maxValueWhisker(result.outlier_above_limit, result.Q3, checked); + + return result; +}; + +GenericGraph.prototype.drawSVGVerticalText = function(x, y, text, properties) { + var transform = [ "transform", "translate(" + x + ", " + y + "), rotate(-90) " ]; + properties.push(transform); + SVG.drawText(0, 0, text, this.svg, properties); +}; + +/** Plot the numbers on the axis * */ +GenericGraph.prototype.plotRuler = function(rulerProperties) { + + SVG.drawRectangle(rulerProperties.vertical.x, rulerProperties.vertical.y, rulerProperties.vertical.width, rulerProperties.vertical.height, + this.svg, [ [ "fill", "black" ] ]); + var distance = rulerProperties.vertical.height / (this.rulerVerticalMarksNumber + 1); + for ( var i = 0; i <= this.rulerVerticalMarksNumber + 1; i++) { + var deltaHeight = distance * i; + var aux = rulerProperties.vertical.height - deltaHeight; + + var text = Number((aux / rulerProperties.vertical.height) * (rulerProperties.maxPoint - rulerProperties.minPoint) + rulerProperties.minPoint) + .toFixed(3); + + SVG.drawLine(rulerProperties.horizontal.x, this.top + deltaHeight, rulerProperties.horizontal.x - rulerProperties.markWidth, + this.top + deltaHeight, this.svg, [ [ "stroke", "black" ] ]); + SVG.drawText(this.left, this.top + distance * i + 5, text, this.svg, [ [ "style", "font-size:xx-small" ] ]); + /** Drawing the mark up to the end * */ + SVG.drawLine(rulerProperties.horizontal.x, this.top + deltaHeight, this.width - this.right, this.top + deltaHeight, this.svg, [ + [ "stroke", rulerProperties.markColor ], [ "stroke-width", "0.3" ] ]); + + if (i == this.rulerVerticalMarksNumber + 1) { + SVG.drawLine(rulerProperties.horizontal.x, this.top + deltaHeight, this.width - this.right, this.top + deltaHeight, this.svg, [ [ + "stroke", rulerProperties.markColor ] ]); + } + } + + /** Drawing horizontal rulers * */ + if (!this.plotHorizontalByCluster) { + var width = rulerProperties.horizontal.width; + var ratio = width / (rulerProperties.horizontal.xValues.range); + for ( i = 0; i < rulerProperties.horizontal.xValues.values.length; i++) { + var coorX = rulerProperties.horizontal.xValues.values[i] - rulerProperties.horizontal.xValues.min; + SVG.drawText(rulerProperties.horizontal.x + coorX * ratio, this.height - (this.bottom + (this.clusterTitleHeight)), + rulerProperties.horizontal.xValues.values[i], this.svg, [ [ "style", "font-size:small" ] ]); + } + } +}; + +GenericGraph.prototype.plotAxes = function(properties) { + /** + * Drawing canvas plot-free spaces SVG.drawRectangle(0, this.top, this.left, + * this.height, this.svg, [["fill", "pink"]]); SVG.drawRectangle(this.width - + * this.right, this.top, plot.width, plot.height, this.svg, [["fill", + * "pink"]]); SVG.drawRectangle(0, 0, this.width, this.top, this.svg, + * [["fill", "red"]]); SVG.drawRectangle(0, this.height - this.bottom, + * this.width, this.bottom, this.svg, [["fill", "red"]]); + */ + + /** Drawing ruler Space * */ + this.plotRuler({ + minPoint : Number(properties.minPoint), + maxPoint : Number(properties.maxPoint), + markColor : "black", + markWidth : 20, + vertical : { + x : this.left + this.rulerWidth - this.rulerStroke, + y : this.top, + width : this.rulerStroke, + height : this.height - (this.top + this.bottom + this.clusterTitleHeight) - this.rulerHeight + }, + horizontal : { + x : this.left + this.rulerWidth - this.rulerStroke, + y : this.height - (this.bottom + this.clusterTitleHeight + this.rulerHeight), + width : properties.width, + height : this.rulerStroke, + xValues : properties.xValues + } + }); + +}; + +/** Remove nulls and NaN elements in the array * */ +GenericGraph.prototype.cleanArray = function(data) { + var checked = []; + + /** checking data are numbers * */ + for ( var i = 0; i < data.length; i++) { + if (data[i] != null) { + if (!isNaN(data[i])) { + checked.push(data[i]); + } + } + } + return checked; +}; + +GenericGraph.prototype.refresh = function(data) { + document.getElementById(this.targetId).innerHTML = ""; + this.draw(this.targetId, data); +}; + +GenericGraph.prototype.getClassColor = function(className) { + for ( var i = 0; i < this.data.clusters.length; i++) { + var cluster = this.data.clusters[i]; + for ( var j = 0; j < cluster.classes.length; j++) { + var classes = cluster.classes[j]; + if (classes.name == className) { + if (classes.color != null) { + return classes.color; + } + } + } + } + return "black"; +}; + +GenericGraph.prototype.getDimensions = function(data) { + var results = {}; + var points = []; + + this.data = data; + var classesNumber = 0; + var xValues = []; + + for ( var i = 0; i < data.clusters.length; i++) { + var cluster = data.clusters[i]; + if (!this.plotHorizontalByCluster) { + xValues.push(data.clusters[i].x); + } + for ( var j = 0; j < cluster.classes.length; j++) { + var classes = cluster.classes[j]; + points = points.concat(classes.values); + classesNumber = classesNumber + 1; + } + } + + var checked = this.cleanArray(points); + + checked.sort(function(a, b) { + return a - b; + }); + + results.minPoint = checked[0]; + if (this.rulerMinValue != null) { + results.minPoint = this.rulerMinValue; + } + results.maxPoint = checked[checked.length - 1]; + if (this.rulerMaxValue != null) { + results.maxPoint = this.rulerMaxValue; + } + + results.classesNumber = classesNumber; + results.clusterNumber = data.clusters.length; + + var totalInterClassesFreeSpace = (classesNumber - data.clusters.length) * this.interClassesSpace; + var totalInterClusterFreeSpace = (data.clusters.length) * this.interClustersSpace; + results.classWidth = (this.width - (this.rulerWidth + this.left + this.right + totalInterClassesFreeSpace + totalInterClusterFreeSpace))/ classesNumber; + results.width = this.width - (this.right + this.left) - this.rulerWidth + this.rulerStroke; + + results.xValues = {}; + + xValues.sort(function(a, b) { + return a - b; + }); + results.xValues.values = xValues; + if (xValues.length > 0) { + results.xValues.min = xValues[0]; + results.xValues.max = xValues[xValues.length - 1]; + results.xValues.range = results.xValues.max - results.xValues.min; + } + return results; + +}; + +GenericGraph.prototype.draw = function(targetId, data) { + this.targetId = targetId; + var properties = (this.getDimensions(data)); + this.svg = SVG.createSVGCanvas(document.getElementById(this.targetId), [ [ "width", this.width ], [ "height", this.height ] ]); + this.plotAxes(properties); +}; + +GenericGraph.prototype.getMedian = function(checked) { + /** Calculating median * */ + if (checked.length % 2 == 1) { + return checked[Math.floor(checked.length / 2)]; + } else { + return (Number(checked[(checked.length / 2) - 1]) + Number(checked[checked.length / 2])) / 2; + } +}; + +GenericGraph.prototype.pointToPixel = function(value, boxProperties) { + var ratio = (value - boxProperties.minPoint) / (boxProperties.maxPoint - boxProperties.minPoint); + var pixelLength = boxProperties.height - boxProperties.y + this.top; + return (-1 * ratio) * (pixelLength) + (boxProperties.y + boxProperties.height); +}; + +GenericGraph.prototype.maxValueWhisker = function(aboveLimit, q3, array) { + var points = []; + for ( var i = 0; i < array.length; i++) { + if ((array[i] > q3) && (array[i]) <= aboveLimit) { + points.push(array[i]); + } + } + if (points.length > 0) { + points.sort(function(a, b) { + return a - b; + }); + return points[points.length - 1]; + } + return null; +}; + +GenericGraph.prototype.input = function() { + return DATADOC.getBoxWhikerData(); +}; + +GenericGraph.prototype.test = function(targetId) { + var plot = new GenericGraph({ + targetId : targetId, + height : 350, + width : 450, + maxBoxWidth : 25 + }); + plot.refresh(this.input()); +}; /** * Using dygraph it plots a chart. Params: targetId, labelsContainerId, args @@ -2087,338 +2087,338 @@ MacromoleculeConditionGrid.prototype.test = function(targetId) { panel.render(targetId); }; - -function ItemGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ - this.id = id; - this.args = new Object(); - - this.defaultFormat = new ItemFormat(defaultFormat); - - if(selectedFormat != null){ - this.selected = new ItemFormat(selectedFormat); - } - else{ - this.selected = new ItemFormat(defaultFormat); - } - - if(overFormat != null){ - this.over = new ItemFormat(overFormat); - } - else{ - this.over = new ItemFormat(defaultFormat); - } - - if(draggingFormat != null){ - this.dragging = new ItemFormat(draggingFormat); - } - else{ - this.dragging = new ItemFormat(defaultFormat); - } - - //Events - this.stateChanged = new Event(this); - - - //Attaching events - var _this = this; - this._setEvents(); -}; - -ItemGraphFormatter.prototype.getType = function(){ - return this.args.type; -}; - - -ItemGraphFormatter.prototype.toJSON = function(){ - var json = this.args; - json.defaultFormat = this.getDefault().toJSON(); - json.over = this.getOver().toJSON(); - json.selected = this.getSelected().toJSON(); - json.dragging = this.getDragging().toJSON(); - json.id = this.id; - return json; -}; - -ItemGraphFormatter.prototype.loadFromJSON = function(json){ - this.args = json; - this.defaultFormat = new ItemFormat(json.defaultFormat); - this.over = new ItemFormat(json.over); - this.selected = new ItemFormat(json.selected); - this.dragging = new ItemFormat(json.dragging); - this._setEvents(); -}; - -ItemGraphFormatter.prototype._setEvents = function(){ - //Attaching events - var _this = this; - - this.defaultFormat.changed.attach(function (sender, item){ - _this.over.setSize(_this.defaultFormat.getSize()); - _this.selected.setSize(_this.defaultFormat.getSize()); - _this.dragging.setSize(_this.defaultFormat.getSize()); - _this.stateChanged.notify(_this); - }); - - this.selected.changed.attach(function (sender, item){ - _this.stateChanged.notify(_this); - }); - - this.over.changed.attach(function (sender, item){ - _this.stateChanged.notify(_this); - }); - - this.dragging.changed.attach(function (sender, item){ - _this.stateChanged.notify(_this); - }); -}; - -/** Getters **/ -ItemGraphFormatter.prototype.getId = function(){return this.id;}; -ItemGraphFormatter.prototype.getDefault = function(){return this.defaultFormat;}; -ItemGraphFormatter.prototype.getSelected = function(){return this.selected;}; -ItemGraphFormatter.prototype.getOver = function(){return this.over;}; -ItemGraphFormatter.prototype.getDragging = function(){return this.dragging;}; - -function ItemFormat(args){ - this.defaultFormat = new Object(); - this.args = new Object(); - this.args.title = new Object(); - //Defult properties - this.args.visible = true; - this.args.hidden = false; - this.args.stroke = "#000000"; - this.args.strokeOpacity = 0.8; - this.args["stroke-width"] = 1; - this.args.fill = "#000000"; - this.args["fill-opacity"] = 1; - this.args.size = 1; - this.args.opacity = 1; - this.args.fontSize = "8"; - this.args.fontColor = "#000000"; - - /** For directed edge with arrow **/ - //this.args.arrowSize = 1; - - - if (args != null){ - if (args.visible != null){ - this.args.visible = args.visible; - } - if (args.opacity != null){ - this.args.opacity = args.opacity; - } - if (args.size != null){ - this.args.size = args.size; - } - if (args.hidden != null){ - this.args.hidden = args.hidden; - } - if (args.stroke != null){ - this.args.stroke = this._fixColor(args.stroke); - } - if (args.strokeOpacity != null){ - this.args.strokeOpacity = args.strokeOpacity; - } - if (args["stroke-width"]!=null){ - this.args["stroke-width"] = args["stroke-width"]; - } - if (args["fill-opacity"]!=null){ - this.args["fill-opacity"] = args["fill-opacity"]; - } - if (args.shape!=null){ - this.args.shape = args.shape; - } - if (args.fill!=null){ - this.args.fill = this._fixColor(args.fill); - } - - - if (args.title!=null){ - if (args.title.fontSize!=null){ - this.args.title.fontSize = args.title.fontSize; - } - if (args.title.fill!=null){ - this.args.title.fill = this._fixColor(args.title.fill); - } - } - - /** For directed edge with arrow **/ - /*if (args.arrowSize!=null){ - this.args.arrowSize = args.arrowSize; - }*/ - - } - - this.changed = new Event(); -}; - -ItemFormat.prototype._fixColor = function(color){ - var fixed = color; - if (color.indexOf("green") != -1){ - fixed = '#04B431'; - } - - if (color.indexOf("blue") != -1){ - fixed = '#045FB4'; - } - - if (color.indexOf("red") != -1){ - fixed = '#DF0101'; - } - - if (color.indexOf("black") != -1){ - fixed = '#000000'; - } - - if (color.indexOf("white") != -1){ - fixed = '#FFFFFF'; - } - - if (color.indexOf("#") == -1){ - fixed = "#" + color; - } - return fixed; -}; - -ItemFormat.prototype.toJSON = function(){ - if(this.args.strokeOpacity != null){ - this.args["stroke-opacity"] = this.args.strokeOpacity; - delete this.args.strokeOpacity; - } - -// if(this.args.strokeWidth != null){ -// this.args["stroke-width"] = this.args.strokeWidth; -// delete this.args["stroke-width"]; -// } - - if(this.args.title.fontColor != null){ - this.args.title["font-color"] = this.args.title.fontColor; - } - else{ - this.args.title["font-color"] = this.args.fontColor;//;this.args.title.fontColor; - } - - if(this.args.title.fontSize != null){ - this.args.title["font-size"] = this.args.title.fontSize;//;this.args.title.fontColor; - } - else{ - this.args.title["font-size"] = this.args.fontSize;//;this.args.title.fontColor; - } - //return this.args; - return this.args; -}; - -ItemFormat.prototype.getAttribute = function(name){return this.args[name];}; - -//Getters and Setters -ItemFormat.prototype.setVisible = function(visible){ - if (this.args.visible != visible){ - this.args.visible = visible; - this.changed.notify(this); - } -}; - -ItemFormat.prototype.getVisible = function(){return this.args.visible;}; - -ItemFormat.prototype.setHidden = function(hidden){ - if (this.args.hidden != hidden){ - this.args.hidden = hidden; - this.changed.notify(this); - } -}; - -ItemFormat.prototype.getHidden = function(){return this.args.hidden;}; - - -ItemFormat.prototype.setStroke = function(stroke){ - if (this.args.stroke != stroke){ - this.args.stroke = stroke; - this.changed.notify(this); - } -}; - -ItemFormat.prototype.getStroke = function(){return this.args.stroke;}; - -ItemFormat.prototype.setStrokeOpacity = function(strokeOpacity){ - if (this.args.strokeOpacity != strokeOpacity){ - this.args.strokeOpacity = strokeOpacity; - this.changed.notify(this); - } -}; - -ItemFormat.prototype.getStrokeOpacity = function(){return this.args["stroke-opacity"];}; - -ItemFormat.prototype.setStrokeWidth = function(strokeWidth){ - if (this.args["stroke-width"] != strokeWidth){ - this.args["stroke-width"] = strokeWidth; - this.changed.notify(this); - } -}; - - -ItemFormat.prototype.getFillOpacity = function(){return this.args["fill-opacity"];}; - -ItemFormat.prototype.setfillOpacity = function(strokeWidth){ - if (this.args["fill-opacity"] != strokeWidth){ - this.args["fill-opacity"] = strokeWidth; - this.changed.notify(this); - } -}; - - -ItemFormat.prototype.getStrokeWidth = function(){ - return this.args["stroke-width"]; -}; - -ItemFormat.prototype.setFill = function(fill){ - if (this.args.fill != fill){ - this.args.fill = fill; - this.changed.notify(this); - } -}; - -ItemFormat.prototype.getFill = function(){return this.args.fill;}; - -ItemFormat.prototype.setSize = function(size){ - if (this.args.size != size){ - this.args.size = size; - this.changed.notify(this); - } -}; - -ItemFormat.prototype.getSize = function(){return this.args.size;}; - -ItemFormat.prototype.setOpacity = function(opacity){ - if (this.args.opacity != opacity){ - this.args.opacity = opacity; - this.changed.notify(this); - } -}; - -ItemFormat.prototype.getOpacity = function(){return this.args.opacity;}; - -ItemFormat.prototype.getArrowSize = function(){return this.args.arrowSize;}; - -ItemFormat.prototype.setArrowSize = function(arrowSize){ - if (this.args.arrowSize != arrowSize){ - this.args.arrowSize = arrowSize; - this.changed.notify(this); - } -}; - -ItemFormat.prototype.getFontSize = function(){return this.args.title.fontSize;}; - -ItemFormat.prototype.setFontSize = function(fontSize){ - - if (this.args.title.fontSize != fontSize){ - this.args.title.fontSize = fontSize; - this.changed.notify(this); - } -}; - - - - + +function ItemGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ + this.id = id; + this.args = new Object(); + + this.defaultFormat = new ItemFormat(defaultFormat); + + if(selectedFormat != null){ + this.selected = new ItemFormat(selectedFormat); + } + else{ + this.selected = new ItemFormat(defaultFormat); + } + + if(overFormat != null){ + this.over = new ItemFormat(overFormat); + } + else{ + this.over = new ItemFormat(defaultFormat); + } + + if(draggingFormat != null){ + this.dragging = new ItemFormat(draggingFormat); + } + else{ + this.dragging = new ItemFormat(defaultFormat); + } + + //Events + this.stateChanged = new Event(this); + + + //Attaching events + var _this = this; + this._setEvents(); +}; + +ItemGraphFormatter.prototype.getType = function(){ + return this.args.type; +}; + + +ItemGraphFormatter.prototype.toJSON = function(){ + var json = this.args; + json.defaultFormat = this.getDefault().toJSON(); + json.over = this.getOver().toJSON(); + json.selected = this.getSelected().toJSON(); + json.dragging = this.getDragging().toJSON(); + json.id = this.id; + return json; +}; + +ItemGraphFormatter.prototype.loadFromJSON = function(json){ + this.args = json; + this.defaultFormat = new ItemFormat(json.defaultFormat); + this.over = new ItemFormat(json.over); + this.selected = new ItemFormat(json.selected); + this.dragging = new ItemFormat(json.dragging); + this._setEvents(); +}; + +ItemGraphFormatter.prototype._setEvents = function(){ + //Attaching events + var _this = this; + + this.defaultFormat.changed.attach(function (sender, item){ + _this.over.setSize(_this.defaultFormat.getSize()); + _this.selected.setSize(_this.defaultFormat.getSize()); + _this.dragging.setSize(_this.defaultFormat.getSize()); + _this.stateChanged.notify(_this); + }); + + this.selected.changed.attach(function (sender, item){ + _this.stateChanged.notify(_this); + }); + + this.over.changed.attach(function (sender, item){ + _this.stateChanged.notify(_this); + }); + + this.dragging.changed.attach(function (sender, item){ + _this.stateChanged.notify(_this); + }); +}; + +/** Getters **/ +ItemGraphFormatter.prototype.getId = function(){return this.id;}; +ItemGraphFormatter.prototype.getDefault = function(){return this.defaultFormat;}; +ItemGraphFormatter.prototype.getSelected = function(){return this.selected;}; +ItemGraphFormatter.prototype.getOver = function(){return this.over;}; +ItemGraphFormatter.prototype.getDragging = function(){return this.dragging;}; + +function ItemFormat(args){ + this.defaultFormat = new Object(); + this.args = new Object(); + this.args.title = new Object(); + //Defult properties + this.args.visible = true; + this.args.hidden = false; + this.args.stroke = "#000000"; + this.args.strokeOpacity = 0.8; + this.args["stroke-width"] = 1; + this.args.fill = "#000000"; + this.args["fill-opacity"] = 1; + this.args.size = 1; + this.args.opacity = 1; + this.args.fontSize = "8"; + this.args.fontColor = "#000000"; + + /** For directed edge with arrow **/ + //this.args.arrowSize = 1; + + + if (args != null){ + if (args.visible != null){ + this.args.visible = args.visible; + } + if (args.opacity != null){ + this.args.opacity = args.opacity; + } + if (args.size != null){ + this.args.size = args.size; + } + if (args.hidden != null){ + this.args.hidden = args.hidden; + } + if (args.stroke != null){ + this.args.stroke = this._fixColor(args.stroke); + } + if (args.strokeOpacity != null){ + this.args.strokeOpacity = args.strokeOpacity; + } + if (args["stroke-width"]!=null){ + this.args["stroke-width"] = args["stroke-width"]; + } + if (args["fill-opacity"]!=null){ + this.args["fill-opacity"] = args["fill-opacity"]; + } + if (args.shape!=null){ + this.args.shape = args.shape; + } + if (args.fill!=null){ + this.args.fill = this._fixColor(args.fill); + } + + + if (args.title!=null){ + if (args.title.fontSize!=null){ + this.args.title.fontSize = args.title.fontSize; + } + if (args.title.fill!=null){ + this.args.title.fill = this._fixColor(args.title.fill); + } + } + + /** For directed edge with arrow **/ + /*if (args.arrowSize!=null){ + this.args.arrowSize = args.arrowSize; + }*/ + + } + + this.changed = new Event(); +}; + +ItemFormat.prototype._fixColor = function(color){ + var fixed = color; + if (color.indexOf("green") != -1){ + fixed = '#04B431'; + } + + if (color.indexOf("blue") != -1){ + fixed = '#045FB4'; + } + + if (color.indexOf("red") != -1){ + fixed = '#DF0101'; + } + + if (color.indexOf("black") != -1){ + fixed = '#000000'; + } + + if (color.indexOf("white") != -1){ + fixed = '#FFFFFF'; + } + + if (color.indexOf("#") == -1){ + fixed = "#" + color; + } + return fixed; +}; + +ItemFormat.prototype.toJSON = function(){ + if(this.args.strokeOpacity != null){ + this.args["stroke-opacity"] = this.args.strokeOpacity; + delete this.args.strokeOpacity; + } + +// if(this.args.strokeWidth != null){ +// this.args["stroke-width"] = this.args.strokeWidth; +// delete this.args["stroke-width"]; +// } + + if(this.args.title.fontColor != null){ + this.args.title["font-color"] = this.args.title.fontColor; + } + else{ + this.args.title["font-color"] = this.args.fontColor;//;this.args.title.fontColor; + } + + if(this.args.title.fontSize != null){ + this.args.title["font-size"] = this.args.title.fontSize;//;this.args.title.fontColor; + } + else{ + this.args.title["font-size"] = this.args.fontSize;//;this.args.title.fontColor; + } + //return this.args; + return this.args; +}; + +ItemFormat.prototype.getAttribute = function(name){return this.args[name];}; + +//Getters and Setters +ItemFormat.prototype.setVisible = function(visible){ + if (this.args.visible != visible){ + this.args.visible = visible; + this.changed.notify(this); + } +}; + +ItemFormat.prototype.getVisible = function(){return this.args.visible;}; + +ItemFormat.prototype.setHidden = function(hidden){ + if (this.args.hidden != hidden){ + this.args.hidden = hidden; + this.changed.notify(this); + } +}; + +ItemFormat.prototype.getHidden = function(){return this.args.hidden;}; + + +ItemFormat.prototype.setStroke = function(stroke){ + if (this.args.stroke != stroke){ + this.args.stroke = stroke; + this.changed.notify(this); + } +}; + +ItemFormat.prototype.getStroke = function(){return this.args.stroke;}; + +ItemFormat.prototype.setStrokeOpacity = function(strokeOpacity){ + if (this.args.strokeOpacity != strokeOpacity){ + this.args.strokeOpacity = strokeOpacity; + this.changed.notify(this); + } +}; + +ItemFormat.prototype.getStrokeOpacity = function(){return this.args["stroke-opacity"];}; + +ItemFormat.prototype.setStrokeWidth = function(strokeWidth){ + if (this.args["stroke-width"] != strokeWidth){ + this.args["stroke-width"] = strokeWidth; + this.changed.notify(this); + } +}; + + +ItemFormat.prototype.getFillOpacity = function(){return this.args["fill-opacity"];}; + +ItemFormat.prototype.setfillOpacity = function(strokeWidth){ + if (this.args["fill-opacity"] != strokeWidth){ + this.args["fill-opacity"] = strokeWidth; + this.changed.notify(this); + } +}; + + +ItemFormat.prototype.getStrokeWidth = function(){ + return this.args["stroke-width"]; +}; + +ItemFormat.prototype.setFill = function(fill){ + if (this.args.fill != fill){ + this.args.fill = fill; + this.changed.notify(this); + } +}; + +ItemFormat.prototype.getFill = function(){return this.args.fill;}; + +ItemFormat.prototype.setSize = function(size){ + if (this.args.size != size){ + this.args.size = size; + this.changed.notify(this); + } +}; + +ItemFormat.prototype.getSize = function(){return this.args.size;}; + +ItemFormat.prototype.setOpacity = function(opacity){ + if (this.args.opacity != opacity){ + this.args.opacity = opacity; + this.changed.notify(this); + } +}; + +ItemFormat.prototype.getOpacity = function(){return this.args.opacity;}; + +ItemFormat.prototype.getArrowSize = function(){return this.args.arrowSize;}; + +ItemFormat.prototype.setArrowSize = function(arrowSize){ + if (this.args.arrowSize != arrowSize){ + this.args.arrowSize = arrowSize; + this.changed.notify(this); + } +}; + +ItemFormat.prototype.getFontSize = function(){return this.args.title.fontSize;}; + +ItemFormat.prototype.setFontSize = function(fontSize){ + + if (this.args.title.fontSize != fontSize){ + this.args.title.fontSize = fontSize; + this.changed.notify(this); + } +}; + + + + /** * This class executes the actions @@ -4952,2095 +4952,1101 @@ function openExperiment(experimentId) { BIOSAXS.openExperiment(experimentId); } -var SITE_CONF = { - SAMPLE_CHANGER_CONFIGURATION : { - "3":{ - "platetype3VO": {"plateTypeId":4,"name":"96 Well plate","rowCount":8,"columnCount":12,"shape":"REC"}, - "name":"96 Well plate", - "slotPositionRow":"1", - "slotPositionColumn":"3", - "storageTemperature":"0", - "sampleplateposition3VOs":[], - "experimentId":0 - }, - "2":{ - "platetype3VO":{"plateTypeId":2,"name":" 4 x ( 8 + 3 ) Block","rowCount":4,"columnCount":11,"shape":"REC"}, - "name":" 4 x ( 8 + 3 ) Block", - "slotPositionRow":"1", - "slotPositionColumn":"2", - "storageTemperature":"0", - "sampleplateposition3VOs":[],"experimentId":0 - }, - "1":{ - "platetype3VO":{"plateTypeId":1,"name":"Deep Well","rowCount":8,"columnCount":12,"shape":"REC"}, - "name":"Deep Well", - "slotPositionRow":"1", - "slotPositionColumn":"1", - "storageTemperature":"0", - "sampleplateposition3VOs":[], - "experimentId":0 - } - } +var SITE_CONF = { + SAMPLE_CHANGER_CONFIGURATION : { + "3":{ + "platetype3VO": {"plateTypeId":4,"name":"96 Well plate","rowCount":8,"columnCount":12,"shape":"REC"}, + "name":"96 Well plate", + "slotPositionRow":"1", + "slotPositionColumn":"3", + "storageTemperature":"0", + "sampleplateposition3VOs":[], + "experimentId":0 + }, + "2":{ + "platetype3VO":{"plateTypeId":2,"name":" 4 x ( 8 + 3 ) Block","rowCount":4,"columnCount":11,"shape":"REC"}, + "name":" 4 x ( 8 + 3 ) Block", + "slotPositionRow":"1", + "slotPositionColumn":"2", + "storageTemperature":"0", + "sampleplateposition3VOs":[],"experimentId":0 + }, + "1":{ + "platetype3VO":{"plateTypeId":1,"name":"Deep Well","rowCount":8,"columnCount":12,"shape":"REC"}, + "name":"Deep Well", + "slotPositionRow":"1", + "slotPositionColumn":"1", + "storageTemperature":"0", + "sampleplateposition3VOs":[], + "experimentId":0 + } + } }; - -var ISPYB_CONF = { - load : function(config) { - for (var key in config) { - ISPYB_CONF[key] = config[key]; - } - }, - SAMPLE_CHANGER_CONFIGURATION : { - "1": { - "platetype3VO": {"plateTypeId": 1, "name": "Deep Well", "rowCount": 8, "columnCount": 12, "shape": "REC"}, - "name": "Deep Well", - "slotPositionRow": "1", - "slotPositionColumn": "1", - "storageTemperature": "0", - "sampleplateposition3VOs": [], - "experimentId": 0 - } - } + +var ISPYB_CONF = { + load : function(config) { + for (var key in config) { + ISPYB_CONF[key] = config[key]; + } + }, + SAMPLE_CHANGER_CONFIGURATION : { + "1": { + "platetype3VO": {"plateTypeId": 1, "name": "Deep Well", "rowCount": 8, "columnCount": 12, "shape": "REC"}, + "name": "Deep Well", + "slotPositionRow": "1", + "slotPositionColumn": "1", + "storageTemperature": "0", + "sampleplateposition3VOs": [], + "experimentId": 0 + } + } }; -var SITE_CONF = { - -}; - -/** - * Example form - * - * @witdh - * @height - */ -function AbinitioForm(args) { - this.id = BUI.id(); - this.width = null; - this.height = null; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } - - var _this = this; - /** Widgets **/ - this.abinitioGrid = new AbinitioGrid({ - width : null, - height : 200 - }); - - this.abinitioGrid.onSelected.attach(function(sender, models) { - var modelsIdList = []; - for ( var i in models) { - modelsIdList.push(models[i].modelId); - } - _this._renderPlot(_this.subtractions[0].subtractionId, modelsIdList); - _this._renderPDB(modelsIdList); - }); - - /** Dygraph Widget that plots fir files**/ - this.plotWidget = new PlotWidget({ - width : 745 / 2, - height : 300, - margin : "10 0 5 10" - }); - - /** PDB viewer **/ - this.viewer = new PDBViewer({ - width : 745 / 2, - height : 300 - }); - -} - -AbinitioForm.prototype._renderPlot = function(subtractionId, modelsIdList) { - /** Trying to plot tje subtraction and the models **/ - try { - var colors = [ "#669900", "#0000FF" ]; - this.plotWidget.refresh([], [ ], modelsIdList, [], [], colors); - } catch (e) { - console.log(e); - } -}; - -AbinitioForm.prototype._renderPDB = function(modelsIdList) { - /** Trying to plot the PDB file **/ - try { - var viz = []; - for (var i = 0; i < modelsIdList.length; i++) { - viz.push({ - modelId : modelsIdList[i], - color : "0xFF6600", - opacity : 0.8 - }); - } - this.viewer.refresh(viz); - } catch (e) { - console.log(e); - } -}; - -AbinitioForm.prototype._getItems = function() { - var _this = this; - return [ { - xtype : 'label', - forId : 'myFieldId', - text : 'INLINE HELP: To be updated', - margin : '15 0 20 10', - cls : "inline-help" - }, this.abinitioGrid.getPanel(), { - xtype : 'container', - layout : 'hbox', - items : [ this.plotWidget.getPanel(), this.viewer.getPanel() ] - } ] -}; - -AbinitioForm.prototype._getButtons = function() { - return []; -}; - -AbinitioForm.prototype.getPanel = function() { - var _this = this; - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - margin : 10, - border : 1, - defaultType : 'textfield', - items : this._getItems(), - buttons : this._getButtons(), - listeners : { - afterrender : function() { - _this._populate(); +var SITE_CONF = { + +}; - } - } - }); - return this.panel; -}; +/** + * Example form + * + * @witdh + * @height + */ +function AbinitioForm(args) { + this.id = BUI.id(); + this.width = null; + this.height = null; + + if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } + } + + var _this = this; + /** Widgets **/ + this.abinitioGrid = new AbinitioGrid({ + width : null, + height : 200 + }); + + this.abinitioGrid.onSelected.attach(function(sender, models) { + var modelsIdList = []; + for ( var i in models) { + modelsIdList.push(models[i].modelId); + } + _this._renderPlot(_this.subtractions[0].subtractionId, modelsIdList); + _this._renderPDB(modelsIdList); + }); + + /** Dygraph Widget that plots fir files**/ + this.plotWidget = new PlotWidget({ + width : 745 / 2, + height : 300, + margin : "10 0 5 10" + }); + + /** PDB viewer **/ + this.viewer = new PDBViewer({ + width : 745 / 2, + height : 300 + }); + +} + +AbinitioForm.prototype._renderPlot = function(subtractionId, modelsIdList) { + /** Trying to plot tje subtraction and the models **/ + try { + var colors = [ "#669900", "#0000FF" ]; + this.plotWidget.refresh([], [ ], modelsIdList, [], [], colors); + } catch (e) { + console.log(e); + } +}; + +AbinitioForm.prototype._renderPDB = function(modelsIdList) { + /** Trying to plot the PDB file **/ + try { + var viz = []; + for (var i = 0; i < modelsIdList.length; i++) { + viz.push({ + modelId : modelsIdList[i], + color : "0xFF6600", + opacity : 0.8 + }); + } + this.viewer.refresh(viz); + } catch (e) { + console.log(e); + } +}; + +AbinitioForm.prototype._getItems = function() { + var _this = this; + return [ { + xtype : 'label', + forId : 'myFieldId', + text : 'INLINE HELP: To be updated', + margin : '15 0 20 10', + cls : "inline-help" + }, this.abinitioGrid.getPanel(), { + xtype : 'container', + layout : 'hbox', + items : [ this.plotWidget.getPanel(), this.viewer.getPanel() ] + } ] +}; + +AbinitioForm.prototype._getButtons = function() { + return []; +}; + +AbinitioForm.prototype.getPanel = function() { + var _this = this; + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + margin : 10, + border : 1, + defaultType : 'textfield', + items : this._getItems(), + buttons : this._getButtons(), + listeners : { + afterrender : function() { + _this._populate(); + + } + } + }); + return this.panel; +}; + +/** Populates could be call when the DOM is not filled yet **/ +AbinitioForm.prototype._populate = function() { +}; + +/** It populates the form * */ +AbinitioForm.prototype.refresh = function(subtractions) { + this.subtractions = subtractions; + this.abinitioGrid.refresh(subtractions); +}; + +AbinitioForm.prototype.input = function() { + return {}; +}; + +/** It populates the form **/ +AbinitioForm.prototype.test = function(targetId) { + var macromoleculeForm = new AbinitioForm(); + var panel = macromoleculeForm.getPanel(); + panel.render(targetId); +}; -/** Populates could be call when the DOM is not filled yet **/ -AbinitioForm.prototype._populate = function() { -}; - -/** It populates the form * */ -AbinitioForm.prototype.refresh = function(subtractions) { - this.subtractions = subtractions; - this.abinitioGrid.refresh(subtractions); -}; - -AbinitioForm.prototype.input = function() { - return {}; -}; - -/** It populates the form **/ -AbinitioForm.prototype.test = function(targetId) { - var macromoleculeForm = new AbinitioForm(); - var panel = macromoleculeForm.getPanel(); - panel.render(targetId); -}; - -/** - * Example form - * - * @witdh - * @height - */ -function DataReductionForm(args) { - this.id = BUI.id(); - this.width = null; - this.height = null; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } - - var _this = this; - - /** Widgets **/ - this.plotWidget = new PlotWidget({ - width : 650, - height : 490 - }); - - /** Selected frames to be displayed **/ - this.selectedItems = { - frames : [], - averages : [], - subtractions : [] - }; - -} - -DataReductionForm.prototype._parseSelectedItemsToIds = function(selectedArray) { - var ids = []; - if (selectedArray != null) { - for (var i = 0; i < selectedArray.length; i++) { - ids.push(selectedArray[i].id); - } - } - return ids; -}; - -DataReductionForm.prototype.onSelectionChanged = function(columnName, selected) { - if (selected != null) { - if (columnName == "Frames") { - this.selectedItems.frames = selected; - this.selectedItems.subtractions = []; - } - if (columnName == "Averages") { - this.selectedItems.averages = selected; - } - if (columnName == "Subtractions") { - this.selectedItems.frames = []; - this.selectedItems.subtractions = selected; - } - } - this.plotWidget.refresh(this._parseSelectedItemsToIds(this.selectedItems.frames), this._parseSelectedItemsToIds(this.selectedItems.subtractions)); -}; - -DataReductionForm.prototype._getFramesExtPanel = function(store, columnName, height) { - var _this = this; - - var selModel = Ext.create('Ext.selection.RowModel', { - allowDeselect : true, - mode : 'MULTI', - listeners : { - selectionchange : function(sm, selections) { - var selected = []; - for (var i = 0; i < selections.length; i++) { - selected.push(selections[i].raw); - } - _this.onSelectionChanged(columnName, selected); - } - } - }); - - return Ext.create('Ext.grid.Panel', { - store : store, - margin : 10, - height : height, - width : 200, - selModel : selModel, - columns : [ { - text : columnName, - dataIndex : 'fileName', - flex : 1 - } ], - viewConfig : { - } - }); -}; - -DataReductionForm.prototype._getFramesPanel = function() { - var fields = [ 'fileName', 'type', 'id' ]; - - this.framesStore = Ext.create('Ext.data.Store', { - fields : fields, - sorters : 'fileName' - }); - - this.averagesStore = Ext.create('Ext.data.Store', { - fields : fields - }); - - this.subtractionStore = Ext.create('Ext.data.Store', { - fields : fields - }); - - var gridFrames = this._getFramesExtPanel(this.framesStore, "Frames", 375); - var gridAvgs = this._getFramesExtPanel(this.averagesStore, "Averages", 125); - var subtractionAvgs = this._getFramesExtPanel(this.subtractionStore, "Subtractions", 75); - - return { - xtype : 'container', - layout : 'vbox', - items : [ gridFrames, subtractionAvgs ] - }; -}; - -DataReductionForm.prototype._getImageContainer = function(name, help) { - var html = "
" + name + "
" - return { - xtype : 'container', - layout : 'vbox', - items : [ { - html : html, - margin : "5 0 0 0", - height : 95, - width : 100 - }, { - xtype : 'label', - forId : 'myFieldId', - text : help, - margin : '5 0 0 0', - cls : "inline-help" - } ] - } -}; - -DataReductionForm.prototype._getItems = function() { - var _this = this; - return [ { - xtype : 'container', - layout : 'hbox', - items : [ - this._getFramesPanel(), - this.plotWidget.getPanel(), - { - xtype : 'panel', - width : 110, - frame : true, - margin : "10 5 5 5", - border : 0, - layout : 'vbox', - items : [ this._getImageContainer("scattering", "Scattering"), this._getImageContainer("guinier", "Guinier Region"), - this._getImageContainer("kratky", "Kratky Plot"), this._getImageContainer("gnom", "P(r) distribution") ] - } ] - } ] -}; - -DataReductionForm.prototype._getButtons = function() { - return []; -}; - -DataReductionForm.prototype.getPanel = function() { - var _this = this; - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - border : 0, - items : this._getItems(), - buttons : this._getButtons(), - listeners : { - afterrender : function() { - _this._populate(); - } - } - }); - return this.panel; -}; - -/** Populates could be call when the DOM is not filled yet **/ -DataReductionForm.prototype._populate = function() { -}; - -/** It populates the form * */ -DataReductionForm.prototype.refresh = function(subtractions) { - if (subtractions != null) { - for (var i = 0; i < subtractions.length; i++) { - /** Loading frame grids **/ - var subtraction = subtractions[i]; - var averages = [ { - fileName : BUI.getFileName(subtraction.bufferAverageFilePath), - type : 'bufferAvg', - id : subtraction.subtractionId - }, { - fileName : BUI.getFileName(subtraction.sampleAverageFilePath), - type : 'sampleAvg', - id : subtraction.subtractionId - } - - ]; - this.averagesStore.loadData(averages, true); - this.subtractionStore.loadData([ { - fileName : BUI.getFileName(subtraction.substractedFilePath), - type : 'SUBTRACTION', - id : subtraction.subtractionId - } ], true); - - var frames = []; - /** Buffers **/ - if (subtraction.bufferOneDimensionalFiles != null) { - if (subtraction.bufferOneDimensionalFiles.frametolist3VOs != null) { - for (var j = 0; j < subtraction.bufferOneDimensionalFiles.frametolist3VOs.length; j++) { - var frametolist3VO = subtraction.bufferOneDimensionalFiles.frametolist3VOs[j]; - if (frametolist3VO.frame3VO != null) { - frames.push({ - fileName : BUI.getFileName(frametolist3VO.frame3VO.filePath), - type : 'BUFFER', - id : frametolist3VO.frame3VO.frameId - }); - } - } - } - } - /** Samples **/ - if (subtraction.sampleOneDimensionalFiles != null) { - if (subtraction.sampleOneDimensionalFiles.frametolist3VOs != null) { - for (var j = 0; j < subtraction.sampleOneDimensionalFiles.frametolist3VOs.length; j++) { - var frametolist3VO = subtraction.sampleOneDimensionalFiles.frametolist3VOs[j]; - if (frametolist3VO.frame3VO != null) { - frames.push({ - fileName : BUI.getFileName(frametolist3VO.frame3VO.filePath), - type : 'SAMPLE', - id : frametolist3VO.frame3VO.frameId - }); - } - } - } - } - - this.framesStore.loadData(frames, true); - - /** Loading images **/ - this._displayImage("scattering", subtraction.subtractionId); - this._displayImage("kratky", subtraction.subtractionId); - this._displayImage("guinier", subtraction.subtractionId); - this._displayImage("gnom", subtraction.subtractionId); - } - } -}; - -DataReductionForm.prototype._displayImage = function(name, subtractionId) { - var url = BUI.getURL() + '&type=' + name + '&subtractionId=' + subtractionId; - var event = "OnClick= window.open('" + url + "')"; - document.getElementById(this.id + "_" + name).innerHTML = ''; -}; - -DataReductionForm.prototype.input = function() { - return {}; -}; - -/** It populates the form **/ -DataReductionForm.prototype.test = function(targetId) { - var macromoleculeForm = new DataReductionForm(); - var panel = macromoleculeForm.getPanel(); - panel.render(targetId); -}; - -function PlotWidget(args) { - this.width = 600; - this.height = 600; - this.id = BUI.id(); - - this.linear = false; - - this.margin = "10 0 0 0"; - /** for each stat the max and minimum value when it is scaled in order to show correctly in the legend **/ - this.ranges = {}; - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - if (args.margin != null) { - this.margin = args.margin; - } - } - -} - -PlotWidget.prototype.getMenu = function() { - var _this = this; - /** Actions buttons **/ - var actions = []; - actions.push("->"); - actions.push({ - text : "Export as Image", - scope : this, - icon : '../images/save.gif', - handler : function(item, pressed) { - var largeImage = document.createElement("img"); - largeImage.style.display = 'block'; - largeImage.style.width = 200 + "px"; - largeImage.style.height = 200 + "px"; - largeImage.setAttribute('src', Dygraph.Export.asCanvas(this.dygraphObject.dygraph).toDataURL()); - window.open(Dygraph.Export.asCanvas(this.dygraphObject.dygraph).toDataURL(), 'Image', ''); - } - }); - - return actions; -}; - -/** Looks for the maximum value and then divide everything but that value **/ -PlotWidget.prototype.scaledData = function(data) { - for (var i = 0; i < data.length; i++) { - var values = this.getMaxAndMinValue(data[i]); - data[i] = this.divideValuesByMax(data[i], values.max); - this.ranges[data[i].label] = values; - } - return data; -}; - -/** Given a stat float[] and a max number it will divide each value by max **/ -PlotWidget.prototype.divideValuesByMax = function(stat, max) { - for (var j = 0; j < stat.data.length; j++) { - if (max != 0) { - stat.data[j] = Number(stat.data[j]) / max; - stat.std[j] = Number(stat.std[j]) / max; - } - } - return stat; -}; - -/** returns max value of a stat **/ -PlotWidget.prototype.getMaxAndMinValue = function(stat) { - var max = 0; - var min = stat.data[0]; - for (var j = 0; j < stat.data.length; j++) { - if (Number(stat.data[j]) > max) { - max = Number(stat.data[j]); - } - if (Number(stat.std[j]) > max) { - max = Number(stat.std[j]); - } - if (Number(stat.data[j]) < min) { - min = Number(stat.data[j]); - } - } - return { - max : Number(max), - min : Number(min) - }; -}; - -PlotWidget.prototype._renderDygraph = function(parsed, colors, labels) { - this.dygraphObject = new StdDevDyGraph(this.id, { - width : this.width - 20, - height : this.height - 40, - xlabel : "", - }); - - this.dygraphObject.draw(parsed, colors, labels); - -}; - -PlotWidget.prototype.getPanel = function() { - this.panel = Ext.create('Ext.panel.Panel', { - width : this.width, - height : this.height, - margin : this.margin, - tbar : this.getMenu(), - items : [ { - html : "", - id : this.id, - width : this.width, - height : this.height, - padding : 10, - margin : "0 0 0 -30", - border : 0 - } ] - }); - - return this.panel; -}; - -PlotWidget.prototype.getPoint = function(y, error) { - var minus = y - error; - var max = y + error; - - if (this.linear) { - return [ Math.abs(minus), y, Math.abs(max) ]; - } - if ((minus != 0) && (max != 0)) { - return [ Math.log(Math.abs(minus)), Math.log(y), Math.log(Math.abs(max)) ]; - } else { - return [ Math.log(y), Math.log(y), Math.log(y) ]; - } - -}; - -PlotWidget.prototype.getDataPlot = function(frames, subtractions, models, fits, rbms) { - var files = []; - var labels = [ "Intensity" ]; - if (frames != null) { - for (var i = 0; i < frames.length; i++) { - files.push(frames[i].data); - labels.push(frames[i].fileName); - } - } - function splitData(data, column, errorColumn, name){ - var result = [] - for (var j = 0; j < data.length; j++) { - console.log(data[j][column]); - result.push([j,data[j][column],data[j][errorColumn]]);//[0, data[i][column],0]]); - } - files.push(result); - labels.push(name); - } - - if (subtractions != null) { - for (var i = 0; i < subtractions.length; i++) { - /** For subtraction **/ - files.push(subtractions[i].subtraction.data); - labels.push(subtractions[i].subtraction.fileName); - /** For sample average **/ -// files.push(subtractions[i].sampleAvg.data); -// labels.push(subtractions[i].sampleAvg.fileName); - /** For buffer average **/ -// files.push(subtractions[i].bufferAvg.data); -// labels.push(subtractions[i].bufferAvg.fileName); - } - } - - if (models != null) { - for (var i = 0; i < models.length; i++) { - for ( var key in models[i]) { - splitData(models[i][key].fir.data, 1, 2, "Intensity"); - splitData(models[i][key].fir.data, 3, 3, "Fit"); - } - } - } - - if (fits != null) { - for (var i = 0; i < fits.length; i++) { - for ( var key in fits[i]) { - - /** adding fit file to be plotted **/ - if (fits[i][key].fit.data[0].length == 3){ - splitData(fits[i][key].fit.data, 1, 1, "Intensity"); - splitData(fits[i][key].fit.data, 2, 2, "Fit"); - } - - /** s, Iexp(s), err, Ifit(s). **/ - if (fits[i][key].fit.data[0].length == 4){ - splitData(fits[i][key].fit.data, 1, 2, "Intensity"); - splitData(fits[i][key].fit.data, 3, 3, "Fit"); - } - - if (fits[i][key].fit.data[0].length == 5){ - /** X Intensity Fit Error Residues **/ - - splitData(fits[i][key].fit.data, 1, 3, "Intensity"); - splitData(fits[i][key].fit.data, 2, 2, "Fit"); - } - } - } - } - - var dataPoints = []; - if (files.length > 0) { - for (var i = 0; i < files[0].length; i++) { - dataPoints.push([ files[0][i][0], this.getPoint(files[0][i][1], files[0][i][2]) ]); - } - if (files.length > 1) { - for (var i = 1; i < files.length; i++) { - for (var j = 0; j < dataPoints.length; j++) { - if (files[i][j] != null){ - dataPoints[j].push(this.getPoint(files[i][j][1], files[i][j][2])); - } - else{ - dataPoints[j].push([0,0,0]); - } - } - } - } - } - - return { - dataPoints : dataPoints, - labels : labels - } -}; - -PlotWidget.prototype.refresh = function(frames, subtractions, models, fits, rbms, colors) { - - var _this = this; - this.panel.setLoading("Reading Files"); - - var dataAdapter = new BiosaxsDataAdapter(); - dataAdapter.onSuccess.attach(function(sender, data) { - _this.panel.setLoading("Rendering"); - var parsed = _this.getDataPlot(data.frames, data.subtractions, data.models, data.fits, rbms); - _this._renderDygraph(parsed.dataPoints, colors, parsed.labels); - _this.panel.setLoading(false); - }); - dataAdapter.onError.attach(function(sender, data) { - _this.panel.setLoading(false); - }); - dataAdapter.getDataPlot(frames, subtractions, models, fits, rbms); -}; - -PlotWidget.prototype.input = function() { - return DATADOC.getHPLCData(); -}; - - -/** - * Fit form - * - * @witdh - * @height - */ -function FitForm(args) { - this.id = BUI.id(); - this.width = null; - this.height = null; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } - - var _this = this; - - /** Widgets **/ - this.fitGrid = new FitStructureToExperimentDataGrid({ - width : null, - height : 200 - }); - - this.fitGrid.onSelected.attach(function(sender, fits) { - var modelsIdList = []; - for ( var i in fits) { - modelsIdList.push(fits[i].fitStructureToExperimentalDataId); - } - _this._renderPlot(_this.subtractions[0].subtractionId, modelsIdList); -// var adapter = new BiosaxsDataAdapter(); -// adapter.onSuccess.attach(function(sender, data) { -// -// }); -// adapter.getScatteringCurveByFrameIdsList([], [], [], ids); - }); - - - /** Dygraph Widget that plots fir files**/ - this.plotWidget = new PlotWidget({ - width : 745, - height : 300, - margin : "10 0 10 10" - }); -} - -FitForm.prototype._renderPlot = function(subtractionId, modelsIdList) { - /** Trying to plot tje subtraction and the models **/ - try { - var colors = [ "#669900", "#0000FF" ]; - - this.plotWidget.refresh([], [ ], [], modelsIdList, [], colors); - } catch (e) { - console.log(e); - } -}; - -FitForm.prototype._getItems = function() { - var _this = this; - return [ { - xtype : 'label', - forId : 'myFieldId', - text : 'INLINE HELP: To be updated', - margin : '15 0 20 10', - cls : "inline-help" - }, this.fitGrid.getPanel(), this.plotWidget.getPanel() ] - -}; - -FitForm.prototype._getButtons = function() { - return []; -}; - -FitForm.prototype.getPanel = function() { - var _this = this; - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - margin : 10, - border : 1, - defaultType : 'textfield', - items : this._getItems(), - buttons : this._getButtons(), - listeners : { - afterrender : function() { - _this._populate(); - - } - } - }); - return this.panel; -}; - -/** Populates could be call when the DOM is not filled yet **/ -FitForm.prototype._populate = function() { -}; - -/** It populates the form * */ -FitForm.prototype.refresh = function(subtractions) { - this.subtractions = subtractions; - this.fitGrid.refresh(subtractions); -}; - -FitForm.prototype.input = function() { - return {}; -}; - -/** It populates the form **/ -FitForm.prototype.test = function(targetId) { - var macromoleculeForm = new FitForm(); - var panel = macromoleculeForm.getPanel(); - panel.render(targetId); -}; - -/** - * Example form - * - * @witdh - * @height - */ -function RigidBodyModelingResultForm(args) { - this.id = BUI.id(); - this.width = null; - this.height = null; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } - - var _this = this; - /** Widgets **/ - this.rigidModelGrid = new RigidModelGrid({ - width : null, - height : 200 - }); - - this.rigidModelGrid.onSelected.attach(function(sender, fits){ - var ids = []; - for ( var i in fits) { - ids.push(fits[i].fitStructureToExperimentalDataId); - } - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, data){ -// debugger - - }); - - adapter.getScatteringCurveByFrameIdsList([], [], [], ids); - }); - -} - -RigidBodyModelingResultForm.prototype._getItems = function() { - var _this = this; - return [ { - xtype : 'label', - forId : 'myFieldId', - text : 'INLINE HELP: To be updated', - margin : '15 0 20 10', - cls : "inline-help" - }, this.rigidModelGrid.getPanel() ] - -}; - -RigidBodyModelingResultForm.prototype._getButtons = function() { - return []; -}; - -RigidBodyModelingResultForm.prototype.getPanel = function() { - var _this = this; - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - margin : 10, - border : 1, - defaultType : 'textfield', - items : this._getItems(), - buttons : this._getButtons(), - listeners : { - afterrender : function() { - _this._populate(); - - } - } - }); - return this.panel; -}; - -/** Populates could be call when the DOM is not filled yet **/ -RigidBodyModelingResultForm.prototype._populate = function() { -}; - -/** It populates the form * */ -RigidBodyModelingResultForm.prototype.refresh = function(subtractions) { - this.rigidModelGrid.refresh(subtractions); -}; - -RigidBodyModelingResultForm.prototype.input = function() { - return {}; -}; - -/** It populates the form **/ -RigidBodyModelingResultForm.prototype.test = function(targetId) { - var macromoleculeForm = new RigidBodyModelingResultForm(); - var panel = macromoleculeForm.getPanel(); - panel.render(targetId); -}; - -/** - * Example form - * - * @witdh - * @height - */ -function SuperpositionForm(args) { - this.id = BUI.id(); - this.width = null; - this.height = null; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } - - var _this = this; - - /** Widgets **/ - this.superpositionGrid = new SuperpositionGrid({ - width : null, - height : 200 - }); - - this.superpositionGrid.onSelected.attach(function(sender, superpositions) { - var ids = []; - for ( var i in superpositions) { - ids.push(superpositions[i].superpositionId); - } -// _this._renderAbinitio(ids); -// _this.aprioriPDBViewer.refresh(); - _this._renderAligned(ids); - // getAlignedPDBContentBySuperpositionList - }); - - /** PDB viewer **/ -// this.abinitioPDBViewer = new PDBViewer({ -// width : 860 / 2, -// height : 300 / 2, -// margin : 0 -// }); -// -// /** PDB viewer **/ -// this.aprioriPDBViewer = new StructurePDBViewer({ -// width : 860 / 2, -// height : 300 / 2, -// margin : 0 -// }); - - this.alignedPDBViewer = new AlignedSuperpositionPDBViewer({ - width : 860 , - height : 300 - }); - -} - -SuperpositionForm.prototype._renderAligned = function(modelsIdList) { - /** Trying to plot the PDB file **/ - try { - this.alignedPDBViewer.refresh(modelsIdList); - } catch (e) { - console.log(e); - } -}; - -SuperpositionForm.prototype._renderAbinitio = function(modelsIdList) { - /** Trying to plot the PDB file **/ - try { - var viz = []; - for (var i = 0; i < modelsIdList.length; i++) { - viz.push({ - modelId : modelsIdList[i], - color : "0xFF6600", - opacity : 0.8 - }); - } - this.abinitioPDBViewer.refresh(viz); - } catch (e) { - console.log(e); - } -}; - -SuperpositionForm.prototype._getItems = function() { - var _this = this; - return [ { - xtype : 'label', - forId : 'myFieldId', - text : 'INLINE HELP: To be updated', - margin : '15 0 20 10', - cls : "inline-help" - }, this.superpositionGrid.getPanel(), { - xtype : 'container', - layout : 'hbox', - items : [ -// { -// xtype : 'container', -// layout : 'vbox', -// items : [ this.abinitioPDBViewer.getPanel(), this.aprioriPDBViewer.getPanel() -// -// ] -// }, - - this.alignedPDBViewer.getPanel() ] - } ] - -}; - -SuperpositionForm.prototype._getButtons = function() { - return []; -}; - -SuperpositionForm.prototype.getPanel = function() { - var _this = this; - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - margin : 10, - border : 1, - defaultType : 'textfield', - items : this._getItems(), - buttons : this._getButtons(), - listeners : { - afterrender : function() { - _this._populate(); - - } - } - }); - return this.panel; -}; - -/** Populates could be call when the DOM is not filled yet **/ -SuperpositionForm.prototype._populate = function() { -}; - -/** It populates the form * */ -SuperpositionForm.prototype.refresh = function(subtractions) { - this.subtractions = subtractions; - this.superpositionGrid.refresh(subtractions); -}; - -SuperpositionForm.prototype.input = function() { - return {}; -}; - -/** It populates the form **/ -SuperpositionForm.prototype.test = function(targetId) { - var macromoleculeForm = new SuperpositionForm(); - var panel = macromoleculeForm.getPanel(); - panel.render(targetId); -}; - -/** - * Example form - * - * @witdh - * @height - */ -function AssemblyForm(args) { - this.id = BUI.id(); - this.width = 700; - this.height = 500; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } - - this.molarityGrid = new MolarityGrid({height : this.height - 50}); -} - -AssemblyForm.prototype._getItems = function() { - return [ { - xtype : 'label', - forId : 'myFieldId', - text : 'List of previously defined macromolecules present in the assembly. This information will be used for additional cross-checks where possible', - margin : '15 0 20 10', - cls : "inline-help" - }, this.molarityGrid.getPanel() ]; -}; - -AssemblyForm.prototype._getButtons = function() { - return []; -}; - -AssemblyForm.prototype.getPanel = function() { - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - margin : 10, - border : 0, - defaultType : 'textfield', - items : this._getItems(), - buttons : this._getButtons() - }); - return this.panel; -}; - - -/** It populates the form **/ -AssemblyForm.prototype.refresh = function(macromolecule) { - this.macromolecule = macromolecule; - this.molarityGrid.refresh(macromolecule); -}; - -AssemblyForm.prototype.input = function() { - return {}; -}; - - -AssemblyForm.prototype.test = function(targetId) { - var assemblyForm = new AssemblyForm(); - - var panel = assemblyForm.getPanel(); - panel.render(targetId); -}; /** - * Edit the information of a buffer + * Example form * - * #onSaved - * #onRemoveAdditive + * @witdh + * @height */ -function BufferForm() { +function DataReductionForm(args) { + this.id = BUI.id(); + this.width = null; + this.height = null; + + if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } + } + var _this = this; - this.additiveGrid = new AdditiveGrid(); - this.additiveGrid.onRemoveButtonClicked.attach(function(sender, args) { - _this.onRemoveAdditive.notify(args); + /** Widgets **/ + this.plotWidget = new PlotWidget({ + width : 650, + height : 490 }); - this.onSaved = new Event(this); - this.onRemoveAdditive = new Event(this); + /** Selected frames to be displayed **/ + this.selectedItems = { + frames : [], + averages : [], + subtractions : [] + }; + } -BufferForm.prototype.getBuffer = function() { - this.buffer.name = Ext.getCmp("buffer_name").getValue(); - this.buffer.acronym = Ext.getCmp("buffer_acronym").getValue(); - this.buffer.comments = Ext.getCmp("buffer_comments").getValue(); - this.buffer.ph = Ext.getCmp("buffer_ph").getValue(); - this.buffer.composition = Ext.getCmp("buffer_composition").getValue(); - this.buffer.bufferhasadditive3VOs = this.additiveGrid.getAdditives(); - return this.buffer; +DataReductionForm.prototype._parseSelectedItemsToIds = function(selectedArray) { + var ids = []; + if (selectedArray != null) { + for (var i = 0; i < selectedArray.length; i++) { + ids.push(selectedArray[i].id); + } + } + return ids; }; -BufferForm.prototype._getTopPanel = function() { +DataReductionForm.prototype.onSelectionChanged = function(columnName, selected) { + if (selected != null) { + if (columnName == "Frames") { + this.selectedItems.frames = selected; + this.selectedItems.subtractions = []; + } + if (columnName == "Averages") { + this.selectedItems.averages = selected; + } + if (columnName == "Subtractions") { + this.selectedItems.frames = []; + this.selectedItems.subtractions = selected; + } + } + this.plotWidget.refresh(this._parseSelectedItemsToIds(this.selectedItems.frames), this._parseSelectedItemsToIds(this.selectedItems.subtractions)); +}; + +DataReductionForm.prototype._getFramesExtPanel = function(store, columnName, height) { + var _this = this; + + var selModel = Ext.create('Ext.selection.RowModel', { + allowDeselect : true, + mode : 'MULTI', + listeners : { + selectionchange : function(sm, selections) { + var selected = []; + for (var i = 0; i < selections.length; i++) { + selected.push(selections[i].raw); + } + _this.onSelectionChanged(columnName, selected); + } + } + }); + + return Ext.create('Ext.grid.Panel', { + store : store, + margin : 10, + height : height, + width : 200, + selModel : selModel, + columns : [ { + text : columnName, + dataIndex : 'fileName', + flex : 1 + } ], + viewConfig : { + } + }); +}; + +DataReductionForm.prototype._getFramesPanel = function() { + var fields = [ 'fileName', 'type', 'id' ]; + + this.framesStore = Ext.create('Ext.data.Store', { + fields : fields, + sorters : 'fileName' + }); + + this.averagesStore = Ext.create('Ext.data.Store', { + fields : fields + }); + + this.subtractionStore = Ext.create('Ext.data.Store', { + fields : fields + }); + + var gridFrames = this._getFramesExtPanel(this.framesStore, "Frames", 375); + var gridAvgs = this._getFramesExtPanel(this.averagesStore, "Averages", 125); + var subtractionAvgs = this._getFramesExtPanel(this.subtractionStore, "Subtractions", 75); + return { xtype : 'container', - layout : 'hbox', - border : 0, - frame : true, + layout : 'vbox', + items : [ gridFrames, subtractionAvgs ] + }; +}; + +DataReductionForm.prototype._getImageContainer = function(name, help) { + var html = "
" + name + "
" + return { + xtype : 'container', + layout : 'vbox', items : [ { - xtype : 'container', - layout : 'hbox', - items : [ { - xtype : 'container', - flex : 1, - border : false, - layout : 'anchor', - defaultType : 'textfield', - items : [ { - xtype : 'requiredtext', - id : 'buffer_name', - fieldLabel : 'Name', - name : 'name', - width : '200px', - value : this.buffer.name - }, { - xtype : 'requiredtext', - id : 'buffer_acronym', - fieldLabel : 'Acronym', - name : 'acronym', - width : '200px', - value : this.buffer.acronym - } ] - } ] + html : html, + margin : "5 0 0 0", + height : 95, + width : 100 }, { - xtype : 'container', - flex : 1, - layout : 'anchor', - defaultType : 'textfield', - margin : '0 0 0 10', - items : [ { - id : 'buffer_ph', - fieldLabel : 'pH', - name : 'ph', - value : this.buffer.ph, - xtype : 'numberfield', - width : 200, - minValue : 0, - maxValue : 15 - }, { - xtype : 'requiredtext', - id : 'buffer_composition', - fieldLabel : 'Composition', - name : 'composition', - width : 200, - value : this.buffer.composition - } ] + xtype : 'label', + forId : 'myFieldId', + text : help, + margin : '5 0 0 0', + cls : "inline-help" } ] - }; + } }; -BufferForm.prototype.getPanel = function(buffer) { - this.buffer = buffer; - this.panel = Ext.createWidget({ +DataReductionForm.prototype._getItems = function() { + var _this = this; + return [ { xtype : 'container', - layout : 'vbox', - style : { - padding : '10px' - }, - fieldDefaults : { - labelAlign : 'left', - labelWidth : 50 + layout : 'hbox', + items : [ + this._getFramesPanel(), + this.plotWidget.getPanel(), + { + xtype : 'panel', + width : 110, + frame : true, + margin : "10 5 5 5", + border : 0, + layout : 'vbox', + items : [ this._getImageContainer("scattering", "Scattering"), this._getImageContainer("guinier", "Guinier Region"), + this._getImageContainer("kratky", "Kratky Plot"), this._getImageContainer("gnom", "P(r) distribution") ] + } ] + } ] +}; - }, - items : [ this._getTopPanel(), { - id : 'buffer_comments', - xtype : 'textareafield', - name : 'comments', - fieldLabel : 'Comments', - width : '100%', - value : buffer.comments - }, this.additiveGrid.getPanel(buffer) ] +DataReductionForm.prototype._getButtons = function() { + return []; +}; + +DataReductionForm.prototype.getPanel = function() { + var _this = this; + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + border : 0, + items : this._getItems(), + buttons : this._getButtons(), + listeners : { + afterrender : function() { + _this._populate(); + } + } }); return this.panel; }; -BufferForm.prototype.input = function() { - return { - buffer : { - "bufferId" : 422, - "proposalId" : 10, - "safetyLevelId" : null, - "name" : "B1", - "acronym" : "B1", - "ph" : null, - "composition" : null, - "bufferhasadditive3VOs" : [], - "comments" : null +/** Populates could be call when the DOM is not filled yet **/ +DataReductionForm.prototype._populate = function() { +}; + +/** It populates the form * */ +DataReductionForm.prototype.refresh = function(subtractions) { + if (subtractions != null) { + for (var i = 0; i < subtractions.length; i++) { + /** Loading frame grids **/ + var subtraction = subtractions[i]; + var averages = [ { + fileName : BUI.getFileName(subtraction.bufferAverageFilePath), + type : 'bufferAvg', + id : subtraction.subtractionId + }, { + fileName : BUI.getFileName(subtraction.sampleAverageFilePath), + type : 'sampleAvg', + id : subtraction.subtractionId + } + + ]; + this.averagesStore.loadData(averages, true); + this.subtractionStore.loadData([ { + fileName : BUI.getFileName(subtraction.substractedFilePath), + type : 'SUBTRACTION', + id : subtraction.subtractionId + } ], true); + + var frames = []; + /** Buffers **/ + if (subtraction.bufferOneDimensionalFiles != null) { + if (subtraction.bufferOneDimensionalFiles.frametolist3VOs != null) { + for (var j = 0; j < subtraction.bufferOneDimensionalFiles.frametolist3VOs.length; j++) { + var frametolist3VO = subtraction.bufferOneDimensionalFiles.frametolist3VOs[j]; + if (frametolist3VO.frame3VO != null) { + frames.push({ + fileName : BUI.getFileName(frametolist3VO.frame3VO.filePath), + type : 'BUFFER', + id : frametolist3VO.frame3VO.frameId + }); + } + } + } + } + /** Samples **/ + if (subtraction.sampleOneDimensionalFiles != null) { + if (subtraction.sampleOneDimensionalFiles.frametolist3VOs != null) { + for (var j = 0; j < subtraction.sampleOneDimensionalFiles.frametolist3VOs.length; j++) { + var frametolist3VO = subtraction.sampleOneDimensionalFiles.frametolist3VOs[j]; + if (frametolist3VO.frame3VO != null) { + frames.push({ + fileName : BUI.getFileName(frametolist3VO.frame3VO.filePath), + type : 'SAMPLE', + id : frametolist3VO.frame3VO.frameId + }); + } + } + } + } + + this.framesStore.loadData(frames, true); + + /** Loading images **/ + this._displayImage("scattering", subtraction.subtractionId); + this._displayImage("kratky", subtraction.subtractionId); + this._displayImage("guinier", subtraction.subtractionId); + this._displayImage("gnom", subtraction.subtractionId); } - }; + } }; -BufferForm.prototype.test = function(targetId) { - var bufferForm = new BufferForm(); - var panel = bufferForm.getPanel(bufferForm.input().buffer); +DataReductionForm.prototype._displayImage = function(name, subtractionId) { + var url = BUI.getURL() + '&type=' + name + '&subtractionId=' + subtractionId; + var event = "OnClick= window.open('" + url + "')"; + document.getElementById(this.id + "_" + name).innerHTML = ''; +}; + +DataReductionForm.prototype.input = function() { + return {}; +}; + +/** It populates the form **/ +DataReductionForm.prototype.test = function(targetId) { + var macromoleculeForm = new DataReductionForm(); + var panel = macromoleculeForm.getPanel(); panel.render(targetId); }; - -/** - * @showTitle - * - * #onSaved - * #onAddPlates - * #onRemovePlates - **/ -function CaseForm(args) { - this.width = 700; - this.showTitle = true; + +function PlotWidget(args) { + this.width = 600; + this.height = 600; + this.id = BUI.id(); + + this.linear = false; + + this.margin = "10 0 0 0"; + /** for each stat the max and minimum value when it is scaled in order to show correctly in the legend **/ + this.ranges = {}; if (args != null) { - if (args.showTitle != null) { - this.showTitle = args.showTitle; + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } + if (args.margin != null) { + this.margin = args.margin; } } - var _this = this; - this.stockSolutionGrid = new StockSolutionGrid({ - width : this.width - 10, - minHeight : 300, - height : 300, - tbar : true, - showTitle : true, - isPackedVisible : false, - btnAddExisting : true, - btnRemoveVisible : false, - btnUnpackVisible : true - }); +} - /** When selecting existing stock solutions **/ - this.stockSolutionGrid.onStockSolutionSelected.attach(function(sender, stockSolutions) { - if (stockSolutions != null) { - for ( var i = 0; i < stockSolutions.length; i++) { - _this.saveStockSolution(stockSolutions[i]); - } +PlotWidget.prototype.getMenu = function() { + var _this = this; + /** Actions buttons **/ + var actions = []; + actions.push("->"); + actions.push({ + text : "Export as Image", + scope : this, + icon : '../images/save.gif', + handler : function(item, pressed) { + var largeImage = document.createElement("img"); + largeImage.style.display = 'block'; + largeImage.style.width = 200 + "px"; + largeImage.style.height = 200 + "px"; + largeImage.setAttribute('src', Dygraph.Export.asCanvas(this.dygraphObject.dygraph).toDataURL()); + window.open(Dygraph.Export.asCanvas(this.dygraphObject.dygraph).toDataURL(), 'Image', ''); } }); - /** it can be because it has been added a new one or removed **/ - this.stockSolutionGrid.onProposalChanged.attach(function(sender, stockSolution) { - if (stockSolution != null) { - _this.saveStockSolution(stockSolution); - } else { - BIOSAXS.proposal.onInitialized.attach(function() { - _this.stockSolutionGrid.refresh(BIOSAXS.proposal.getStockSolutionsByDewarId(_this.dewar.dewarId)); + return actions; +}; - _this.stockSolutionGrid.grid.setLoading(false); - }); - BIOSAXS.proposal.init(); +/** Looks for the maximum value and then divide everything but that value **/ +PlotWidget.prototype.scaledData = function(data) { + for (var i = 0; i < data.length; i++) { + var values = this.getMaxAndMinValue(data[i]); + data[i] = this.divideValuesByMax(data[i], values.max); + this.ranges[data[i].label] = values; + } + return data; +}; + +/** Given a stat float[] and a max number it will divide each value by max **/ +PlotWidget.prototype.divideValuesByMax = function(stat, max) { + for (var j = 0; j < stat.data.length; j++) { + if (max != 0) { + stat.data[j] = Number(stat.data[j]) / max; + stat.std[j] = Number(stat.std[j]) / max; + } + } + return stat; +}; +/** returns max value of a stat **/ +PlotWidget.prototype.getMaxAndMinValue = function(stat) { + var max = 0; + var min = stat.data[0]; + for (var j = 0; j < stat.data.length; j++) { + if (Number(stat.data[j]) > max) { + max = Number(stat.data[j]); + } + if (Number(stat.std[j]) > max) { + max = Number(stat.std[j]); + } + if (Number(stat.data[j]) < min) { + min = Number(stat.data[j]); } + } + return { + max : Number(max), + min : Number(min) + }; +}; +PlotWidget.prototype._renderDygraph = function(parsed, colors, labels) { + this.dygraphObject = new StdDevDyGraph(this.id, { + width : this.width - 20, + height : this.height - 40, + xlabel : "", }); - this.onSaved = new Event(this); - this.onAddPlates = new Event(this); - this.onRemovePlates = new Event(this); -} + this.dygraphObject.draw(parsed, colors, labels); -CaseForm.prototype.saveStockSolution = function(stockSolution) { - var _this = this; - var adapter = new BiosaxsDataAdapter(); - this.stockSolutionGrid.grid.setLoading("ISPyB: setting case to Stock solution"); - adapter.onSuccess.attach(function(sender, stockSolution) { - BIOSAXS.proposal.onInitialized.attach(function() { - _this.stockSolutionGrid.refresh(BIOSAXS.proposal.getStockSolutionsByDewarId(_this.dewar.dewarId)); - _this.stockSolutionGrid.grid.setLoading(false); - }); - BIOSAXS.proposal.init(); - }); - adapter.onError.attach(function(sender, data) { - _this.stockSolutionGrid.grid.setLoading(false); - BUI.showError(data); - }); - stockSolution.boxId = _this.dewar.dewarId; - adapter.saveStockSolution(stockSolution); }; -CaseForm.prototype.fillStores = function() { - var _this = this; - this.panel.setLoading("Loading Labcontacts from database"); - - var proposal = BUI.getProposal(); - proposal.onDataRetrieved.attach(function(sender, data) { - _this.labContactForSendingStore.loadData(data, false); - _this.labContactForReturnStore.loadData(data, false); - _this.panel.setLoading(false); +PlotWidget.prototype.getPanel = function() { + this.panel = Ext.create('Ext.panel.Panel', { + width : this.width, + height : this.height, + margin : this.margin, + tbar : this.getMenu(), + items : [ { + html : "", + id : this.id, + width : this.width, + height : this.height, + padding : 10, + margin : "0 0 0 -30", + border : 0 + } ] }); - proposal.getLabContactsByProposalId(); - -}; -CaseForm.prototype.refresh = function(dewar) { - this.setDewar(dewar); - this.stockSolutionGrid.refresh(BIOSAXS.proposal.getStockSolutionsByDewarId(dewar.dewarId)); + return this.panel; }; -CaseForm.prototype.getDewar = function() { - this.dewar.code = Ext.getCmp("dewar_code").getValue(); - this.dewar.comments = Ext.getCmp("dewar_comments").getValue(); - this.dewar.trackingNumberFromSynchrotron = Ext.getCmp("dewar_trackingNumberFromSynchrotron").getValue(); - this.dewar.trackingNumberToSynchrotron = Ext.getCmp("dewar_trackingNumberToSynchrotron").getValue(); - this.dewar.transportValue = Ext.getCmp("dewar_transportValue").getValue(); - this.dewar.storageLocation = Ext.getCmp("dewar_storageLocation").getValue(); - this.dewar.firstExperimentId = this.macromoleculeCombo.getValue(); - return this.dewar; -}; +PlotWidget.prototype.getPoint = function(y, error) { + var minus = y - error; + var max = y + error; -CaseForm.prototype.setDewar = function(dewar) { - this.dewar = dewar; - Ext.getCmp("dewar_code").setValue(this.dewar.code); - Ext.getCmp("dewar_dewarStatus").setText(new String(this.dewar.dewarStatus).toUpperCase()); - Ext.getCmp("dewar_comments").setValue(this.dewar.comments); - Ext.getCmp("dewar_trackingNumberFromSynchrotron").setValue(this.dewar.trackingNumberFromSynchrotron); - Ext.getCmp("dewar_trackingNumberToSynchrotron").setValue(this.dewar.trackingNumberToSynchrotron); - Ext.getCmp("dewar_transportValue").setValue(this.dewar.transportValue); - Ext.getCmp("dewar_storageLocation").setValue(this.dewar.storageLocation); - if (dewar.sessionVO != null) { - this.macromoleculeCombo.setValue(dewar.sessionVO.sessionId); + if (this.linear) { + return [ Math.abs(minus), y, Math.abs(max) ]; + } + if ((minus != 0) && (max != 0)) { + return [ Math.log(Math.abs(minus)), Math.log(y), Math.log(Math.abs(max)) ]; + } else { + return [ Math.log(y), Math.log(y), Math.log(y) ]; } -}; -CaseForm.prototype.getSessionCombo = function() { - this.macromoleculeCombo = BIOSAXS_COMBOMANAGER.getComboSessions(BIOSAXS.proposal.getSessions(), { - labelWidth : 100, - margin : '5 0 00 0', - width : 250 - }); - return this.macromoleculeCombo; }; -CaseForm.prototype.getInformationPanel = function() { - if (this.panel == null) { - this.informationPanel = Ext.create('Ext.form.Panel', { - width : this.width - 10, - border : 0, - items : [ { - xtype : 'container', - margin : "2 2 2 2", - collapsible : false, - defaultType : 'textfield', - layout : 'anchor', - items : [ { - xtype : 'container', - layout : 'hbox', - items : [ { - xtype : 'requiredtext', - fieldLabel : 'Code', - allowBlank : false, - name : 'code', - id : 'dewar_code', - anchor : '50%' - }, { - xtype : 'label', - margin : '0 0 0 20', - readOnly : true, - id : 'dewar_dewarStatus', - anchor : '50%' - } ] - }, this.getSessionCombo(), { - margin : '5 0 0 0', - xtype : 'textareafield', - name : 'comments', - id : 'dewar_comments', - width : this.width - 50, - fieldLabel : 'Comments' - } ] - }, { - xtype : 'fieldset', - title : 'Courier Accounts Details for Return', - collapsible : false, - layout : 'anchor', - defaults : { - anchor : '100%' - }, - items : [ { - xtype : 'container', - layout : 'hbox', - items : [ { - xtype : 'textfield', - labelWidth : 200, - width : 280, - fieldLabel : 'Track Number From Synchrotron', - id : 'dewar_trackingNumberFromSynchrotron' - }, { - xtype : 'numberfield', - width : 190, - labelWidth : 110, - margin : '0 0 0 30', - fieldLabel : 'Transport Value', - id : 'dewar_transportValue' +PlotWidget.prototype.getDataPlot = function(frames, subtractions, models, fits, rbms) { + var files = []; + var labels = [ "Intensity" ]; + if (frames != null) { + for (var i = 0; i < frames.length; i++) { + files.push(frames[i].data); + labels.push(frames[i].fileName); + } + } + function splitData(data, column, errorColumn, name){ + var result = [] + for (var j = 0; j < data.length; j++) { + console.log(data[j][column]); + result.push([j,data[j][column],data[j][errorColumn]]);//[0, data[i][column],0]]); + } + files.push(result); + labels.push(name); + } + + if (subtractions != null) { + for (var i = 0; i < subtractions.length; i++) { + /** For subtraction **/ + files.push(subtractions[i].subtraction.data); + labels.push(subtractions[i].subtraction.fileName); + /** For sample average **/ +// files.push(subtractions[i].sampleAvg.data); +// labels.push(subtractions[i].sampleAvg.fileName); + /** For buffer average **/ +// files.push(subtractions[i].bufferAvg.data); +// labels.push(subtractions[i].bufferAvg.fileName); + } + } + + if (models != null) { + for (var i = 0; i < models.length; i++) { + for ( var key in models[i]) { + splitData(models[i][key].fir.data, 1, 2, "Intensity"); + splitData(models[i][key].fir.data, 3, 3, "Fit"); + } + } + } + + if (fits != null) { + for (var i = 0; i < fits.length; i++) { + for ( var key in fits[i]) { + + /** adding fit file to be plotted **/ + if (fits[i][key].fit.data[0].length == 3){ + splitData(fits[i][key].fit.data, 1, 1, "Intensity"); + splitData(fits[i][key].fit.data, 2, 2, "Fit"); + } + + /** s, Iexp(s), err, Ifit(s). **/ + if (fits[i][key].fit.data[0].length == 4){ + splitData(fits[i][key].fit.data, 1, 2, "Intensity"); + splitData(fits[i][key].fit.data, 3, 3, "Fit"); + } + + if (fits[i][key].fit.data[0].length == 5){ + /** X Intensity Fit Error Residues **/ + + splitData(fits[i][key].fit.data, 1, 3, "Intensity"); + splitData(fits[i][key].fit.data, 2, 2, "Fit"); + } + } + } + } + + var dataPoints = []; + if (files.length > 0) { + for (var i = 0; i < files[0].length; i++) { + dataPoints.push([ files[0][i][0], this.getPoint(files[0][i][1], files[0][i][2]) ]); + } + if (files.length > 1) { + for (var i = 1; i < files.length; i++) { + for (var j = 0; j < dataPoints.length; j++) { + if (files[i][j] != null){ + dataPoints[j].push(this.getPoint(files[i][j][1], files[i][j][2])); } - - ] - }, { - xtype : 'container', - layout : 'hbox', - margin : '10 0 0 0', - items : [ - - { - xtype : 'textfield', - labelWidth : 200, - width : 280, - fieldLabel : 'Track Number To Synchrotron', - id : 'dewar_trackingNumberToSynchrotron' - }, { - xtype : 'textfield', - margin : '0 0 0 30', - width : 190, - labelWidth : 110, - fieldLabel : 'Storage Location', - id : 'dewar_storageLocation' + else{ + dataPoints[j].push([0,0,0]); } + } + } + } + } - ] - } ] - } ] - }); + return { + dataPoints : dataPoints, + labels : labels } +}; - return this.informationPanel; +PlotWidget.prototype.refresh = function(frames, subtractions, models, fits, rbms, colors) { + + var _this = this; + this.panel.setLoading("Reading Files"); + + var dataAdapter = new BiosaxsDataAdapter(); + dataAdapter.onSuccess.attach(function(sender, data) { + _this.panel.setLoading("Rendering"); + var parsed = _this.getDataPlot(data.frames, data.subtractions, data.models, data.fits, rbms); + _this._renderDygraph(parsed.dataPoints, colors, parsed.labels); + _this.panel.setLoading(false); + }); + dataAdapter.onError.attach(function(sender, data) { + _this.panel.setLoading(false); + }); + dataAdapter.getDataPlot(frames, subtractions, models, fits, rbms); }; -CaseForm.prototype.getPanel = function(dewar) { - this.dewar = dewar; - this.panel = Ext.createWidget({ - xtype : 'container', - layout : 'vbox', - width : this.width, - border : 0, - items : [ { - items : { - xtype : "container", - layout : "vbox", - margin : "5 5 5 5", - items : [ this.getInformationPanel(dewar), this.stockSolutionGrid.getPanel() ] +PlotWidget.prototype.input = function() { + return DATADOC.getHPLCData(); +}; - } - } ] + +/** + * Fit form + * + * @witdh + * @height + */ +function FitForm(args) { + this.id = BUI.id(); + this.width = null; + this.height = null; + + if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } + } + + var _this = this; + + /** Widgets **/ + this.fitGrid = new FitStructureToExperimentDataGrid({ + width : null, + height : 200 }); - this.refresh(dewar); - return this.panel; + this.fitGrid.onSelected.attach(function(sender, fits) { + var modelsIdList = []; + for ( var i in fits) { + modelsIdList.push(fits[i].fitStructureToExperimentalDataId); + } + _this._renderPlot(_this.subtractions[0].subtractionId, modelsIdList); +// var adapter = new BiosaxsDataAdapter(); +// adapter.onSuccess.attach(function(sender, data) { +// +// }); +// adapter.getScatteringCurveByFrameIdsList([], [], [], ids); + }); + + + /** Dygraph Widget that plots fir files**/ + this.plotWidget = new PlotWidget({ + width : 745, + height : 300, + margin : "10 0 10 10" + }); +} +FitForm.prototype._renderPlot = function(subtractionId, modelsIdList) { + /** Trying to plot tje subtraction and the models **/ + try { + var colors = [ "#669900", "#0000FF" ]; + + this.plotWidget.refresh([], [ ], [], modelsIdList, [], colors); + } catch (e) { + console.log(e); + } }; -CaseForm.prototype.input = function() { - return { - dewar : { - "dewarId" : 305861, - "code" : "ESRF-TEST", - "comments" : "comments", - "storageLocation" : "FRIDGE", - "dewarStatus" : "opened", - "timeStamp" : null, - "isStorageDewar" : null, - "barCode" : "ESRF305861", - "customsValue" : null, - "transportValue" : null, - "trackingNumberToSynchrotron" : "3333", - "trackingNumberFromSynchrotron" : "224466", - "type" : "Dewar", - "sessionVO" : { - "sessionId" : 31697, - "expSessionPk" : null, - "projectCode" : null, - "startDate" : "2012 07 21", - "endDate" : "2012 07 23", - "beamlineName" : "BM29", - "scheduled" : 1, - "nbShifts" : 2, - "comments" : null, - "beamlineOperator" : "PERNOT P", - "usedFlag" : null, - "sessionTitle" : null, - "structureDeterminations" : null, - "dewarTransport" : null, - "databackupFrance" : null, - "databackupEurope" : null, - "visit_number" : null, - "operatorSiteNumber" : "14061", - "timeStamp" : "2012 04 25" +FitForm.prototype._getItems = function() { + var _this = this; + return [ { + xtype : 'label', + forId : 'myFieldId', + text : 'INLINE HELP: To be updated', + margin : '15 0 20 10', + cls : "inline-help" + }, this.fitGrid.getPanel(), this.plotWidget.getPanel() ] + +}; + +FitForm.prototype._getButtons = function() { + return []; +}; + +FitForm.prototype.getPanel = function() { + var _this = this; + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + margin : 10, + border : 1, + defaultType : 'textfield', + items : this._getItems(), + buttons : this._getButtons(), + listeners : { + afterrender : function() { + _this._populate(); + } - }, - proposal : { - "assemblies" : [], - "sessions" : [ { - "sessionId" : 31697, - "expSessionPk" : null, - "projectCode" : null, - "startDate" : "2012 07 21", - "endDate" : "2012 07 23", - "beamlineName" : "BM29", - "scheduled" : 1, - "nbShifts" : 2, - "comments" : null, - "beamlineOperator" : "PERNOT P", - "usedFlag" : null, - "sessionTitle" : null, - "structureDeterminations" : null, - "dewarTransport" : null, - "databackupFrance" : null, - "databackupEurope" : null, - "visit_number" : null, - "operatorSiteNumber" : "14061", - "timeStamp" : "2012 04 25" - } ], - "labcontacts" : [ { - "labContactId" : 787, - "personVO" : { - "personId" : 304252, - "personUUID" : null, - "familyName" : "KIM", - "givenName" : "Henry", - "title" : null, - "emailAddress" : "henry-sung.kim@ibs.fr", - "phoneNumber" : "", - "login" : "", - "passwd" : "", - "faxNumber" : "" - }, - "cardName" : "KIM-Institut de Bio", - "defaultCourrierCompany" : "22", - "courierAccount" : "", - "billingReference" : "", - "dewarAvgCustomsValue" : 0, - "dewarAvgTransportValue" : 0 - } ], - "buffers" : [ { - "bufferId" : 811, - "proposalId" : 3124, - "safetyLevelId" : null, - "name" : "EDTA", - "acronym" : "EDTA", - "ph" : null, - "composition" : "", - "bufferhasadditive3VOs" : [], - "comments" : "" - }, { - "bufferId" : 810, - "proposalId" : 3124, - "safetyLevelId" : null, - "name" : "HEPES", - "acronym" : "HEPES", - "ph" : null, - "composition" : "", - "bufferhasadditive3VOs" : [], - "comments" : "" - } ], - "shippings" : [ { - "shippingId" : 304107, - "shippingName" : "TEST", - "deliveryAgentAgentName" : null, - "deliveryAgentShippingDate" : null, - "deliveryAgentDeliveryDate" : null, - "deliveryAgentAgentCode" : null, - "deliveryAgentFlightCode" : null, - "shippingStatus" : "opened", - "timeStamp" : "2013 09 25", - "laboratoryId" : null, - "isStorageShipping" : null, - "creationDate" : "2013 09 25", - "comments" : "test", - "sendingLabContactVO" : { - "labContactId" : 787, - "personVO" : { - "personId" : 304252, - "personUUID" : null, - "familyName" : "KIM", - "givenName" : "Henry", - "title" : null, - "emailAddress" : "henry-sung.kim@ibs.fr", - "phoneNumber" : "", - "login" : "", - "passwd" : "", - "faxNumber" : "" - }, - "cardName" : "KIM-Institut de Bio", - "defaultCourrierCompany" : "22", - "courierAccount" : "", - "billingReference" : "", - "dewarAvgCustomsValue" : 0, - "dewarAvgTransportValue" : 0 - }, - "returnLabContactVO" : { - "labContactId" : 787, - "personVO" : { - "personId" : 304252, - "personUUID" : null, - "familyName" : "KIM", - "givenName" : "Henry", - "title" : null, - "emailAddress" : "henry-sung.kim@ibs.fr", - "phoneNumber" : "", - "login" : "", - "passwd" : "", - "faxNumber" : "" - }, - "cardName" : "KIM-Institut de Bio", - "defaultCourrierCompany" : "22", - "courierAccount" : "", - "billingReference" : "", - "dewarAvgCustomsValue" : 0, - "dewarAvgTransportValue" : 0 - }, - "returnCourier" : null, - "dateOfShippingToUser" : null, - "shippingType" : "DewarTracking", - "dewarVOs" : [ { - "dewarId" : 305861, - "code" : "ESRF-TEST", - "comments" : "comments", - "storageLocation" : "FRIDGE", - "dewarStatus" : "opened", - "timeStamp" : null, - "isStorageDewar" : null, - "barCode" : "ESRF305861", - "customsValue" : null, - "transportValue" : null, - "trackingNumberToSynchrotron" : "3333", - "trackingNumberFromSynchrotron" : "224466", - "type" : "Dewar", - "sessionVO" : { - "sessionId" : 31697, - "expSessionPk" : null, - "projectCode" : null, - "startDate" : "2012 07 21", - "endDate" : "2012 07 23", - "beamlineName" : "BM29", - "scheduled" : 1, - "nbShifts" : 2, - "comments" : null, - "beamlineOperator" : "PERNOT P", - "usedFlag" : null, - "sessionTitle" : null, - "structureDeterminations" : null, - "dewarTransport" : null, - "databackupFrance" : null, - "databackupEurope" : null, - "visit_number" : null, - "operatorSiteNumber" : "14061", - "timeStamp" : "2012 04 25" - } - } ] - } ], - "macromolecules" : [ { - "macromoleculeId" : 5933, - "safetylevelId" : null, - "proposalId" : 3124, - "name" : "A", - "acronym" : "A", - "molecularMass" : "", - "extintionCoefficient" : "", - "sequence" : null, - "creationDate" : null, - "comments" : "", - "macromoleculeregion3VOs" : [], - "stoichiometry3VOsForHostMacromoleculeId" : [], - "structure3VOs" : [] - } ], - "stockSolutions" : [ { - "stockSolutionId" : 6, - "proposalId" : 3124, - "macromoleculeId" : 5933, - "bufferId" : 811, - "instructionSet3VO" : null, - "boxId" : 305861, - "storageTemperature" : "20", - "volume" : "300", - "concentration" : "1.2", - "comments" : "Buffer EDTA with A", - "name" : "A_EDTA_1.2", - "samples" : [] - } ] } + }); + return this.panel; +}; - }; +/** Populates could be call when the DOM is not filled yet **/ +FitForm.prototype._populate = function() { }; -CaseForm.prototype.test = function(targetId) { - var caseForm = new CaseForm(); - BIOSAXS.proposal = new Proposal(caseForm.input().proposal); - var panel = caseForm.getPanel(caseForm.input().dewar); - panel.render(targetId); +/** It populates the form * */ +FitForm.prototype.refresh = function(subtractions) { + this.subtractions = subtractions; + this.fitGrid.refresh(subtractions); +}; + +FitForm.prototype.input = function() { + return {}; +}; + +/** It populates the form **/ +FitForm.prototype.test = function(targetId) { + var macromoleculeForm = new FitForm(); + var panel = macromoleculeForm.getPanel(); + panel.render(targetId); }; -/** - * Example form - * - * @witdh - * @height - */ -function ExampleForm(args) { - this.id = BUI.id(); - this.width = 700; - this.height = 500; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } -} - -ExampleForm.prototype._getItems = function() { - return [{ - fieldLabel : 'First Name', - name : 'first', - allowBlank : false - }, { - fieldLabel : 'Last Name', - name : 'last', - allowBlank : false - } ]; -}; - -ExampleForm.prototype._getItems = function() { - return [ ]; -}; - -ExampleForm.prototype._getButtons = function() { - return [ ]; -}; - -ExampleForm.prototype.getPanel = function() { - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - margin : 10, - border : 1, - defaultType : 'textfield', - items : this._getItems(), - buttons : this._getButtons() - }); - return this.panel; -}; - -/** It populates the form **/ -ExampleForm.prototype.refresh = function(macromolecule) { -}; - -function ExperimentForm(args) { +/** + * Example form + * + * @witdh + * @height + */ +function RigidBodyModelingResultForm(args) { this.id = BUI.id(); + this.width = null; + this.height = null; if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } } - this.onSaved = new Event(this); -} - -ExperimentForm.prototype._getItems = function(experiment) { - this.experiment = experiment; - var typeCombo = Ext.create('Ext.form.ComboBox', { - id : this.id + 'type', - fieldLabel : 'Type', - store : [ "STATIC", "CALIBRATION", "HPLC" ], - queryMode : 'local', - labelWidth : 120, - displayField : 'name', - valueField : 'name', - value : experiment.json.type, - disabled : (experiment.json.type == 'TEMPLATE') + var _this = this; + /** Widgets **/ + this.rigidModelGrid = new RigidModelGrid({ + width : null, + height : 200 }); - var items = []; - - - if (experiment.json.type == "HPLC" ){ - var typeMacromolecule = BIOSAXS_COMBOMANAGER.getComboMacromoleculeByMacromolecules(BIOSAXS.proposal.getMacromolecules(), {labelWidth : 120, width: "120px"}); - if (experiment.getHPLCMacromolecule() != null){ - typeMacromolecule.setValue(experiment.getHPLCMacromolecule().macromoleculeId); - items.push(typeMacromolecule); + this.rigidModelGrid.onSelected.attach(function(sender, fits){ + var ids = []; + for ( var i in fits) { + ids.push(fits[i].fitStructureToExperimentalDataId); } - } - - - items.push(typeCombo, { - id : this.id + 'name', - xtype : 'textfield', - fieldLabel : 'Name', - labelWidth : 120, - width : '100%', - value : experiment.json.name - }, { - id : this.id + 'comments', - xtype : 'textareafield', - name : 'comments', - fieldLabel : 'Comments', - labelWidth : 120, - height : 120, - width : '100%', - value : experiment.json.comments + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, data){ +// debugger + + }); + + adapter.getScatteringCurveByFrameIdsList([], [], [], ids); }); - return items; + +} + +RigidBodyModelingResultForm.prototype._getItems = function() { + var _this = this; + return [ { + xtype : 'label', + forId : 'myFieldId', + text : 'INLINE HELP: To be updated', + margin : '15 0 20 10', + cls : "inline-help" + }, this.rigidModelGrid.getPanel() ] + }; -ExperimentForm.prototype.getPanel = function(experiment) { + +RigidBodyModelingResultForm.prototype._getButtons = function() { + return []; +}; + +RigidBodyModelingResultForm.prototype.getPanel = function() { var _this = this; - - this.panel = Ext.createWidget({ - xtype : 'container', - layout : 'vbox', - border : 0, - style : { - padding : '10px' - }, - fieldDefaults : { - labelAlign : 'left', - labelWidth : 50 - }, - items : this._getItems(experiment) + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + margin : 10, + border : 1, + defaultType : 'textfield', + items : this._getItems(), + buttons : this._getButtons(), + listeners : { + afterrender : function() { + _this._populate(); + + } + } }); return this.panel; }; -ExperimentForm.prototype.input = function() { - return new ExperimentHeaderForm().input(); +/** Populates could be call when the DOM is not filled yet **/ +RigidBodyModelingResultForm.prototype._populate = function() { }; -ExperimentForm.prototype.test = function(targetId) { - var experimentForm = new ExperimentForm(); - var panel = experimentForm.getPanel(new Experiment(experimentForm.input().experiment)); +/** It populates the form * */ +RigidBodyModelingResultForm.prototype.refresh = function(subtractions) { + this.rigidModelGrid.refresh(subtractions); +}; + +RigidBodyModelingResultForm.prototype.input = function() { + return {}; +}; + +/** It populates the form **/ +RigidBodyModelingResultForm.prototype.test = function(targetId) { + var macromoleculeForm = new RigidBodyModelingResultForm(); + var panel = macromoleculeForm.getPanel(); panel.render(targetId); }; /** - * Shows the header for the experiments changing the color and parameters depending on experiment type + * Example form * + * @witdh + * @height */ -function ExperimentHeaderForm(args) { +function SuperpositionForm(args) { this.id = BUI.id(); - this.backgroundColor = '#FFFFFF'; -} + this.width = null; + this.height = null; -ExperimentHeaderForm.prototype.getHTMLSource = function(experiment) { - var html = BUI.createFormLabel("Name :", experiment.json.name, 75, 400, this.backgroundColor); - if (experiment.json.type == "HPLC") { - if (experiment.getHPLCMacromolecule() != null){ - html = html + BUI.createFormLabel("Molecule :", experiment.getHPLCMacromolecule().acronym, 75, 400, this.backgroundColor); + if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; } } - else{ - html = html + BUI.createFormLabel("Type :", experiment.json.type, 75, 400, this.backgroundColor); - } - - html = html + BUI.createFormLabel("Date :", experiment.json.creationDate, 75, 400, this.backgroundColor); - return html; -}; -ExperimentHeaderForm.prototype.getHTMLDownload = function(experiment) { - var bgcolor = "background-color:" + this.backgroundColor + ";"; - var html = "
"; - if ((experiment.json.type == "CALIBATION") || (experiment.json.type == "STATIC")) { - html = html + " Download Source File
"; - html = html - + ""; - } - if (experiment.json.type == "TEMPLATE") { - html = html - + " Download Source File"; - } + var _this = this; - if (experiment.json.type == "HPLC") { - html = html + " Download h5 File"; - } + /** Widgets **/ + this.superpositionGrid = new SuperpositionGrid({ + width : null, + height : 200 + }); - return html; -}; + this.superpositionGrid.onSelected.attach(function(sender, superpositions) { + var ids = []; + for ( var i in superpositions) { + ids.push(superpositions[i].superpositionId); + } +// _this._renderAbinitio(ids); +// _this.aprioriPDBViewer.refresh(); + _this._renderAligned(ids); + // getAlignedPDBContentBySuperpositionList + }); -ExperimentHeaderForm.prototype.getTopPanel = function(experiment) { - return { - xtype : 'container', - layout : 'hbox', - items : [ { - margin : "0 0 0 0", - width : 475, - border : 0, - html : this.getHTMLSource(experiment) - }, { - margin : "0 0 0 0", - width : 475, - border : 0, - html : this.getHTMLDownload(experiment) - } ] - }; + /** PDB viewer **/ +// this.abinitioPDBViewer = new PDBViewer({ +// width : 860 / 2, +// height : 300 / 2, +// margin : 0 +// }); +// +// /** PDB viewer **/ +// this.aprioriPDBViewer = new StructurePDBViewer({ +// width : 860 / 2, +// height : 300 / 2, +// margin : 0 +// }); + + this.alignedPDBViewer = new AlignedSuperpositionPDBViewer({ + width : 860 , + height : 300 + }); + +} + +SuperpositionForm.prototype._renderAligned = function(modelsIdList) { + /** Trying to plot the PDB file **/ + try { + this.alignedPDBViewer.refresh(modelsIdList); + } catch (e) { + console.log(e); + } }; -ExperimentHeaderForm.prototype.getButton = function(experiment) { - var _this = this; - return Ext.create('Ext.Button', { - text : 'EDIT', - minWidth : '100', - margin : '10 0 0 30', - handler : function() { - var experimentWindow = new ExperimentWindow(); - experimentWindow.onSaved.attach(function(sender, data) { - _this.experiment.json.name = data.name; - _this.experiment.json.type = data.type; - _this.experiment.json.comments = data.comments; - _this.panel.remove(_this.panel.items.items[0]); - _this.panel.remove(_this.panel.items.items[0]); - _this.panel.insert(_this.getTopPanel(_this.experiment)); - _this.panel.insert(_this.getBottomPanel(_this.experiment)); +SuperpositionForm.prototype._renderAbinitio = function(modelsIdList) { + /** Trying to plot the PDB file **/ + try { + var viz = []; + for (var i = 0; i < modelsIdList.length; i++) { + viz.push({ + modelId : modelsIdList[i], + color : "0xFF6600", + opacity : 0.8 }); - experimentWindow.show(experiment); } - }); + this.abinitioPDBViewer.refresh(viz); + } catch (e) { + console.log(e); + } }; -ExperimentHeaderForm.prototype.getBottomPanel = function(experiment) { - return { +SuperpositionForm.prototype._getItems = function() { + var _this = this; + return [ { + xtype : 'label', + forId : 'myFieldId', + text : 'INLINE HELP: To be updated', + margin : '15 0 20 10', + cls : "inline-help" + }, this.superpositionGrid.getPanel(), { xtype : 'container', layout : 'hbox', - margin : '10 0 0 0', - items : [ this.getComments(experiment), this.getButton(experiment) ] - }; + items : [ +// { +// xtype : 'container', +// layout : 'vbox', +// items : [ this.abinitioPDBViewer.getPanel(), this.aprioriPDBViewer.getPanel() +// +// ] +// }, + + this.alignedPDBViewer.getPanel() ] + } ] + }; -ExperimentHeaderForm.prototype.getComments = function(experiment) { - return { - xtype : 'textareafield', - labelStyle : 'font-weight: bold;', - name : 'comments', - fieldLabel : 'Comments', - labelWidth : 70, - height : 40, - minWidth : '450', - readOnly : true, - value : experiment.json.comments - }; +SuperpositionForm.prototype._getButtons = function() { + return []; }; -ExperimentHeaderForm.prototype.getPanel = function(experiment) { - this.experiment = experiment; - - if (experiment.json.type == 'CALIBRATION') { - this.backgroundColor = '#EFFBFB'; - } - if (experiment.json.type == 'TEMPLATE') { - this.backgroundColor = '#E0F8E6'; - } +SuperpositionForm.prototype.getPanel = function() { + var _this = this; + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + margin : 10, + border : 1, + defaultType : 'textfield', + items : this._getItems(), + buttons : this._getButtons(), + listeners : { + afterrender : function() { + _this._populate(); - this.panel = Ext.create('Ext.container.Container', { - frame : false, - layout : 'vbox', - padding : 5, - bodyPadding : '5 5 0 0', - width : 890, - margin : '0 0 10 0', - height : 120, - style : { - borderColor : '#99bce8', - borderStyle : 'solid', - borderWidth : '1px', - 'background-color' : this.backgroundColor - }, - fieldDefaults : { - msgTarget : 'side', - labelWidth : 100 - }, - items : [ this.getTopPanel(experiment), this.getBottomPanel(experiment) ] + } + } }); return this.panel; }; -ExperimentHeaderForm.prototype.input = function() { - return { - experiment : DATADOC.getExperiment_10() - }; +/** Populates could be call when the DOM is not filled yet **/ +SuperpositionForm.prototype._populate = function() { }; -ExperimentHeaderForm.prototype.test = function(targetId) { - var experimentHeaderForm = new ExperimentHeaderForm(); - var panel = experimentHeaderForm.getPanel(new Experiment(experimentHeaderForm.input().experiment)); - panel.render(targetId); +/** It populates the form * */ +SuperpositionForm.prototype.refresh = function(subtractions) { + this.subtractions = subtractions; + this.superpositionGrid.refresh(subtractions); +}; + +SuperpositionForm.prototype.input = function() { + return {}; +}; +/** It populates the form **/ +SuperpositionForm.prototype.test = function(targetId) { + var macromoleculeForm = new SuperpositionForm(); + var panel = macromoleculeForm.getPanel(); + panel.render(targetId); }; /** - * Macromolecule form with the general parameters of a macromolecule + * Example form * * @witdh * @height - * - * #onSave button save has been clicked - * #onClose button close has been clicked */ -function MacromoleculeForm(args) { +function AssemblyForm(args) { this.id = BUI.id(); this.width = 700; this.height = 500; @@ -7053,6751 +6059,7745 @@ function MacromoleculeForm(args) { this.height = args.height; } } - - /** Events **/ - this.onSave = new Event(this); - this.onClose = new Event(this); -} -/** Type : is the Ext type then requiredtext or textfield * */ -MacromoleculeForm.prototype._getFieldTextWithHelp = function(type, fieldLabel, fieldName, help) { - return Ext.create('Ext.container.Container', { - margin : "10 0 0 10", - items : [ { - xtype : type, - fieldLabel : fieldLabel, - name : fieldName, - id : this.id + fieldName - }, { - xtype : 'label', - forId : 'myFieldId', - text : help, - margin : "5 0 0 105", - cls : "inline-help" - } ] - }); -}; + this.molarityGrid = new MolarityGrid({height : this.height - 50}); +} -MacromoleculeForm.prototype._getNumericWithHelp = function(type, fieldLabel, fieldName, help) { - return Ext.create('Ext.container.Container', { - margin : "0 0 0 10", - items : [ { - xtype : type, - fieldLabel : fieldLabel, - name : fieldName, - id : this.id + fieldName, - decimalPrecision : 6, - width : 220 - }, { - xtype : 'label', - forId : 'myFieldId', - text : help, - margin : "5 0 0 10", - cls : "inline-help" - } ] - }); +AssemblyForm.prototype._getItems = function() { + return [ { + xtype : 'label', + forId : 'myFieldId', + text : 'List of previously defined macromolecules present in the assembly. This information will be used for additional cross-checks where possible', + margin : '15 0 20 10', + cls : "inline-help" + }, this.molarityGrid.getPanel() ]; }; -MacromoleculeForm.prototype._getButtons = function() { - var _this = this; - return [ { - text : 'Save', - handler : function() { - _this._save(); - } - },{ - text : 'Close', - handler : function() { - _this.onClose.notify(); - - } - } ]; +AssemblyForm.prototype._getButtons = function() { + return []; }; -/** It persits the macromolecule in the database **/ -MacromoleculeForm.prototype._persist = function(macromoleculeId, acronym, name, molecularMass, extintionCoefficient, comments, refractiveIndex, solventViscosity) { - - /** Checking not duplicated acronym **/ - if (((macromoleculeId == null) && (BIOSAXS.proposal.getMacromoleculeByAcronym(acronym) != null))== true){ - BUI.showError("Duplicated acronym"); - return; - } - - - if (macromoleculeId == null){ - /** new macromolecule **/ - this.macromolecule = {}; - this.macromolecule.macromoleculeId = null; - } - else{ - this.macromolecule.macromoleculeId = macromoleculeId; - } - - this.macromolecule["acronym"] = acronym; - this.macromolecule["name"] = name; - this.macromolecule["molecularMass"] = molecularMass; - this.macromolecule["extintionCoefficient"] = extintionCoefficient; - this.macromolecule["comments"] = comments; - this.macromolecule["symmetry"] = Ext.getCmp(this.id + 'comboSym').getValue(); - this.macromolecule["refractiveIndex"] = refractiveIndex; - this.macromolecule["solventViscosity"] = solventViscosity; - - var _this = this; - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, proposal) { - /** Updating the proposal global object **/ - BIOSAXS.proposal.setItems(proposal); - _this.panel.setLoading(false); - - var saved = BIOSAXS.proposal.getMacromoleculeByAcronym(acronym); - /** Refreshing to check that everything is ok **/ - _this.refresh(saved); - _this.onSave.notify(saved); +AssemblyForm.prototype.getPanel = function() { + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + margin : 10, + border : 0, + defaultType : 'textfield', + items : this._getItems(), + buttons : this._getButtons() }); - - this.panel.setLoading("Saving Macromolecule") - adapter.saveMacromolecule(this.macromolecule); + return this.panel; }; -/** Save the macromolecule in the DB **/ -MacromoleculeForm.prototype._save = function() { - - var _this = this; - - var acronym = this._getField("acronym"); - var name = this._getField("name"); - var molecularMass = this._getField("molecularMass"); - var extintionCoefficient = this._getField("extintionCoefficient"); - var comments = this._getField("comments"); - - var refractiveIndex = this._getField("refractiveIndex"); - var solventViscosity = this._getField("solventViscosity"); - - /** Checking required fields **/ - if (name == "") { - BUI.showError("Name field is mandatory"); - return; - } - if (acronym == "") { - BUI.showError("Acroynm field is mandatory"); - return; - } - if (this.macromolecule != null){ - /** Checking if it is a new macromolecule **/ - if (this.macromolecule.macromoleculeId == null){ - /** Check if the acronym exists already **/ - this._persist(null, acronym, name, molecularMass, extintionCoefficient, comments, refractiveIndex, solventViscosity); - } - else{ - /** It is an update **/ - this._persist(this.macromolecule.macromoleculeId, acronym, name, molecularMass, extintionCoefficient, comments, refractiveIndex, solventViscosity); - } - } - else{ - /** It is a new macromolecule **/ - this._persist(null, acronym, name, molecularMass, extintionCoefficient, comments, refractiveIndex, solventViscosity); - } +/** It populates the form **/ +AssemblyForm.prototype.refresh = function(macromolecule) { + this.macromolecule = macromolecule; + this.molarityGrid.refresh(macromolecule); }; +AssemblyForm.prototype.input = function() { + return {}; +}; -MacromoleculeForm.prototype._getItems = function() { +AssemblyForm.prototype.test = function(targetId) { + var assemblyForm = new AssemblyForm(); + + var panel = assemblyForm.getPanel(); + panel.render(targetId); +}; +/** + * Edit the information of a buffer + * + * #onSaved + * #onRemoveAdditive + */ +function BufferForm() { var _this = this; - /** Symmetry combo box **/ - var symmetry = Ext.create('Ext.data.Store', { - fields : [ 's' ], - data : this._getSymmetries() - }); - this.symmetryComboBox = Ext.create('Ext.form.ComboBox', { - fieldLabel : 'Symmetry', - store : symmetry, - id : this.id + 'comboSym', - queryMode : 'local', - displayField : 's', - valueField : 's', - value : "P1", - margin : "0 0 0 30", - width : 220 + this.additiveGrid = new AdditiveGrid(); + this.additiveGrid.onRemoveButtonClicked.attach(function(sender, args) { + _this.onRemoveAdditive.notify(args); }); - - return [this._getFieldTextWithHelp("requiredtext", "Name", "name", "Long name. i.e: Bovine serum albumin"), - this._getFieldTextWithHelp("requiredtext", "Acronym", "acronym", "Acronym will be used in the files and analisys. i.e: BSA"), - this._getFieldTextWithHelp("textfield", "Mol. Mass (Da)", "molecularMass", "Atomic mass estimation measured in Da"), - { - xtype : 'container', - layout : 'hbox', - margin : "10 0 0 0", - items :[ - this._getNumericWithHelp("numberfield", "Extinction coef.", "extintionCoefficient", ""), - this.symmetryComboBox - ] - }, - { - xtype : 'container', - layout : 'hbox', - margin : "5 0 0 0", - items :[ - this._getNumericWithHelp("numberfield", "Refractive Index", "refractiveIndex", "How radiation propagates through the medium"), - this._getNumericWithHelp("numberfield", "Solvent Viscosity", "solventViscosity", "") - ] - }, - { - id : this.id + "comments", - xtype : 'textareafield', - name : 'comments', - margin : '35 0 0 10', - fieldLabel : 'Comments', - width : this.width - 100 - } ]; + + this.onSaved = new Event(this); + this.onRemoveAdditive = new Event(this); +} + +BufferForm.prototype.getBuffer = function() { + this.buffer.name = Ext.getCmp("buffer_name").getValue(); + this.buffer.acronym = Ext.getCmp("buffer_acronym").getValue(); + this.buffer.comments = Ext.getCmp("buffer_comments").getValue(); + this.buffer.ph = Ext.getCmp("buffer_ph").getValue(); + this.buffer.composition = Ext.getCmp("buffer_composition").getValue(); + this.buffer.bufferhasadditive3VOs = this.additiveGrid.getAdditives(); + return this.buffer; }; -MacromoleculeForm.prototype._getSymmetries = function() { - return [ { - "s" : "P1" - }, { - "s" : "P2" - }, { - "s" : "P3" - }, { - "s" : "P4" - }, { - "s" : "P5" - }, { - "s" : "P6" - }, { - "s" : "P32" - }, { - "s" : "P42" - }, { - "s" : "P52" - }, { - "s" : "P62" - }, { - "s" : "P222" - } ] +BufferForm.prototype._getTopPanel = function() { + return { + xtype : 'container', + layout : 'hbox', + border : 0, + frame : true, + items : [ { + xtype : 'container', + layout : 'hbox', + items : [ { + xtype : 'container', + flex : 1, + border : false, + layout : 'anchor', + defaultType : 'textfield', + items : [ { + xtype : 'requiredtext', + id : 'buffer_name', + fieldLabel : 'Name', + name : 'name', + width : '200px', + value : this.buffer.name + }, { + xtype : 'requiredtext', + id : 'buffer_acronym', + fieldLabel : 'Acronym', + name : 'acronym', + width : '200px', + value : this.buffer.acronym + } ] + } ] + }, { + xtype : 'container', + flex : 1, + layout : 'anchor', + defaultType : 'textfield', + margin : '0 0 0 10', + items : [ { + id : 'buffer_ph', + fieldLabel : 'pH', + name : 'ph', + value : this.buffer.ph, + xtype : 'numberfield', + width : 200, + minValue : 0, + maxValue : 15 + }, { + xtype : 'requiredtext', + id : 'buffer_composition', + fieldLabel : 'Composition', + name : 'composition', + width : 200, + value : this.buffer.composition + } ] + } ] + }; }; -MacromoleculeForm.prototype.getPanel = function() { - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - margin : 10, - border : 1, - defaultType : 'textfield', - items : this._getItems(), - buttons : this._getButtons() +BufferForm.prototype.getPanel = function(buffer) { + this.buffer = buffer; + this.panel = Ext.createWidget({ + xtype : 'container', + layout : 'vbox', + style : { + padding : '10px' + }, + fieldDefaults : { + labelAlign : 'left', + labelWidth : 50 + + }, + items : [ this._getTopPanel(), { + id : 'buffer_comments', + xtype : 'textareafield', + name : 'comments', + fieldLabel : 'Comments', + width : '100%', + value : buffer.comments + }, this.additiveGrid.getPanel(buffer) ] }); return this.panel; }; - -/** Populates each text field by field name and value **/ -MacromoleculeForm.prototype._populateField = function(fieldName, value) { - if (value != null){ - Ext.getCmp(this.id + fieldName).setValue(value); - } +BufferForm.prototype.input = function() { + return { + buffer : { + "bufferId" : 422, + "proposalId" : 10, + "safetyLevelId" : null, + "name" : "B1", + "acronym" : "B1", + "ph" : null, + "composition" : null, + "bufferhasadditive3VOs" : [], + "comments" : null + } + }; }; -/** Gets the value of a textfield **/ -MacromoleculeForm.prototype._getField = function(fieldName) { - return Ext.getCmp(this.id + fieldName).getValue(); +BufferForm.prototype.test = function(targetId) { + var bufferForm = new BufferForm(); + var panel = bufferForm.getPanel(bufferForm.input().buffer); + panel.render(targetId); }; - - -/** It populates the form **/ -MacromoleculeForm.prototype.refresh = function(macromolecule) { - this.macromolecule = macromolecule; - if (macromolecule != null){ - this._populateField("name", macromolecule.name); - this._populateField("acronym", macromolecule.acronym); - this._populateField("extintionCoefficient", macromolecule.extintionCoefficient); - this._populateField("molecularMass", macromolecule.molecularMass); - this._populateField("comments", macromolecule.comments); - this._populateField("refractiveIndex", macromolecule.refractiveIndex); - this._populateField("solventViscosity", macromolecule.solventViscosity); - if (macromolecule.symmetry != null){ - Ext.getCmp(this.id + 'comboSym').setValue(macromolecule.symmetry); + +/** + * @showTitle + * + * #onSaved + * #onAddPlates + * #onRemovePlates + **/ +function CaseForm(args) { + this.width = 700; + this.showTitle = true; + if (args != null) { + if (args.showTitle != null) { + this.showTitle = args.showTitle; } } -}; - -MacromoleculeForm.prototype.input = function() { - return {}; -}; - - -/** It populates the form **/ -MacromoleculeForm.prototype.test = function(targetId) { - var macromoleculeForm = new MacromoleculeForm(); - macromoleculeForm.onClose.attach(function(sender){ - alert("Click on close"); + var _this = this; + this.stockSolutionGrid = new StockSolutionGrid({ + width : this.width - 10, + minHeight : 300, + height : 300, + tbar : true, + showTitle : true, + isPackedVisible : false, + btnAddExisting : true, + btnRemoveVisible : false, + btnUnpackVisible : true }); - var panel = macromoleculeForm.getPanel(); - panel.render(targetId); -}; + /** When selecting existing stock solutions **/ + this.stockSolutionGrid.onStockSolutionSelected.attach(function(sender, stockSolutions) { + if (stockSolutions != null) { + for ( var i = 0; i < stockSolutions.length; i++) { + _this.saveStockSolution(stockSolutions[i]); + } + } + }); - + /** it can be because it has been added a new one or removed **/ + this.stockSolutionGrid.onProposalChanged.attach(function(sender, stockSolution) { + if (stockSolution != null) { + _this.saveStockSolution(stockSolution); + } else { + BIOSAXS.proposal.onInitialized.attach(function() { + _this.stockSolutionGrid.refresh(BIOSAXS.proposal.getStockSolutionsByDewarId(_this.dewar.dewarId)); + _this.stockSolutionGrid.grid.setLoading(false); + }); + BIOSAXS.proposal.init(); -function ModelVisualizerForm(args){ - this.id =BUI.id(); - this.width = 600; - this.height = 400; - if (args!= null){ - if (args.width != null){ - this.width = args.width; - } - if (args.height != null){ - this.height = args.height; } - } -}; -ModelVisualizerForm.prototype._getFirHTML = function(modelId, width, height, type, desc) { - var html = ""; - html = html + ''; - html = html + ''; - html = html + ''; - html = html + '
dammin.' + type + '
' + desc + '
'; - return html; -}; - -ModelVisualizerForm.prototype.getItems = function(modelPanel){ - _this = this; - var height = _this.height/2 - 60; - var width = _this.width/2 - 10; - - return Ext.create('Ext.container.Container', { - layout: { - type: 'vbox', // Arrange child items vertically - }, - items: [ - modelPanel, - { - xtype : 'container', - layout: { - type: 'hbox', // Arrange child items vertically - }, - items : [{ - html : this._getFirHTML("id", width, height, "fir", "Fit of the simulated scattering curve versus a smoothed experimental data (spline interpolation)"), - height :height, - width : width, - padding: 2 - }, - { - html : this._getFirHTML("id", width, height, "fit", "Fit of the simulated scattering curve versus the experimental data."), - height : height, - width : width, - padding: 2 - }] - } - - ] }); -}; -ModelVisualizerForm.prototype.refresh = function(models){ - var input = []; -// var colors = ["008000", "F0A804", "0000FF", "800080", "C0C0C0"]; - for (var i = 0; i < models.length; i++) { - console.log(BUI.rainbow(models.length, i).replace("#", "0x")); - input.push({ - color: BUI.rainbow(models.length, i).replace("#", "0x"), - modelId: models[i].modelId, - opacity: 0.8, - radius: 3, - title: BUI.getFileNameByPath(models[i].pdbFile), - type: "SHAPEDETERMINATIONMODEL" - - }); - } - - this.panel.removeAll(); - this.panel.add( - _this.getItems( - new PDBViewer({ - width : this.width - 10, - height : (this.height/2) - 10, - title : "" - }).draw(input) - ) - ); - + this.onSaved = new Event(this); + this.onAddPlates = new Event(this); + this.onRemovePlates = new Event(this); +} + +CaseForm.prototype.saveStockSolution = function(stockSolution) { + var _this = this; var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, data) { - var splitted = data.toString().split("\n"); - var array = []; - for ( var i = 0; i < splitted.length; i++) { - var line = splitted[i].trim(); - var line_splited = line.split(/\s*[\s,]\s*/); - if (line_splited.length == 4) { - array.push([ Number(line_splited[0]), BUI.getStvArray(line_splited[1], line_splited[2]), BUI.getStvArray(line_splited[3], 0) ]); - } - } - - var id = (_this.id + "firid"); - var dygraphWidget = new StdDevDyGraph(id, { - width : (_this.width/2) - 10, - height :(_this.height/2) -110, - xlabel : 'q(nm-1)' + this.stockSolutionGrid.grid.setLoading("ISPyB: setting case to Stock solution"); + adapter.onSuccess.attach(function(sender, stockSolution) { + BIOSAXS.proposal.onInitialized.attach(function() { + _this.stockSolutionGrid.refresh(BIOSAXS.proposal.getStockSolutionsByDewarId(_this.dewar.dewarId)); + _this.stockSolutionGrid.grid.setLoading(false); }); - dygraphWidget.draw(array, [ "#FF0000", "#0000FF", "#FF00FF" ], [ 's', 'I(exp)', 'I(sim)' ]); + BIOSAXS.proposal.init(); }); - - adapter.getModelFile("FIR", models[0].modelId); - - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, data) { - var splitted = data.toString().split("\n"); - var array = []; - for ( var i = 0; i < splitted.length; i++) { - var line = splitted[i].trim(); - var line_splited = line.split(/\s*[\s,]\s*/); - if (line_splited.length == 3) { - array.push([ Number(line_splited[0]), BUI.getStvArray(line_splited[1], 0), BUI.getStvArray(line_splited[2], 0) ]); - } - } - - var id = (_this.id + "fitid"); - - var dygraphWidget = new StdDevDyGraph(id, { - width : (_this.width/2) - 10, - height : (_this.height/2) - 110, - xlabel : 'q(nm-1)' - }); - dygraphWidget.draw(array, [ "#FF0000", "#0000FF" ], [ "s", "I(exp)", "I(sim)" ]); + adapter.onError.attach(function(sender, data) { + _this.stockSolutionGrid.grid.setLoading(false); + BUI.showError(data); }); - adapter.getModelFile("FIT", models[0].modelId); + stockSolution.boxId = _this.dewar.dewarId; + adapter.saveStockSolution(stockSolution); }; -ModelVisualizerForm.prototype.getPanel = function(modelList){ - _this = this; - this.modelList = modelList; - this.panel = Ext.create('Ext.Panel', { - title: 'Results', - width: this.width, - height: this.height, - layout: { - type: 'vbox', // Arrange child items vertically -// align: 'stretch' // Each takes up full width - }, - items: [ - - ], - listeners : { - afterrender : function(grid, eOpts) { -// alert(_this.modelList) - } - } +CaseForm.prototype.fillStores = function() { + var _this = this; + this.panel.setLoading("Loading Labcontacts from database"); + + var proposal = BUI.getProposal(); + proposal.onDataRetrieved.attach(function(sender, data) { + _this.labContactForSendingStore.loadData(data, false); + _this.labContactForReturnStore.loadData(data, false); + _this.panel.setLoading(false); }); - - return this.panel; + proposal.getLabContactsByProposalId(); }; +CaseForm.prototype.refresh = function(dewar) { + this.setDewar(dewar); + this.stockSolutionGrid.refresh(BIOSAXS.proposal.getStockSolutionsByDewarId(dewar.dewarId)); +}; + +CaseForm.prototype.getDewar = function() { + this.dewar.code = Ext.getCmp("dewar_code").getValue(); + this.dewar.comments = Ext.getCmp("dewar_comments").getValue(); + this.dewar.trackingNumberFromSynchrotron = Ext.getCmp("dewar_trackingNumberFromSynchrotron").getValue(); + this.dewar.trackingNumberToSynchrotron = Ext.getCmp("dewar_trackingNumberToSynchrotron").getValue(); + this.dewar.transportValue = Ext.getCmp("dewar_transportValue").getValue(); + this.dewar.storageLocation = Ext.getCmp("dewar_storageLocation").getValue(); + this.dewar.firstExperimentId = this.macromoleculeCombo.getValue(); + return this.dewar; +}; + +CaseForm.prototype.setDewar = function(dewar) { + this.dewar = dewar; + Ext.getCmp("dewar_code").setValue(this.dewar.code); + Ext.getCmp("dewar_dewarStatus").setText(new String(this.dewar.dewarStatus).toUpperCase()); + Ext.getCmp("dewar_comments").setValue(this.dewar.comments); + Ext.getCmp("dewar_trackingNumberFromSynchrotron").setValue(this.dewar.trackingNumberFromSynchrotron); + Ext.getCmp("dewar_trackingNumberToSynchrotron").setValue(this.dewar.trackingNumberToSynchrotron); + Ext.getCmp("dewar_transportValue").setValue(this.dewar.transportValue); + Ext.getCmp("dewar_storageLocation").setValue(this.dewar.storageLocation); + if (dewar.sessionVO != null) { + this.macromoleculeCombo.setValue(dewar.sessionVO.sessionId); + } +}; + +CaseForm.prototype.getSessionCombo = function() { + this.macromoleculeCombo = BIOSAXS_COMBOMANAGER.getComboSessions(BIOSAXS.proposal.getSessions(), { + labelWidth : 100, + margin : '5 0 00 0', + width : 250 + }); + return this.macromoleculeCombo; +}; + +CaseForm.prototype.getInformationPanel = function() { + if (this.panel == null) { + this.informationPanel = Ext.create('Ext.form.Panel', { + width : this.width - 10, + border : 0, + items : [ { + xtype : 'container', + margin : "2 2 2 2", + collapsible : false, + defaultType : 'textfield', + layout : 'anchor', + items : [ { + xtype : 'container', + layout : 'hbox', + items : [ { + xtype : 'requiredtext', + fieldLabel : 'Code', + allowBlank : false, + name : 'code', + id : 'dewar_code', + anchor : '50%' + }, { + xtype : 'label', + margin : '0 0 0 20', + readOnly : true, + id : 'dewar_dewarStatus', + anchor : '50%' + } ] + }, this.getSessionCombo(), { + margin : '5 0 0 0', + xtype : 'textareafield', + name : 'comments', + id : 'dewar_comments', + width : this.width - 50, + fieldLabel : 'Comments' + } ] + }, { + xtype : 'fieldset', + title : 'Courier Accounts Details for Return', + collapsible : false, + layout : 'anchor', + defaults : { + anchor : '100%' + }, + items : [ { + xtype : 'container', + layout : 'hbox', + items : [ { + xtype : 'textfield', + labelWidth : 200, + width : 280, + fieldLabel : 'Track Number From Synchrotron', + id : 'dewar_trackingNumberFromSynchrotron' + }, { + xtype : 'numberfield', + width : 190, + labelWidth : 110, + margin : '0 0 0 30', + fieldLabel : 'Transport Value', + id : 'dewar_transportValue' + } + + ] + }, { + xtype : 'container', + layout : 'hbox', + margin : '10 0 0 0', + items : [ + + { + xtype : 'textfield', + labelWidth : 200, + width : 280, + fieldLabel : 'Track Number To Synchrotron', + id : 'dewar_trackingNumberToSynchrotron' + }, { + xtype : 'textfield', + margin : '0 0 0 30', + width : 190, + labelWidth : 110, + fieldLabel : 'Storage Location', + id : 'dewar_storageLocation' + } + + ] + } ] + } ] + }); + } + + return this.informationPanel; +}; + +CaseForm.prototype.getPanel = function(dewar) { + this.dewar = dewar; + this.panel = Ext.createWidget({ + xtype : 'container', + layout : 'vbox', + width : this.width, + border : 0, + items : [ { + items : { + xtype : "container", + layout : "vbox", + margin : "5 5 5 5", + items : [ this.getInformationPanel(dewar), this.stockSolutionGrid.getPanel() ] + + } + } ] + }); + + this.refresh(dewar); + return this.panel; + +}; + +CaseForm.prototype.input = function() { + return { + dewar : { + "dewarId" : 305861, + "code" : "ESRF-TEST", + "comments" : "comments", + "storageLocation" : "FRIDGE", + "dewarStatus" : "opened", + "timeStamp" : null, + "isStorageDewar" : null, + "barCode" : "ESRF305861", + "customsValue" : null, + "transportValue" : null, + "trackingNumberToSynchrotron" : "3333", + "trackingNumberFromSynchrotron" : "224466", + "type" : "Dewar", + "sessionVO" : { + "sessionId" : 31697, + "expSessionPk" : null, + "projectCode" : null, + "startDate" : "2012 07 21", + "endDate" : "2012 07 23", + "beamlineName" : "BM29", + "scheduled" : 1, + "nbShifts" : 2, + "comments" : null, + "beamlineOperator" : "PERNOT P", + "usedFlag" : null, + "sessionTitle" : null, + "structureDeterminations" : null, + "dewarTransport" : null, + "databackupFrance" : null, + "databackupEurope" : null, + "visit_number" : null, + "operatorSiteNumber" : "14061", + "timeStamp" : "2012 04 25" + } + }, + proposal : { + "assemblies" : [], + "sessions" : [ { + "sessionId" : 31697, + "expSessionPk" : null, + "projectCode" : null, + "startDate" : "2012 07 21", + "endDate" : "2012 07 23", + "beamlineName" : "BM29", + "scheduled" : 1, + "nbShifts" : 2, + "comments" : null, + "beamlineOperator" : "PERNOT P", + "usedFlag" : null, + "sessionTitle" : null, + "structureDeterminations" : null, + "dewarTransport" : null, + "databackupFrance" : null, + "databackupEurope" : null, + "visit_number" : null, + "operatorSiteNumber" : "14061", + "timeStamp" : "2012 04 25" + } ], + "labcontacts" : [ { + "labContactId" : 787, + "personVO" : { + "personId" : 304252, + "personUUID" : null, + "familyName" : "KIM", + "givenName" : "Henry", + "title" : null, + "emailAddress" : "henry-sung.kim@ibs.fr", + "phoneNumber" : "", + "login" : "", + "passwd" : "", + "faxNumber" : "" + }, + "cardName" : "KIM-Institut de Bio", + "defaultCourrierCompany" : "22", + "courierAccount" : "", + "billingReference" : "", + "dewarAvgCustomsValue" : 0, + "dewarAvgTransportValue" : 0 + } ], + "buffers" : [ { + "bufferId" : 811, + "proposalId" : 3124, + "safetyLevelId" : null, + "name" : "EDTA", + "acronym" : "EDTA", + "ph" : null, + "composition" : "", + "bufferhasadditive3VOs" : [], + "comments" : "" + }, { + "bufferId" : 810, + "proposalId" : 3124, + "safetyLevelId" : null, + "name" : "HEPES", + "acronym" : "HEPES", + "ph" : null, + "composition" : "", + "bufferhasadditive3VOs" : [], + "comments" : "" + } ], + "shippings" : [ { + "shippingId" : 304107, + "shippingName" : "TEST", + "deliveryAgentAgentName" : null, + "deliveryAgentShippingDate" : null, + "deliveryAgentDeliveryDate" : null, + "deliveryAgentAgentCode" : null, + "deliveryAgentFlightCode" : null, + "shippingStatus" : "opened", + "timeStamp" : "2013 09 25", + "laboratoryId" : null, + "isStorageShipping" : null, + "creationDate" : "2013 09 25", + "comments" : "test", + "sendingLabContactVO" : { + "labContactId" : 787, + "personVO" : { + "personId" : 304252, + "personUUID" : null, + "familyName" : "KIM", + "givenName" : "Henry", + "title" : null, + "emailAddress" : "henry-sung.kim@ibs.fr", + "phoneNumber" : "", + "login" : "", + "passwd" : "", + "faxNumber" : "" + }, + "cardName" : "KIM-Institut de Bio", + "defaultCourrierCompany" : "22", + "courierAccount" : "", + "billingReference" : "", + "dewarAvgCustomsValue" : 0, + "dewarAvgTransportValue" : 0 + }, + "returnLabContactVO" : { + "labContactId" : 787, + "personVO" : { + "personId" : 304252, + "personUUID" : null, + "familyName" : "KIM", + "givenName" : "Henry", + "title" : null, + "emailAddress" : "henry-sung.kim@ibs.fr", + "phoneNumber" : "", + "login" : "", + "passwd" : "", + "faxNumber" : "" + }, + "cardName" : "KIM-Institut de Bio", + "defaultCourrierCompany" : "22", + "courierAccount" : "", + "billingReference" : "", + "dewarAvgCustomsValue" : 0, + "dewarAvgTransportValue" : 0 + }, + "returnCourier" : null, + "dateOfShippingToUser" : null, + "shippingType" : "DewarTracking", + "dewarVOs" : [ { + "dewarId" : 305861, + "code" : "ESRF-TEST", + "comments" : "comments", + "storageLocation" : "FRIDGE", + "dewarStatus" : "opened", + "timeStamp" : null, + "isStorageDewar" : null, + "barCode" : "ESRF305861", + "customsValue" : null, + "transportValue" : null, + "trackingNumberToSynchrotron" : "3333", + "trackingNumberFromSynchrotron" : "224466", + "type" : "Dewar", + "sessionVO" : { + "sessionId" : 31697, + "expSessionPk" : null, + "projectCode" : null, + "startDate" : "2012 07 21", + "endDate" : "2012 07 23", + "beamlineName" : "BM29", + "scheduled" : 1, + "nbShifts" : 2, + "comments" : null, + "beamlineOperator" : "PERNOT P", + "usedFlag" : null, + "sessionTitle" : null, + "structureDeterminations" : null, + "dewarTransport" : null, + "databackupFrance" : null, + "databackupEurope" : null, + "visit_number" : null, + "operatorSiteNumber" : "14061", + "timeStamp" : "2012 04 25" + } + } ] + } ], + "macromolecules" : [ { + "macromoleculeId" : 5933, + "safetylevelId" : null, + "proposalId" : 3124, + "name" : "A", + "acronym" : "A", + "molecularMass" : "", + "extintionCoefficient" : "", + "sequence" : null, + "creationDate" : null, + "comments" : "", + "macromoleculeregion3VOs" : [], + "stoichiometry3VOsForHostMacromoleculeId" : [], + "structure3VOs" : [] + } ], + "stockSolutions" : [ { + "stockSolutionId" : 6, + "proposalId" : 3124, + "macromoleculeId" : 5933, + "bufferId" : 811, + "instructionSet3VO" : null, + "boxId" : 305861, + "storageTemperature" : "20", + "volume" : "300", + "concentration" : "1.2", + "comments" : "Buffer EDTA with A", + "name" : "A_EDTA_1.2", + "samples" : [] + } ] + } + + }; +}; + +CaseForm.prototype.test = function(targetId) { + var caseForm = new CaseForm(); + BIOSAXS.proposal = new Proposal(caseForm.input().proposal); + var panel = caseForm.getPanel(caseForm.input().dewar); + panel.render(targetId); +}; -/** - * Example form - * - * @witdh - * @height - */ -function MolarityForm(args) { - this.id = BUI.id(); - this.width = 700; - this.height = 500; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } - - this.onSave = new Event(this); - this.onClose = new Event(this); -} - - -MolarityForm.prototype._getNumericWithHelp = function(type, fieldLabel, fieldName, help) { - return Ext.create('Ext.container.Container', { - margin : "10 0 0 10", - items : [ { - xtype : type, - fieldLabel : fieldLabel, - name : fieldName, - id : this.id + fieldName, - decimalPrecision : 6 - }, { - xtype : 'label', - forId : 'myFieldId', - text : help, - margin : "5 0 0 105", - cls : "inline-help" - } ] - }); -}; - - -MolarityForm.prototype._getItems = function() { - this.macromoleculeCombo = BIOSAXS_COMBOMANAGER.getComboMacromoleculeByMacromolecules(this.getMacromuleculesCandidates(this.macromolecule), { - width : 250, - labelWidth : 100, - margin : 10 - }); - - return [ { - xtype : 'container', - flex : 1, - margin : '10 0 0 10', - border : 0, - layout : 'anchor', - defaultType : 'requiredtext', - items : [ this.macromoleculeCombo, - this._getNumericWithHelp("textfield", "Ratio", "ratio", "Number in assymmetric units") - ] - } ]; -}; - -MolarityForm.prototype._persist = function() { - var _this = this; - var macromoleculeId = this.macromoleculeCombo.getValue(); - var ratio = Ext.getCmp(this.id + "ratio").getValue(); - var comments = "Not used yet"; - var dataAdapter = new BiosaxsDataAdapter(); - this.panel.setLoading("Saving"); - dataAdapter.onSuccess.attach(function(sender, args) { - _this.onSave.notify(); - }); - dataAdapter.saveStoichiometry(this.macromolecule.macromoleculeId, macromoleculeId, ratio, comments); -}; - -MolarityForm.prototype._getButtons = function() { - var _this = this; - - function onClose() { - _this.onClose.notify(); - } - - return [ { - text : 'Save', - handler : function() { - _this._persist(); - } - }, { - text : 'Cancel', - handler : function() { - onClose(); - } - } ]; -}; - -MolarityForm.prototype.getPanel = function() { - this.panel = Ext.create('Ext.form.Panel', { -// width : null, - height : this.height, - margin : 2, - border : 1, - defaultType : 'requiredtext', - items : this._getItems(), - buttons : this._getButtons() - }); - return this.panel; -}; - -/** macromolecules contains all macromolecules except this one **/ -MolarityForm.prototype.getMacromuleculesCandidates = function(macromolecule) { - var macromolecules = []; - if ( BIOSAXS.proposal.macromolecules){ - for (var i = 0; i < BIOSAXS.proposal.macromolecules.length; i++) { - var m = BIOSAXS.proposal.macromolecules[i]; - if (this.macromolecule != null){ - if (m.macromoleculeId != this.macromolecule.macromoleculeId) { - macromolecules.push(m); - } - } - } - } - return macromolecules; -}; - - -/** It populates the form **/ -MolarityForm.prototype.refresh = function(macromolecule) { - this.macromolecule = macromolecule; - -}; - - -MolarityForm.prototype.input = function() { - return {}; -}; - - -/** It populates the form **/ -MolarityForm.prototype.test = function(targetId) { - var macromoleculeForm = new MolarityForm(); - var panel = macromoleculeForm.getPanel(); - panel.render(targetId); -}; - -///** -// * -// * @witdh -// * @height -// */ -//function MacromoleculeForm(args) { -// this.id = BUI.id(); -// this.width = 700; -// this.height = 500; -// -// if (args != null) { -// if (args.width != null) { -// this.width = args.width; -// } -// if (args.height != null) { -// this.height = args.height; -// } -// } -// -// this.onClose = new Event(this); -//} -// -//MacromoleculeForm.prototype.getMacromolecule = function() { -// this.macromolecule.name = Ext.getCmp(this.panel.getItemId()).getValues().name; -// this.macromolecule.acronym = Ext.getCmp(this.panel.getItemId()).getValues().acronym; -// this.macromolecule.comments = Ext.getCmp(this.panel.getItemId()).getValues().comments; -// this.macromolecule.extintionCoefficient = Ext.getCmp(this.panel.getItemId()).getValues().extintionCoefficient; -// this.macromolecule.molecularMass = Ext.getCmp(this.panel.getItemId()).getValues().molecularMass; -// return this.macromolecule; -//}; -// -//MacromoleculeForm.prototype.setMacromolecule = function(macromolecule) { -// this.pdbStore.loadData(macromolecule.structure3VOs); -// -//}; -// -//MacromoleculeForm.prototype.getForm = function(macromolecule) { -// this.panel = Ext.createWidget('form', { -// frame : false, -// border : 0, -// padding : 15, -// width : 550, -// height : 350, -// items : [ { -// xtype : 'container', -// layout : 'hbox', -// items : [ { -// xtype : 'container', -// flex : 1, -// border : false, -// layout : 'anchor', -// defaultType : 'requiredtext', -// items : [ { -// fieldLabel : 'Name', -// name : 'name', -// anchor : '95%', -// tooltip : "Name of the macromolecule", -// value : macromolecule.name -// }, { -// fieldLabel : 'Acronym', -// name : 'acronym', -// anchor : '95%', -// value : macromolecule.acronym -// } ] -// }, { -// xtype : 'container', -// flex : 1, -// layout : 'anchor', -// defaultType : 'textfield', -// items : [ { -// xtype : 'numberfield', -// fieldLabel : 'Mol. Mass (Da)', -// name : 'molecularMass', -// value : macromolecule.molecularMass, -// decimalPrecision : 6 -// }, { -// xtype : 'numberfield', -// fieldLabel : 'Extinction coef.', -// name : 'extintionCoefficient', -// value : macromolecule.extintionCoefficient, -// decimalPrecision : 6 -// } ] -// } ] -// }, { -// xtype : 'textareafield', -// name : 'comments', -// fieldLabel : 'Comments', -// value : macromolecule.comments, -// width : this.width - 10 -// }, -// -// { -// html : BUI.getWarningHTML("The macromolecule is unsaved. Save the macromolecule to get access to other tabs"), -// margin : "150 10 10 10", -// id : this.id + "unsavedWarning", -// hidden : !(!macromolecule.macromoleculeId) -// } -// -// ] -// }); -// return this.panel; -//}; -// -//MacromoleculeForm.prototype.save = function() { -// var _this = this; -// -// var adapter = new BiosaxsDataAdapter(); -// adapter.onSuccess.attach(function(sender, proposal) { -// BIOSAXS.proposal.setItems(proposal); -// _this.panel.setLoading(false); -// -// Ext.getCmp(_this.id + "assembly").enable() -// Ext.getCmp(_this.id + "advanced").enable(); -// Ext.getCmp(_this.id + "unsavedWarning").hide(); -// }); -// -// if (this.getMacromolecule().name == "") { -// BUI.showError("Name field is mandatory"); -// return; -// } -// if (this.getMacromolecule().acronym == "") { -// BUI.showError("Acroynm field is mandatory"); -// return; -// } -// -// /** Check if acronym is unique * */ -// if (this.getMacromolecule().macromoleculeId == null) { -// if (BIOSAXS.proposal.getMacromoleculeByAcronym(this.getMacromolecule().acronym) == null) { -// this.panel.setLoading("ISPyB: Saving Macromolecule") -// adapter.saveMacromolecule(this.getMacromolecule()); -// } else { -// alert("There is already an existing macromolecule with the same acronym"); -// -// } -// } else { -// this.panel.setLoading("ISPyB: Saving Macromolecule") -// adapter.saveMacromolecule(this.getMacromolecule()); -// } -// -//}; -// -//MacromoleculeForm.prototype.getPanel = function(macromolecule) { -// var _this = this; -// this.macromolecule = macromolecule; -// return Ext.createWidget('tabpanel', { -// height : this.height, -// margin : 5, -// plain : true, -// style : { -// padding : 5 -// }, -// items : [ { -// tabConfig : { -// title : "General", -// disabled : false -// }, -// items : [ this.getForm(macromolecule) ], -// bbar : [ "->", { -// text : 'Save', -// cls : 'btn-with-border', -// style : { -// -// border : 1 -// }, -// handler : function() { -// _this.save(); -// } -// }, { -// text : 'Close', -// cls : 'btn-with-border', -// handler : function() { -// _this.onClose.notify(); -// } -// } ] -// }, { -// tabConfig : { -// id : this.id + "assembly", -// title : "Assembly", -// tooltip : 'Description of subunits present in the macromolecule', -// // hidden : (!macromolecule.macromoleculeId), -// disabled : (!macromolecule.macromoleculeId) -// }, -// items : [ this.getMolarityGrid(macromolecule) ] -// }, { -// tabConfig : { -// id : this.id + "advanced", -// title : "Advanced Modeling", -// // hidden : (!macromolecule.macromoleculeId), -// tooltip : 'Definition of the description contacts and symetries', -// disabled : (!macromolecule.macromoleculeId) -// }, -// items : [ this.getRigidBodyForm(macromolecule) ] -// } ] -// }); -//}; -// -//MacromoleculeForm.prototype.getRigidBodyForm = function(macromolecule) { -// var _this = this; -// -// // [P1, P2, P3, P4 ,P5 ,P6 ,32, P42, P52, P62] + P222 -// var symmetry = Ext.create('Ext.data.Store', { -// fields : [ 's' ], -// data : [ { -// "s" : "P1" -// }, { -// "s" : "P2" -// }, { -// "s" : "P3" -// }, { -// "s" : "P4" -// }, { -// "s" : "P5" -// }, { -// "s" : "P6" -// }, { -// "s" : "P32" -// }, { -// "s" : "P42" -// }, { -// "s" : "P52" -// }, { -// "s" : "P62" -// }, { -// "s" : "P222" -// } ] -// }); -// -// if (macromolecule.symmetry == null) { -// macromolecule.symmetry = "P1"; -// } -// var comboBox = Ext.create('Ext.form.ComboBox', { -// fieldLabel : 'Symmetry', -// store : symmetry, -// id : 'comboSym', -// queryMode : 'local', -// displayField : 's', -// valueField : 's', -// value : macromolecule.symmetry, -// margin : "10 0 0 0", -// listeners : { -// change : function(combo, newValue, oldValue, eOpts) { -// macromolecule.symmetry = newValue; -// } -// } -// }); -// -// this.rigidBodyPanel = Ext.createWidget('form', { -// frame : false, -// border : 0, -// padding : 10, -// width : 550, -// height : 400, -// items : [ { -// xtype : 'container', -// layout : 'hbox', -// items : [ { -// xtype : 'container', -// border : false, -// layout : 'hbox', -// items : [ { -// xtype : 'label', -// forId : 'myFieldId', -// text : 'Contact Desc:', -// width : 105, -// margin : '0 0 0 0' -// }, { -// xtype : 'textfield', -// hideLabel : true, -// id : "contactsDescriptionFilePath", -// margin : '0 0 0 0', -// width : 300, -// value : macromolecule.contactsDescriptionFilePath -// }, { -// text : 'Upload', -// xtype : 'button', -// margin : "0 0 0 20", -// width : 100, -// handler : function() { -// _this._openUploadDialog(macromolecule.macromoleculeId, "CONTACTS", "Upload Contact Description File"); -// } -// } ] -// } ] -// }, -// -// comboBox, { -// xtype : 'checkbox', -// margin : '10 0 0 5', -// boxLabel : "I want rigid body modeling run on this stuff", -// checked : true, -// width : 300 -// }, _this.getPDBGrid(macromolecule) ] -// }); -// return this.rigidBodyPanel; -//}; -// -//MacromoleculeForm.prototype.update = function() { -// var _this = this; -// BIOSAXS.proposal.onInitialized.attach(function() { -// if (BIOSAXS.proposal != null) { -// var macromolecules = BIOSAXS.proposal.macromolecules; -// for (var i = 0; i < macromolecules.length; i++) { -// if (macromolecules[i].macromoleculeId == _this.macromolecule.macromoleculeId) { -// _this.macromolecule = macromolecules[i]; -// _this.setMacromolecule(_this.macromolecule); -// _this.molarityStore.loadData(_this.parseMolarityData(_this.macromolecule)); -// _this.pdbGrid.setLoading(false); -// Ext.getCmp("contactsDescriptionFilePath").setValue(_this.macromolecule.contactsDescriptionFilePath) -// _this.molarityGrid.setLoading(false); -// -// } -// } -// } -// }); -// this.molarityGrid.setLoading("Updating"); -// this.pdbGrid.setLoading("Updating"); -// BIOSAXS.proposal.init(); -//}; -// -///******************************************************************************* -// * MOLARITY GRID -// ******************************************************************************/ -// -//MacromoleculeForm.prototype.parseMolarityData = function(macromolecule) { -// var data = []; -// if (macromolecule.stoichiometry != null) { -// for (var i = 0; i < macromolecule.stoichiometry.length; i++) { -// data.push({ -// ratio : macromolecule.stoichiometry[i].ratio, -// acronym : macromolecule.stoichiometry[i].macromolecule3VO.acronym, -// comments : macromolecule.stoichiometry[i].macromolecule3VO.comments, -// stoichiometryId : macromolecule.stoichiometry[i].stoichiometryId, -// name : macromolecule.stoichiometry[i].macromolecule3VO.name -// }); -// } -// } -// return data; -//}; -// -//MacromoleculeForm.prototype.getMolarityGrid = function(macromolecule) { -// var _this = this; -// -// this.molarityStore = Ext.create('Ext.data.Store', { -// fields : [ 'acronym', 'ratio', 'comments', 'stoichiometryId', 'name' ], -// data : this.parseMolarityData(macromolecule), -// sorters : { -// property : 'ratio', -// direction : 'DESC' -// } -// }); -// -// this.molarityGrid = Ext.create('Ext.grid.Panel', { -// store : this.molarityStore, -// height : 350, -// padding : 5, -// columns : [ -// -// { -// text : 'Subunit', -// columns : [ { -// text : "Acronym", -// width : 100, -// hidden : false, -// dataIndex : 'acronym', -// sortable : true -// }, { -// text : "Name", -// width : 100, -// hidden : false, -// dataIndex : 'name', -// sortable : true -// }, { -// text : "Comments", -// width : 100, -// dataIndex : 'comments', -// sortable : true -// } ] -// }, { -// text : "Number
in assymmetric units", -// width : 150, -// dataIndex : 'ratio', -// tooltip : 'Number of times this subunit is present in the macromolecule', -// sortable : true -// }, { -// id : this.id + 'MOLARITY_REMOVE', -// flex : 0.1, -// sortable : false, -// renderer : function(value, metaData, record, rowIndex, colIndex, store) { -// return BUI.getRedButton('REMOVE'); -// } -// } ], -// listeners : { -// cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { -// if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'MOLARITY_REMOVE') { -// var dataAdapter = new BiosaxsDataAdapter(); -// dataAdapter.onSuccess.attach(function() { -// _this.molarityGrid.setLoading(false); -// _this.update(); -// }); -// dataAdapter.removeStoichiometry(record.data.stoichiometryId); -// _this.molarityGrid.setLoading("Removing Structure"); -// } -// } -// }, -// buttons : [ { -// text : 'Add molarity', -// handler : function() { -// -// function onClose() { -// w.destroy(); -// _this.update(); -// } -// var w = Ext.create('Ext.window.Window', { -// title : 'Molarity', -// height : 300, -// width : 500, -// modal : true, -// buttons : [ { -// text : 'Save', -// handler : function() { -// var macromoleculeId = (_this.macromoleculeCombo.getValue()); -// var ratio = Ext.getCmp(_this.id + "ratio").getValue(); -// var comments = ""; -// var dataAdapter = new BiosaxsDataAdapter(); -// dataAdapter.onSuccess.attach(function(sender, args) { -// _this.update(); -// w.destroy(); -// }); -// dataAdapter.saveStoichiometry(_this.macromolecule.macromoleculeId, macromoleculeId, ratio, comments); -// } -// }, { -// text : 'Cancel', -// handler : function() { -// onClose(); -// } -// } ], -// items : [ _this.getMolarityForm(macromolecule) ], -// listeners : { -// onEsc : function() { -// onClose(); -// }, -// close : function() { -// onClose(); -// } -// } -// }).show(); -// } -// } ] -// }); -// return this.molarityGrid; -//}; -// -///******************************************************************************* -// * PDB GRID -// ******************************************************************************/ -// -//MacromoleculeForm.prototype._openUploadDialog = function(macromoleculeId, type, title) { -// var _this = this; -// function onClose() { -// w.destroy(); -// _this.update(); -// } -// -// var w = Ext.create('Ext.window.Window', { -// title : title, -// height : 200, -// width : 400, -// modal : true, -// buttons : [ { -// text : 'Close', -// handler : function() { -// onClose(); -// } -// } ], -// layout : 'fit', -// items : { -// html : "" -// }, -// listeners : { -// onEsc : function() { -// onClose(); -// }, -// close : function() { -// onClose(); -// } -// } -// }).show(); -//}; -// -//MacromoleculeForm.prototype._getPlugins = function() { -// var _this = this; -// var plugins = []; -// // if (this.updateRowEnabled) { -// plugins.push(Ext.create('Ext.grid.plugin.RowEditing', { -// clicksToEdit : 1, -// listeners : { -// validateedit : function(grid, e) { -// /** Comments are always updatable* */ -// e.record.raw.symmetry = e.newValues.symmetry; -// e.record.raw.multiplicity = e.newValues.multiplicity; -// -// var adapter = new BiosaxsDataAdapter(); -// adapter.onSuccess.attach(function(sender, measurement) { -// // _this.grid.setLoading(false); -// }); -// adapter.onError.attach(function() { -// alert("Error"); -// // _this.grid.setLoading(false); -// }); -// -// // _this.grid.setLoading(); -// adapter.saveStructure(e.record.raw); -// } -// } -// })); -// // } -// return plugins; -//}; -// -//MacromoleculeForm.prototype.getPDBGrid = function(macromolecule) { -// var _this = this; -// -// var data = macromolecule.structure3VOs; -// -// // /** Getting PDB from subunits **/ -// // if (macromolecule != null){ -// // if (macromolecule.stoichiometry != null){ -// // for (var i =0; i < macromolecule.stoichiometry.length; i++){ -// // var stoichiometry = macromolecule.stoichiometry[i]; -// // if (stoichiometry.macromolecule3VO != null){ -// // if (stoichiometry.macromolecule3VO.structure3VOs != null){ -// // for (var j = 0; j < stoichiometry.macromolecule3VO.structure3VOs.length; -// // j++) { -// // var structure = stoichiometry.macromolecule3VO.structure3VOs[j]; -// // structure["isSubunit"] = stoichiometry.macromolecule3VO.acronym; -// // data.push(structure) -// // } -// // } -// // } -// // } -// // } -// // } -// -// this.pdbStore = Ext.create('Ext.data.Store', { -// fields : [ 'filePath', 'structureId', 'structureType', 'symmetry', 'structureId', 'name', 'multiplicity' ], -// data : macromolecule.structure3VOs, -// groupField : 'structureType', -// sorters : { -// property : 'structureId', -// direction : 'DESC' -// } -// }); -// -// var groupingFeature = Ext.create('Ext.grid.feature.Grouping', { -// groupHeaderTpl : Ext.create('Ext.XTemplate', -// "
{name:this.formatName}
", { -// formatName : function(name) { -// return name; -// } -// }), -// hideGroupedHeader : true, -// startCollapsed : false -// }); -// -// this.pdbGrid = Ext.create('Ext.grid.Panel', { -// margin : "15 0 0 5", -// height : 250, -// store : this.pdbStore, -// plugins : _this._getPlugins(), -// buttons : [ { -// // text : 'Add PDB file', -// text : 'Add Modeling Option', -// handler : function() { -// _this._openUploadDialog(macromolecule.macromoleculeId, "PDB", 'Upload PDB File'); -// } -// } -// -// ], -// columns : [ -// { -// text : "structureId", -// flex : 0.2, -// hidden : true, -// dataIndex : 'structureId', -// sortable : true -// }, -// { -// text : "File", -// flex : 0.5, -// dataIndex : 'filePath', -// sortable : true, -// hidden : true -// }, -// { -// text : "PDB", -// flex : 0.4, -// dataIndex : 'name', -// sortable : true -// }, -// { -// text : "Symmetry", -// flex : 0.4, -// dataIndex : 'symmetry', -// sortable : true, -// editor : { -// xtype : 'combobox', -// typeAhead : true, -// triggerAction : 'all', -// selectOnTab : true, -// store : [ [ "P1", "P1" ], [ "P2", "P2" ], [ "P3", "P3" ], [ "P4", "P4" ], [ "P5", "P5" ], [ "P6", "P6" ], [ "P32", "P32" ], [ "P42", "P42" ], -// [ "P52", "P52" ], [ "P62", "P62" ], [ "P222", "P222" ] ], -// } -// }, { -// text : "Multiplicity", -// flex : 0.4, -// dataIndex : 'multiplicity', -// sortable : true, -// editor : { -// xtype : 'textfield' -// } -// -// }, { -// text : "Subunit", -// flex : 0.2, -// dataIndex : 'isSubunit', -// sortable : true, -// hidden : true -// }, { -// text : "Type", -// flex : 0.2, -// dataIndex : 'structureType', -// sortable : true, -// hidden : true -// }, -// -// { -// id : this.id + 'REMOVE', -// flex : 0.2, -// hidden : true, -// sortable : false, -// renderer : function(value, metaData, record, rowIndex, colIndex, store) { -// return BUI.getRedButton('REMOVE'); -// } -// }, ], -// -// listeners : { -// itemdblclick : function(dataview, record, item, e) { -// _this._editExperiment(record.raw.experimentId); -// }, -// cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { -// -// if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'REMOVE') { -// var dataAdapter = new BiosaxsDataAdapter(); -// dataAdapter.onSuccess.attach(function() { -// _this.pdbGrid.setLoading(false); -// _this.update(); -// }); -// dataAdapter.removeStructure(record.data.structureId); -// _this.pdbGrid.setLoading("Removing PDB file"); -// } -// -// } -// }, -// viewConfig : { -// getRowClass : function(record, rowIdx, params, store) { -// if (record.raw.isSubunit != null) { -// return "blue-row"; -// } -// } -// } -// }); -// -// return this.pdbGrid; -//}; -// -//MacromoleculeForm.prototype.getMolarityForm = function(macromolecule) { -// var _this = this; -// var data = []; -// for (var i = 0; i < BIOSAXS.proposal.macromolecules.length; i++) { -// var m = BIOSAXS.proposal.macromolecules[i]; -// if (m.macromoleculeId != macromolecule.macromoleculeId) { -// data.push(m); -// } -// -// } -// this.macromoleculeCombo = BIOSAXS_COMBOMANAGER.getComboMacromoleculeByMacromolecules(data, { -// width : 250, -// labelWidth : 100, -// margin : 10 -// }); -// -// return Ext.createWidget('form', { -// -// frame : false, -// border : 0, -// // padding : 15, -// width : 550, -// height : 350, -// items : [ { -// xtype : 'container', -// flex : 1, -// border : false, -// layout : 'anchor', -// defaultType : 'requiredtext', -// items : [ this.macromoleculeCombo, { -// xtype : 'numberfield', -// name : 'Ratio', -// id : _this.id + "ratio", -// fieldLabel : 'Number in assymmetric units', -// value : 1, -// decimalPrecision : 6, -// margin : 10 -// }, { -// xtype : 'textareafield', -// name : 'comments', -// fieldLabel : 'Comments', -// margin : 10, -// width : 400, -// value : "" -// -// } ] -// } ] -// }); -// -//}; -// -///******************************************************************************* -// * JAVASCRIPT DOC -// ******************************************************************************/ -//MacromoleculeForm.prototype.input = function() { -// return { -// macromolecule : DATADOC.getMacromolecule_10() -// }; -//}; -// -//MacromoleculeForm.prototype.test = function(targetId) { -// var macromoleculeForm = new MacromoleculeForm(); -// var panel = macromoleculeForm.getPanel(macromoleculeForm.input().macromolecule); -// panel.render(targetId); -//}; - -function ResultSummaryForm() { - this.radiationDamageThreshold = BUI.getRadiationDamageThreshold(); - this.qualityThreshold = BUI.getQualityThreshold(); - - /** Data clusters with bufers **/ - this.clusterByBuffers = false; - - /** Visualization are groupeb by concenttrations. Ex: 4.5mg/ml and 4.7mg/ml will be clusterized together **/ - this.collapseConcentrations = true; - - this.summaryHeight = 350; - this.id = BUI.id(); - - var _this = this; - - this.qualityControlResultsWidget = new QualityControlResultsWidget({ - qualityThreshold : this.radiationDamageThreshold, - radiationDamageThreshold : this.qualityThreshold - - }); - this.qualityControlResultsWidget.onQualityChanged.attach(function(sender, value) { - _this.qualityThreshold = value; - _this.thresholdsChanged(); - }); - - this.qualityControlResultsWidget.onRadiationDatamageChanged.attach(function(sender, value) { - _this.radiationDamageThreshold = value; - _this.thresholdsChanged(); - - }); - this.concentrationHTMLTableWidget = new ConcentrationHTMLTableWidget({ - height : 250, - showBufferColumns : this.clusterByBuffers - }); - - this.plot = new BoxWhiskerGraph({ - targetId : _this.id + '_boxPlot', - height : 350, - width : 450, - maxBoxWidth : 25 - }); - - this.rangePlot = new RangeWhiskerGraph({ - targetId : _this.id + '_rangePlot', - height : 350, - width : 450, - maxBoxWidth : 25 - }); -} - -ResultSummaryForm.prototype.thresholdsChanged = function() { - var parsedData = this.prepareData(this.rawData); - - var filtered = JSON.parse(JSON.stringify(parsedData)); - filtered.concentration.concentrations = []; - for ( var conc in parsedData.concentration.concentrations) { - if (parsedData.concentration.concentrations[conc].calculation.rgGnom.validNumber > 0) { - filtered.concentration.concentrations.push(parsedData.concentration.concentrations[conc]); - } - } - - this.plotWhisker(filtered); - this.plotRange(filtered); - - this.concentrationHTMLTableWidget.refresh(parsedData); -}; - -/** Given a frame object (object returned by analyzeFrames()) and depending of the threshold indicates if a datacollection has radiation damage **/ -ResultSummaryForm.prototype.hasRadiationDamage = function(frameObject) { - var bb = frameObject.bufferBeforeFramesMerged / frameObject.framesCount; - var ba = frameObject.bufferAfterFramesMerged / frameObject.framesCount; - var mol = frameObject.framesMerge / frameObject.framesCount; - return !((bb >= this.radiationDamageThreshold) && (ba >= this.radiationDamageThreshold) && (mol >= this.radiationDamageThreshold)); -}; - -/** Return (frameObject) an object with the information about the frames for a data collection**/ -ResultSummaryForm.prototype.analyzeFrames = function(dataCollectionRow) { - return { - bufferAfterFramesMerged : dataCollectionRow.bufferAfterFramesMerged, - bufferBeforeFramesMerged : dataCollectionRow.bufferBeforeFramesMerged, - framesCount : dataCollectionRow.framesCount, - framesMerge : dataCollectionRow.framesMerge - }; -}; - -ResultSummaryForm.prototype.detectDataCollectionWarnings = function(dataCollectionRow) { - var frameObject = this.analyzeFrames(dataCollectionRow); - var warnings = { - count : 0, - type : [] - }; - - if (this.hasRadiationDamage(frameObject)) { - warnings.count = warnings.count + 1; - warnings.type.push("RADIATION DAMAGE"); - } - - if (Number(dataCollectionRow.quality) < this.qualityThreshold) { - warnings.count = 1;//warnings.count + 1; - warnings.type.push("Quality <" + this.qualityThreshold); - } - return warnings; -}; - -/** Return array composed by {concentration} objects **/ -ResultSummaryForm.prototype.getConcentrations = function(data) { - var concentrationsId = {}; - - for ( var i = 0; i < data.length; i++) { - var warning = this.detectDataCollectionWarnings(data[i]); - var id = data[i].conc;// + "_" + data[i].bufferId; - if (this.clusterByBuffers) { - id = data[i].conc + "_" + data[i].bufferId; - } - - if (concentrationsId[id] == null) { - concentrationsId[id] = { - id : id, - concentration : Number(data[i].conc).toFixed(2), - bufferId : data[i].bufferId, - bufferAcronym : data[i].bufferAcronym, - rgGuinier : [], - i0Guinier : [], - rgGnom : [], - dMax : [], - quality : [], - frames : [], - frames_warning : warning.count - }; - } else { - concentrationsId[id].frames_warning = concentrationsId[id].frames_warning + warning.count; - } - - concentrationsId[id].frames.push(data[i]); - - if (warning.count == 0) { - concentrationsId[id].rgGuinier.push(data[i].rgGuinier); - concentrationsId[id].i0Guinier.push(data[i].I0); - concentrationsId[id].quality.push(data[i].quality); - concentrationsId[id].rgGnom.push(data[i].rgGnom); - concentrationsId[id].dMax.push(data[i].dmax); - } - - } - var concentrations = []; - for ( var item in concentrationsId) { - if (concentrationsId.hasOwnProperty(item)) { - concentrations.push({ - concentration : concentrationsId[item].concentration, - id : item, - bufferId : Number(concentrationsId[item].bufferId).toFixed(2), - bufferAcronym : concentrationsId[item].bufferAcronym, - rgGuinier : concentrationsId[item].rgGuinier, - /** Frames **/ - frames : concentrationsId[item].frames, - frames_warning : concentrationsId[item].frames_warning, - /** Calculation **/ - calculation : { - rgGuinier : BUI.getStandardDeviation(concentrationsId[item].rgGuinier), - i0Guinier : BUI.getStandardDeviation(concentrationsId[item].i0Guinier), - quality : BUI.getStandardDeviation(concentrationsId[item].quality), - rgGnom : BUI.getStandardDeviation(concentrationsId[item].rgGnom), - dMax : BUI.getStandardDeviation(concentrationsId[item].dMax) - - } - }); - } - } - - return { - concentrations : concentrations - }; -}; - -ResultSummaryForm.prototype.prepareData = function(data) { - /** Return array composed by {acronym, bufferId} objects **/ - function getBuffers(data) { - var buffersId = {}; - for ( var i = 0; i < data.length; i++) { - buffersId[data[i].bufferId] = data[i].acronym; - } - var buffers = []; - for ( var id in buffersId) { - if (buffersId.hasOwnProperty(id)) { - buffers.push({ - acronym : buffersId[id], - bufferId : id - }); - } - } - return buffers; - } - - /** Get a string with all the concentrations **/ - function getConcentrationString(parseConcentrations) { - var concentrations = []; - for ( var i = 0; i < parseConcentrations.concentrations.length; i++) { - concentrations.push(parseConcentrations.concentrations[i].concentration + " mg/ml "); - } - return concentrations.toString(); - } - - var parseConcentrations = this.getConcentrations(data); - - return { - dataCollectionCount : data.length, - buffers : getBuffers(data), - concentration : parseConcentrations, - concentrationLabel : getConcentrationString(parseConcentrations) - }; -}; - -ResultSummaryForm.prototype.getDataForWhisker = function(data) { - var clusters = []; - - var concentrations = {}; - var i = 0; - var conc = 0; - if (this.collapseConcentrations) { - for (i = 0; i < data.concentration.concentrations.length; i++) { - conc = data.concentration.concentrations[i]; - var concentration = Number(conc.concentration).toFixed(0); - if (concentrations[concentration] == null) { - concentrations[concentration] = {}; - concentrations[concentration].concentration = concentration; - concentrations[concentration].calculation = {}; - concentrations[concentration].calculation.rgGuinier = {}; - concentrations[concentration].calculation.rgGuinier.values = []; - concentrations[concentration].calculation.rgGuinier.values = conc.calculation.rgGuinier.values; - concentrations[concentration].calculation.rgGnom = {}; - concentrations[concentration].calculation.rgGnom.values = []; - concentrations[concentration].calculation.rgGnom.values = conc.calculation.rgGnom.values; - } else { - concentrations[concentration].calculation.rgGuinier.values = concentrations[concentration].calculation.rgGuinier.values - .concat(conc.calculation.rgGuinier.values); - concentrations[concentration].calculation.rgGnom.values = concentrations[concentration].calculation.rgGnom.values - .concat(conc.calculation.rgGnom.values); - } - } - - /** From object to array **/ - var array = []; - for ( var key in concentrations) { - if (concentrations.hasOwnProperty(key)) { - array.push(concentrations[key]); - } - } - data.concentration.concentrations = array; - } - - for (i = 0; i < data.concentration.concentrations.length; i++) { - conc = data.concentration.concentrations[i]; - clusters.push({ - name : conc.concentration + "mg/ml", - concentration : Number(conc.concentration), - x : Number(conc.concentration), - classes : [] - }); - clusters[clusters.length - 1].classes.push({ - name : "Guinier", - color : '#9A2EFE', - values : conc.calculation.rgGuinier.values - - }); - clusters[clusters.length - 1].classes.push({ - name : "P(r)", - color : '#2E64FE', - values : conc.calculation.rgGnom.values - - }); - } - return { - clusters : clusters.sort(function(a, b) { - return a.concentration - b.concentration; - }) - }; -}; - -ResultSummaryForm.prototype.getDataForWhiskerQuality = function(data) { - var clusters = []; - - for ( var i = 0; i < data.concentration.concentrations.length; i++) { - var conc = data.concentration.concentrations[i]; - clusters.push({ - name : conc.concentration + "mg/ml", - classes : [] - }); - clusters[clusters.length - 1].classes.push({ - name : "Quality", - values : conc.calculation.quality.values - - }); - } - - return { - clusters : clusters - }; -}; - -ResultSummaryForm.prototype.plotQualityWhisker = function(parsedData) { - this.qualityPlot.refresh(this.getDataForWhiskerQuality(parsedData)); -}; - -ResultSummaryForm.prototype.plotWhisker = function(parsedData) { - this.plot.refresh(this.getDataForWhisker(parsedData)); -}; - -ResultSummaryForm.prototype.plotRange = function(parsedData) { - this.rangePlot.refresh(this.getDataForWhisker(parsedData)); -}; - -ResultSummaryForm.prototype.getPanel = function(data) { - var _this = this; - _this.rawData = data; - var parsedData = this.prepareData(data); - - this.panel = Ext - .createWidget( - 'form', - { - bodyPadding : 20, - frame : false, - border : 0, - width : this.width, - height : this.summaryHeight + 1000, - items : [ { - xtype : 'container', - layout : 'hbox', - items : [ { - xtype : 'container', - flex : 1, - border : false, - layout : 'anchor', - defaultType : 'textfield', - items : [ - _this.qualityControlResultsWidget.getPanel(), - { - xtype : 'fieldset', - width : 950, - margin : "20, 0 0 0", - height : this.summaryHeight + 500, - items : [ - { - html : "
Concentration Analysis
", - border : 0, - width : 900 - - }, - { - html : this.concentrationHTMLTableWidget.getPanel(parsedData), - border : 0, - width : 900, - margin : "10, 0 0 10" - - }, - { - xtype : 'container', - layout : 'vbox', - border : 5, - items : [ - { - html : "
Rg based on Guinier and Gnom
", - border : 8, - width : 900, - margin : "20 0 0 10" - - }, { - xtype : 'container', - layout : 'hbox', - items : [ { - xtype : 'container', - layout : 'vbox', - items : [ { - html : "
", - border : 0, - width : this.plot.width, - padding : "10 0 0 20", - listeners : { - afterrender : function() { - _this.plotWhisker(parsedData); - - } - } - }, { - html : "
Concentration (mg/ml)
", - width : 450, - border : 0, - margin : "-50 0 0 0" - - } ] - }, { - xtype : 'container', - layout : 'vbox', - items : [ { - html : "
", - border : 0, - width : this.rangePlot.width, - padding : "10 0 0 10", - listeners : { - afterrender : function() { - _this.plotRange(parsedData); - } - } - }, { - html : "
Concentration (mg/ml)
", - width : 450, - border : 0, - margin : "-50 0 0 0" - - } ] - } ] - } ] - } ] - } ] - } - - ] - } ] - }); - return this.panel; - -}; - -ResultSummaryForm.prototype.input = function() { - return { - data : DATADOC.getData_3367() - }; -}; - -ResultSummaryForm.prototype.test = function(targetId) { - var resultSummaryForm = new ResultSummaryForm(); - var panel = resultSummaryForm.getPanel(resultSummaryForm.input().data); - panel.render(targetId); - -}; - -/** - * Example form - * - * @witdh - * @height - */ -function RigibBodyModelingForm(args) { - this.id = BUI.id(); - this.width = 700; - this.height = 500; - - if (args != null) { - if (args.width != null) { - this.width = args.width; - } - if (args.height != null) { - this.height = args.height; - } - } - - var _this = this; - this.rigidBodyGrid = new AprioriRigidBodyGrid(); - - this.rigidBodyGrid.onUploadFile.attach(function(sender, type, title){ - _this._openUploadDialog(_this.macromolecule.macromoleculeId, type, title); - }); - - this.rigidBodyGrid.onRemove.attach(function(sender, type, title){ - _this._update(); - }); - - this.onSave = new Event(this); - -} - -RigibBodyModelingForm.prototype._getItems = function() { - var _this = this; - - - return [ { - xtype : 'label', - forId : 'myFieldId', - text : 'Information for model fit, mixture analysis and rigid body modeling', - margin : '15 0 20 10', - cls : "inline-help" - }, - this.rigidBodyGrid.getPanel(), - { - xtype : 'label', - forId : 'myFieldId', - text : 'Distance restraints may be imposed on the model using contacts conditions file (OPTIONAL)', - margin : '25 0 5 10', - cls : "inline-help" - }, - { - xtype : 'container', - layout : 'hbox', - items : [ { - xtype : 'container', - border : false, - layout : 'hbox', - items : [ { - xtype : 'label', - forId : 'myFieldId', - text : 'Contact Description File: (Optional)', - width : 150, - margin : '10 0 0 10' - }, { - id : this.id + "contactsDescriptionFilePath", - xtype : 'textfield', - hideLabel : true, - margin : '10 0 0 0', - width : 200, - disabled: true - }, { - text : 'Upload', - xtype : 'button', - margin : "10 0 0 10", - width : 80, - handler : function() { - - _this._openUploadDialog(_this.macromolecule.macromoleculeId, "CONTACTS", "Upload Contact Description File"); - } - }, { - text : 'Remove', - id : _this.id + "_remove", - xtype : 'button', - margin : "10 0 0 10", - width : 80, - handler : function() { - _this.macromolecule.contactsDescriptionFilePath = null; - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, proposal) { - /** Updating the proposal global object **/ - BIOSAXS.proposal.setItems(proposal); - _this.panel.setLoading(false); - - var saved = BIOSAXS.proposal.getMacromoleculeByAcronym(_this.macromolecule.acronym); - /** Refreshing to check that everything is ok **/ - _this.refresh(saved); - _this.onSave.notify(saved); - }); - - _this.panel.setLoading("Saving Macromolecule") - adapter.saveMacromolecule(_this.macromolecule); - } - } ] - } ] - }, { - xtype : 'panel', - html : "Go to SASREF manual for further information", - margin : "10 0 0 160", - border : 0 - - }, - { - xtype : 'checkbox', - margin : '10 0 0 5', - boxLabel : "I want rigid body modeling run on this stuff", - checked : true, - width : 300 - } ] - -}; - -/** Because update is a jsp page we don't know if the user has uploaded a file or not then we need to refresh **/ -RigibBodyModelingForm.prototype._update = function(macromoleculeId, type, title) { - var _this = this; - BIOSAXS.proposal.onInitialized.attach(function() { - if (BIOSAXS.proposal != null) { - _this.refresh(BIOSAXS.proposal.getMacromoleculeById(_this.macromolecule.macromoleculeId)); - _this.panel.setLoading(false); - } - }); - this.panel.setLoading(); - BIOSAXS.proposal.init(); -}; - -RigibBodyModelingForm.prototype._openUploadDialog = function(macromoleculeId, type, title) { - var _this = this; - function onClose() { - w.destroy(); - _this._update(); - - } - - var w = Ext.create('Ext.window.Window', { - title : title, - height : 200, - width : 400, - modal : true, - buttons : [ { - text : 'Close', - handler : function() { - onClose(); - } - } ], - layout : 'fit', - items : { - html : "" - }, - listeners : { - onEsc : function() { - onClose(); - }, - close : function() { - onClose(); - } - } - }).show(); -}; - -RigibBodyModelingForm.prototype._getButtons = function() { - return []; -}; - -RigibBodyModelingForm.prototype.getPanel = function() { - var _this = this; - this.panel = Ext.create('Ext.form.Panel', { - width : this.width, - height : this.height, - margin : 10, - border : 1, - defaultType : 'textfield', - items : this._getItems(), - buttons : this._getButtons(), - listeners : { - afterrender : function(){ - _this._populate(); - - } - } - }); - return this.panel; -}; - -/** Populates could be call when the DOM is not filled yet **/ -RigibBodyModelingForm.prototype._populate = function() { - if (this.macromolecule != null){ - if (Ext.getCmp(this.id + "contactsDescriptionFilePath") != null){ - if (this.macromolecule.contactsDescriptionFilePath != null){ - Ext.getCmp(this.id + "contactsDescriptionFilePath").setValue(this.macromolecule.contactsDescriptionFilePath); - Ext.getCmp(this.id + "_remove").enable(); - } - else{ - Ext.getCmp(this.id + "_remove").disable(); - Ext.getCmp(this.id + "contactsDescriptionFilePath").setValue(""); - - } - } - } -}; - -/** It populates the form * */ -RigibBodyModelingForm.prototype.refresh = function(macromolecule) { - this.macromolecule = macromolecule; - this.rigidBodyGrid.refresh(macromolecule); - this._populate(); -}; - -RigibBodyModelingForm.prototype.input = function() { - return {}; -}; - - -/** It populates the form **/ -RigibBodyModelingForm.prototype.test = function(targetId) { - var macromoleculeForm = new RigibBodyModelingForm(); - var panel = macromoleculeForm.getPanel(); - panel.render(targetId); -}; - - -/** - * Same form as MX part - * - * @creationMode if true a create button appears instead of save - * @showTitle true or false - */ -function ShipmentForm(args) { - this.id = BUI.id(); - - this.creationMode = false; - this.showTitle = true; - if (args != null) { - if (args.creationMode != null) { - this.creationMode = args.creationMode; - } - if (args.showTitle != null) { - this.showTitle = args.showTitle; - } - } - - this.onSaved = new Event(this); -} - -ShipmentForm.prototype.fillStores = function() { - this.panel.setLoading("Loading Labcontacts from database"); - this.labContactForSendingStore.loadData(BIOSAXS.proposal.getLabcontacts(), false); - this.labContactForReturnStore.loadData(BIOSAXS.proposal.getLabcontacts(), false); - this.panel.setLoading(false); - if (this.shipment != null) { - this.setShipment(this.shipment); - } -}; - -ShipmentForm.prototype.draw = function(targetId) { - this.getPanel().render(targetId); -}; - -ShipmentForm.prototype.setShipment = function(shipment) { - this.shipment = shipment; - var _this = this; - Ext.getCmp(_this.id + "shippingName").setValue(shipment.json.shippingName); - Ext.getCmp(_this.id + "shippingStatus").setValue(shipment.json.shippingStatus); - Ext.getCmp(_this.id + "comments").setValue(shipment.json.comments); - if (shipment.json.sendingLabContactVO != null) { - this.labContactsSendingCombo.setValue(shipment.json.sendingLabContactVO.labContactId); - } - if (shipment.json.returnLabContactVO != null) { - this.labContactsReturnCombo.setValue(shipment.json.returnLabContactVO.labContactId); - } - -}; - -ShipmentForm.prototype._saveShipment = function() { - var _this = this; - var shippingId = null; - if (this.shipment != null) { - shippingId = this.shipment.json.shippingId; - } - var json = { - shippingId : shippingId, - name : Ext.getCmp(_this.id + "shippingName").getValue(), - status : Ext.getCmp(_this.id + "shippingStatus").getValue(), - sendingLabContactId : Ext.getCmp(_this.id + "shipmentform_sendingLabContactId").getValue(), - returnLabContactId : Ext.getCmp(_this.id + "returnLabContactId").getValue(), - returnCourier : Ext.getCmp(_this.id + "returnCourier").getValue(), - courierAccount : Ext.getCmp(_this.id + "courierAccount").getValue(), - BillingReference : Ext.getCmp(_this.id + "BillingReference").getValue(), - dewarAvgCustomsValue : Ext.getCmp(_this.id + "dewarAvgCustomsValue").getValue(), - dewarAvgTransportValue : Ext.getCmp(_this.id + "dewarAvgTransportValue").getValue(), - comments : Ext.getCmp(_this.id + "comments").getValue() - }; - - var dataAdapter = new BiosaxsDataAdapter(); - dataAdapter.onSuccess.attach(function(sender, shipment) { - window.location = BUI.getShippingURL(shipment.shippingId); - }); - - dataAdapter.onError.attach(function(sender, error) { - _this.onError.notify(error); - }); - - /** Cheking params **/ - if (json.name == "") { - BUI.showError("Name field is mandatory"); - return; - } - - if (json.sendingLabContactId == null) { - BUI.showError("Lab contact for sending field is mandatory"); - return; - } - - if (json.returnLabContactId == null) { - BUI.showError("Lab contact for return field is mandatory"); - return; - } - - dataAdapter.createShipment(json.shippingId, json.name, json.status, json.comments, json.sendingLabContactId, json.returnLabContactId, - json.returnCourier, json.courierAccount, json.BillingReference, json.dewarAvgCustomsValue, json.dewarAvgTransportValue); - -}; - -ShipmentForm.prototype.getPanel = function(shipment) { - var _this = this; - this.shipment = shipment; - var required = '*'; - var buttons = []; - - if (_this.creationMode) { - buttons.push({ - text : 'Create', - scope : this, - handler : function() { - _this._saveShipment(); - } - }); - } else { - buttons.push({ - text : 'Save', - scope : this, - handler : function() { - _this._saveShipment(); - } - }); - - } - - this.labContactForSendingStore = Ext.create('Ext.data.Store', { - fields : [ 'cardName', 'labContactId' ] - }); - - this.labContactForReturnStore = Ext.create('Ext.data.Store', { - fields : [ 'cardName', 'labContactId' ] - }); - - // Create the combo box, attached to the states data store - this.labContactsSendingCombo = Ext.create('Ext.form.ComboBox', { - id : _this.id + "shipmentform_sendingLabContactId", - fieldLabel : 'Lab contact for sending', - afterLabelTextTpl : required, - store : this.labContactForSendingStore, - queryMode : 'local', - labelWidth : 200, - displayField : 'cardName', - valueField : 'labContactId' - }); - - this.labContactsReturnCombo = Ext.create('Ext.form.ComboBox', { - id : _this.id + "returnLabContactId", - fieldLabel : 'If No, Lab-Contact for Return', - afterLabelTextTpl : required, - store : this.labContactForReturnStore, - queryMode : 'local', - labelWidth : 200, - displayField : 'cardName', - valueField : 'labContactId', - listeners : { - change : function(x, newValue) { - for ( var i = 0; i < x.getStore().data.items.length; i++) { - if (x.getStore().data.items[i].raw.labContactId == newValue) { - Ext.getCmp(_this.id + "returnCourier").setValue(x.getStore().data.items[i].raw.defaultCourrierCompany); - Ext.getCmp(_this.id + "courierAccount").setValue(x.getStore().data.items[i].raw.courierAccount); - Ext.getCmp(_this.id + "BillingReference").setValue(x.getStore().data.items[i].raw.billingReference); - Ext.getCmp(_this.id + "dewarAvgCustomsValue").setValue(x.getStore().data.items[i].raw.dewarAvgCustomsValue); - Ext.getCmp(_this.id + "dewarAvgTransportValue").setValue(x.getStore().data.items[i].raw.dewarAvgTransportValue); - } - } - } - } - }); - - if (this.panel == null) { - this.panel = Ext.create('Ext.form.Panel', { - bodyPadding : 5, - width : 600, - border : 1, - items : [ { - xtype : 'fieldset', - title : 'Details', - collapsible : false, - defaultType : 'textfield', - layout : 'anchor', - defaults : { - anchor : '100%' - }, - items : [ { - xtype : 'requiredtext', - fieldLabel : 'Shipment Label', - allowBlank : false, - name : 'shippingName', - id : _this.id + 'shippingName', - value : '', - anchor : '50%' - }, { - - xtype : 'textareafield', - name : 'comments', - id : _this.id + 'comments', - fieldLabel : 'Comments', - value : '' - }, { - fieldLabel : 'Status', - readOnly : true, - id : _this.id + 'shippingStatus', - value : 'Opened', - anchor : '50%' - } ] - }, { - xtype : 'fieldset', - title : 'Lab-Contacts', - collapsible : false, - defaultType : 'textfield', - layout : 'anchor', - defaults : { - anchor : '100%' - }, - items : [ this.labContactsSendingCombo, this.labContactsReturnCombo ] - }, { - border : 0, - html : BUI.getWarningHTML("These informations are relevant for all shipments") - }, { - xtype : 'fieldset', - title : 'Courier accounts details for return', - collapsible : false, - layout : 'anchor', - defaults : { - anchor : '100%' - }, - items : [ { - xtype : 'textfield', - labelWidth : 400, - fieldLabel : 'Courier company for return (if ESRF sends a dewar back)', - id : _this.id + 'returnCourier', - value : '' - }, { - xtype : 'textfield', - labelWidth : 400, - fieldLabel : 'Courier account', - id : _this.id + 'courierAccount', - value : '' - }, { - xtype : 'textfield', - labelWidth : 400, - fieldLabel : 'Billing reference', - id : _this.id + 'BillingReference', - value : '' - }, { - xtype : 'numberfield', - labelWidth : 400, - fieldLabel : 'Average Customs value of a dewar (Euro)', - id : _this.id + 'dewarAvgCustomsValue', - value : '' - }, { - xtype : 'numberfield', - labelWidth : 400, - fieldLabel : 'Average Transport value of a dewar (Euro)', - id : _this.id + 'dewarAvgTransportValue', - value : '' - } ] - } ], - buttons : buttons - }); - } - this.fillStores(); - if (this.showTitle) { - this.panel.setTitle('Create a new Shipment'); - } - return this.panel; -}; - -ShipmentForm.prototype.input = function() { - return { - proposal : DATADOC.getProposal_10() - - }; -}; - -ShipmentForm.prototype.test = function(targetId) { - var shipmentForm = new ShipmentForm({ - creationMode : true - - }); - BIOSAXS.proposal = new Proposal(shipmentForm.input().proposal); - shipmentForm.getPanel().render(targetId); -}; - -/** - * #onSaved - */ -function StockSolutionForm(args) { - this.id = BUI.id(); - this.actions = []; - - if (args != null) { - if (args.actions != null) { - this.actions = args.actions; - } - } - this.onSaved = new Event(this); -} - -StockSolutionForm.prototype.getStockSolution = function() { - if (this.stockSolution != null) { - this.stockSolution.concentration = Ext.getCmp(this.id + "stockSolution_concentration").getValue(); - this.stockSolution.storageTemperature = Ext.getCmp(this.id + "stockSolution_storageTemperature").getValue(); - this.stockSolution.volume = Ext.getCmp(this.id + "stockSolution_volume").getValue(); - this.stockSolution.comments = Ext.getCmp(this.id + "stockSolution_comments").getValue(); - this.stockSolution.name = Ext.getCmp(this.id + "stockSolution_name").getValue(); - this.stockSolution.bufferId = this.bufferCombo.getValue(); - - if (this.macromoleculeCombo.getValue() != null) { - this.stockSolution.macromoleculeId = this.macromoleculeCombo.getValue(); - } else { - this.stockSolution.macromolecule3VO = null; - } - - } else { - return { - concentration : Ext.getCmp(this.id + "stockSolution_concentration").getValue(), - storageTemperature : Ext.getCmp(this.id + "stockSolution_storageTemperature").getValue(), - volume : Ext.getCmp(this.id + "stockSolution_volume").getValue(), - comments : Ext.getCmp(this.id + "stockSolution_comments").getValue(), - name : Ext.getCmp(this.id + "stockSolution_name").getValue(), - bufferId : this.bufferCombo.getValue(), - macromoleculeId : this.macromoleculeCombo.getValue() - }; - } - return this.stockSolution; -}; - -StockSolutionForm.prototype.setStockSolution = function(stockSolution) { - if (stockSolution != null) { - if (stockSolution.macromoleculeId != null) { - this.macromoleculeCombo.setValue(stockSolution.macromoleculeId); - } - this.bufferCombo.setValue(stockSolution.bufferId); - Ext.getCmp(this.id + "stockSolution_concentration").setValue(this.stockSolution.concentration); - Ext.getCmp(this.id + "stockSolution_storageTemperature").setValue(this.stockSolution.storageTemperature); - Ext.getCmp(this.id + "stockSolution_volume").setValue(this.stockSolution.volume); - Ext.getCmp(this.id + "stockSolution_name").setValue(this.stockSolution.name); - Ext.getCmp(this.id + "stockSolution_comments").setValue(this.stockSolution.comments); - } -}; - -StockSolutionForm.prototype.getBufferCombo = function() { - this.bufferCombo = BIOSAXS_COMBOMANAGER.getComboBuffers(BIOSAXS.proposal.getBuffers(), { - labelWidth : 120, - margin : '0 0 10 0', - width : 220 - - }); - return this.bufferCombo; -}; - -StockSolutionForm.prototype.getMacromoleculeCombo = function() { - this.macromoleculeCombo = BIOSAXS_COMBOMANAGER.getComboMacromoleculeByMacromolecules(BIOSAXS.proposal.getMacromolecules(), { - labelWidth : 120, - margin : '0 0 10 0', - width : 220 - - }); - return this.macromoleculeCombo; -}; - -StockSolutionForm.prototype.refresh = function() { -}; - -StockSolutionForm.prototype._getTopPanel = function() { - return { - xtype : 'container', - layout : 'hbox', - border : 0, - items : [ { - xtype : 'container', - layout : 'hbox', - items : [ { - xtype : 'container', - flex : 1, - border : false, - layout : 'anchor', - defaultType : 'textfield', - items : [ - - this.getMacromoleculeCombo(), { - xtype : 'requiredtext', - id : this.id + 'stockSolution_name', - fieldLabel : 'Acronym', - labelWidth : 120, - width : 250 - }, { - xtype : 'requiredtext', - id : this.id + 'stockSolution_concentration', - fieldLabel : 'Conc. (mg/ml)', - labelWidth : 120, - width : 250 - }, - - { - id : this.id + 'stockSolution_storageTemperature', - fieldLabel : 'Storage Temp.(C)', - labelWidth : 120, - width : 250 - }, { - xtype : 'requiredtext', - id : this.id + 'stockSolution_volume', - fieldLabel : 'Volume in Well (µl)', - labelWidth : 120, - width : 250 - } ] - } ] - }, { - xtype : 'container', - flex : 1, - layout : 'anchor', - defaultType : 'textfield', - margin : '0 0 0 10', - items : [ this.getBufferCombo() ] - } ] - }; - -}; - -StockSolutionForm.prototype.getPanel = function(stockSolution) { - this.stockSolution = stockSolution; - this.panel = Ext.createWidget({ - xtype : 'container', - layout : 'vbox', - border : 0, - style : { - padding : '10px' - }, - fieldDefaults : { - labelAlign : 'left', - labelWidth : 50 - }, - items : [ this._getTopPanel(stockSolution), { - id : this.id + 'stockSolution_comments', - xtype : 'textareafield', - name : 'comments', - fieldLabel : 'Comments', - labelWidth : 120, - width : '100%' - } ] - }); - - this.setStockSolution(stockSolution); - return this.panel; -}; - -StockSolutionForm.prototype.input = function() { - return { - stock : { - "stockSolutionId" : 6, - "proposalId" : 3124, - "macromoleculeId" : 5933, - "bufferId" : 811, - "instructionSet3VO" : null, - "boxId" : 305861, - "storageTemperature" : "20", - "volume" : "300", - "concentration" : "1.2", - "comments" : "Buffer EDTA with A", - "name" : "A_EDTA_1.2", - "samples" : [], - "buffer" : "EDTA", - "macromolecule" : "A" - }, - proposal : new MeasurementGrid().input().proposal - }; -}; - -StockSolutionForm.prototype.test = function(targetId) { - var stockSolutionForm = new StockSolutionForm(); - BIOSAXS.proposal = new Proposal(stockSolutionForm.input().proposal); - var panel = stockSolutionForm.getPanel(new Shipment(stockSolutionForm.input().stock)); - panel.render(targetId); -}; - - -BoxWhiskerGraph.prototype.cleanArray = GenericGraph.prototype.cleanArray; -BoxWhiskerGraph.prototype.plotAxes = GenericGraph.prototype.plotAxes; -BoxWhiskerGraph.prototype.plotRuler = GenericGraph.prototype.plotRuler; -BoxWhiskerGraph.prototype.drawSVGVerticalText = GenericGraph.prototype.drawSVGVerticalText; -BoxWhiskerGraph.prototype.getClassColor = GenericGraph.prototype.getClassColor; -BoxWhiskerGraph.prototype.getDimensions = GenericGraph.prototype.getDimensions; -BoxWhiskerGraph.prototype.calculate = GenericGraph.prototype.calculate; -BoxWhiskerGraph.prototype.getMedian = GenericGraph.prototype.getMedian; -BoxWhiskerGraph.prototype.pointToPixel = GenericGraph.prototype.pointToPixel; -BoxWhiskerGraph.prototype.maxValueWhisker = GenericGraph.prototype.maxValueWhisker; -BoxWhiskerGraph.prototype.refresh = GenericGraph.prototype.refresh; - -/** - * Subclass of GenericGraph - * - * @maxBoxWidth - */ -function BoxWhiskerGraph(args){ - this.maxBoxWidth = 25; - - if (args == null){ - args = new Object(); - } - args["plotHorizontalByCluster"] = true; - - GenericGraph.call(this, args); - - if (args.maxBoxWidth != null){ - this.maxBoxWidth = args.maxBoxWidth; - } -}; - - - -/** -There are several different methods for calculating quartiles.[1] This calculator uses a method described by Moore and McCabe to find quartile values. -The same method also used by The TI-83 to calculate quartile values. -With this method, the first quartile is the median of the numbers below the median, the third quartile is the median of the numbers above the median. - -http://www.miniwebtool.com/quartile-calculator/ -http://www.alcula.com/calculators/statistics/box-plot/ -**/ -BoxWhiskerGraph.prototype.getQ1 = function(array){ - array = array.slice(0, array.length/2); - return this.getMedian(array); -}; - -BoxWhiskerGraph.prototype.getQ3 = function(array){ - array = array.slice((array.length + 1)/2); - return this.getMedian(array); - -}; - -BoxWhiskerGraph.prototype.getQ2 = function(array){ - return this.getMedian(array); -}; - -BoxWhiskerGraph.prototype.getBelowOutliers = function(belowLimit, array){ - var points = new Array(); - for (var i = 0; i < array.length; i++){ - if (array[i] <= belowLimit){ - points.push(array[i]); - } - } - return points; -}; - -BoxWhiskerGraph.prototype.getAboveOutliers = function(aboveLimit, array){ - var points = new Array(); - for (var i = 0; i < array.length; i++){ - if (array[i] >= aboveLimit){ - points.push(array[i]); - } - } - return points; -}; - - -BoxWhiskerGraph.prototype.minValueWhisker = function(belowLimit, q1, array){ - var points = new Array(); - - for (var i = 0; i < array.length; i++){ - if ((array[i] < q1) && (array[i]) > belowLimit){ - points.push(array[i]); - } - } - - if (points.length > 0){ - points.sort(function(a, b){return a - b;}); - return points[0]; - } - return null; -}; - -BoxWhiskerGraph.prototype.isNumber = function(value){ - if (value=="") return false; - - var d = parseInt(value); - if (!isNaN(d)) return true; else return false; - -}; - -BoxWhiskerGraph.prototype.plotBoxWhisker = function(boxProperties){ - if (this.maxBoxWidth != null){ - if (boxProperties.width > this.maxBoxWidth){ - boxProperties.x = boxProperties.x + (boxProperties.width/2) - (this.maxBoxWidth/2); - boxProperties.width = this.maxBoxWidth; - } - - } - - if (this.plotPoints){ - for(var i = 0; i < boxProperties.values.length; i++){ - var value = boxProperties.values[i]; - var toPixel = this.pointToPixel(value, boxProperties); - SVG.drawCircle(boxProperties.x + (boxProperties.width/2) + 2, toPixel, this.pointRadius, this.svg, [["fill", "green"], ["fill-opacity", this.fillOpacityPoint],['stroke-opacity', this.strokeOpacityPoint], ["stroke", "black"]]); - } - } - - - var boxColor = this.getClassColor(boxProperties.name); - var result = this.calculate(boxProperties.values); - /** Q1 **/ - - if (this.isNumber(result.Q1)){ - SVG.drawLine(boxProperties.x, this.pointToPixel(result.Q1, boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result.Q1, boxProperties), this.svg, [["stroke", boxColor]]); - } - /** Q2 **/ - if (this.isNumber(result.Q2)){ - SVG.drawLine(boxProperties.x, this.pointToPixel(result.Q2, boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result.Q2, boxProperties), this.svg, [["stroke", "blue"], ["stroke-width", "2"]]); - } - - /** Q3 **/ - if (this.isNumber(result.Q3)){ - SVG.drawLine(boxProperties.x, this.pointToPixel(result.Q3, boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result.Q3, boxProperties), this.svg, [["stroke", boxColor]]); - } - - /** Concenting Q1 and Q3 **/ - if (this.isNumber(result.Q1)&&this.isNumber(result.Q3)){ - SVG.drawLine(boxProperties.x, this.pointToPixel(result.Q1, boxProperties), boxProperties.x, this.pointToPixel(result.Q3, boxProperties), this.svg, [["stroke", boxColor]]); - SVG.drawLine(boxProperties.x + boxProperties.width, this.pointToPixel(result.Q1, boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result.Q3, boxProperties), this.svg, [["stroke", boxColor]]); - } - - /** min-whisker **/ - if (result["min-whisker"] != null){ - if (this.isNumber(result.Q1)){ - SVG.drawLine(boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result.Q1, boxProperties), boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result["min-whisker"], boxProperties), this.svg, [["stroke", boxColor]]); - } - SVG.drawLine(boxProperties.x,this.pointToPixel(result["min-whisker"], boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result["min-whisker"], boxProperties) , this.svg, [["stroke", boxColor]]); - - } - - /** max-whisker **/ - if (result["max-whisker"] != null){ - if (this.isNumber(result.Q3)){ - SVG.drawLine(boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result.Q3, boxProperties), boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result["max-whisker"], boxProperties), this.svg, [["stroke", boxColor]]); - } - SVG.drawLine(boxProperties.x , this.pointToPixel(result["max-whisker"], boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result["max-whisker"], boxProperties), this.svg, [["stroke", boxColor]]); - - } - - /** outliners **/ - if (result["above-outliers"] != null){ - for (var point in result["above-outliers"]){ - SVG.drawCircle(boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result["above-outliers"][point], boxProperties), this.pointRadius, this.svg, [["fill", "red"], ["fill-opacity", "1"]]); - //SVG.drawText(boxProperties.x + (boxProperties.width/2) - 2, this.pointToPixel(result["above-outliers"][point], boxProperties) + 2, "x",this.svg, [["fill", "black"], ["font-size", "x-small"]]); - } - } - if (result["below-outliers"] != null){ - for (var point in result["below-outliers"]){ - SVG.drawCircle(boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result["below-outliers"][point], boxProperties), this.pointRadius, this.svg, [["fill", "red"], ["fill-opacity", "1"]]); - //SVG.drawText(boxProperties.x + (boxProperties.width/2) - 2, this.pointToPixel(result["below-outliers"][point], boxProperties) + 2, "x",this.svg, [["fill", "black"], ["font-size", "x-small"]]); - } - } -}; - - - -BoxWhiskerGraph.prototype.plotClusterTitles = function(properties){ - /** Cluster Titles **/ - var posX = this.left + this.rulerWidth; - var data = this.data; - for(var i = 0; i < data.clusters.length; i++ ){ - /** title for the clusters **/ - posX = posX + this.interClustersSpace; - - /** Drawing title of classes **/ - var cluster = data.clusters[i]; - var posXClasses = posX; - for(var j = 0; j < cluster.classes.length; j++){ - //SVG.drawRectangle(posXClasses, this.height - (this.bottom + this.clusterTitleHeight + this.rulerHeight), properties.classWidth, this.rulerHeight, this.svg, [["fill", "green"]]); -// SVG.drawText(posXClasses + 1/6*properties.classWidth, this.height - (this.bottom + this.clusterTitleHeight + (this.rulerHeight*1/4)), cluster.classes[j].name, this.svg, [["style", "font-size:xx-small"]]); - var color = cluster.classes[j].color; - this.drawSVGVerticalText(posXClasses + 1/2*(properties.classWidth), this.height - (this.bottom - this.clusterTitleHeight + (this.rulerHeight)), cluster.classes[j].name , [["style", "font-size:x-small;"], ["fill", color]]); - - // SVG.drawRectangle(posXClasses, this.height - (this.bottom + this.clusterTitleHeight), properties.classWidth, 2, this.svg, [["fill", "black"]]); - posXClasses = posXClasses + properties.classWidth + this.interClassesSpace; - } - - var clusterTitleSpace = (data.clusters[i].classes.length * properties.classWidth) + ((data.clusters[i].classes.length - 1) * this.interClassesSpace); - //SVG.drawRectangle(posX, this.height - (this.bottom + this.clusterTitleHeight), clusterTitleSpace, this.clusterTitleHeight, this.svg, [["fill", "pink"]]); - SVG.drawRectangle(posX, this.height - (this.clusterTitleHeight+this.bottom), clusterTitleSpace, 1, this.svg, []); - -// var transform = ["translate", "(" + posX + 1/3*clusterTitleSpace +", " + this.height - (this.bottom + (this.clusterTitleHeight*1/4)) +")"], ["transform", "rotate(180)"]; -// var transform = ["transform", "translate(" + (posX + 1/3*clusterTitleSpace) +", " + (this.height - (this.bottom + (this.clusterTitleHeight*1/4))) + "), rotate(-90) "]; -// this.drawSVGVerticalText(posX + 1/3*clusterTitleSpace, this.height - (this.bottom + (this.clusterTitleHeight*1/4)),data.clusters[i].name, [["style", "font-size:x-small"]]); - SVG.drawText(posX , this.height - (this.bottom + (this.clusterTitleHeight*1/4)),data.clusters[i].name ,this.svg, [["style", "font-size:x-small"]]); - posX = posX + clusterTitleSpace; - } -}; - -BoxWhiskerGraph.prototype.plotWhisters = function(data, properties){ - var colors = ["yellow", "orange", "green"]; - var posX = this.left + this.rulerWidth; - for(var i = 0; i < data.clusters.length; i++ ){ - var cluster = data.clusters[i]; - /** inter cluster space **/ - //SVG.drawRectangle(posX, this.top, this.interClustersSpace, this.height - this.top - this.bottom - this.clusterTitleHeight - this.rulerHeight, this.svg, [["fill", "black"]]); - posX = posX + this.interClustersSpace; - - for (var j = 0; j < cluster.classes.length; j ++){ - - //SVG.drawRectangle(posX, this.top, properties.classWidth, this.height - this.top - this.bottom - this.clusterTitleHeight - this.rulerHeight, this.svg, [["fill", colors[j]]]); - this.plotBoxWhisker( - { - name : cluster.classes[j].name, - values : cluster.classes[j].values, - minPoint : properties.minPoint, - maxPoint : properties.maxPoint, - x : posX, - y : this.top, - width : properties.classWidth, - height : this.height - this.top - this.bottom - this.clusterTitleHeight - this.rulerHeight - - - } - ); - posX = posX + properties.classWidth; - //SVG.drawRectangle(posX, this.top, this.interClassesSpace, this.height - this.top - this.bottom - this.clusterTitleHeight - this.rulerHeight, this.svg, [["fill", "black"]]); - if (j < cluster.classes.length - 1){ - posX = posX + this.interClassesSpace; - } - } - } -}; - -BoxWhiskerGraph.prototype.draw = function(targetId, data){ - this.targetId = targetId; - var properties = (this.getDimensions(data)); - this.svg = SVG.createSVGCanvas(document.getElementById(this.targetId), [["width", this.width], ["height", this.height]]); - this.plotAxes(properties); - this.plotClusterTitles(properties); - this.plotWhisters(data,properties); -}; - -BoxWhiskerGraph.prototype.input = function(){ - return DATADOC.getBoxWhikerData(); -}; - -BoxWhiskerGraph.prototype.test = function(targetId){ - var plot = new BoxWhiskerGraph( - { - targetId : targetId, - height : 350, - width : 450, - maxBoxWidth : 25 - } - ); - plot.refresh(this.input()); -}; - - - - - - - -function DataSet(){ - this.json = null; - -}; - - -DataSet.prototype.loadFromJSON = function(json){ - if(json != null) { - if(this.validate(json)) { - this.json = json; - } - } -}; - - -DataSet.prototype.toJSON = function(json){ - return this.json; -}; - - -/** Abstract method to be override on childs classes **/ -DataSet.prototype.validate = function(json){ - if (true){ - return true; - } - /*else{ - throw "Data validation failed"; - }*/ -}; - - - - -Edge.prototype.getName = GraphItem.prototype.getName; -Edge.prototype.setName = GraphItem.prototype.setName; -Edge.prototype.getId = GraphItem.prototype.getId; - -function Edge(id, name, nodeSource, nodeTarget, args){ - GraphItem.prototype.constructor.call(this, id, name, args); - - this.sourceNode = nodeSource; - this.targetNode = nodeTarget; - -}; - -Edge.prototype.toJSON = function(){ - return {"index": this.id,"sourceIndex":this.sourceNode.getId(),"targetIndex":this.targetNode.getId(),"args":this.args}; -}; - -Edge.prototype.getNodeSource = function(){ - return this.sourceNode; -}; - -Edge.prototype.getNodeTarget = function(){ - return this.targetNode; -}; - -Edge.prototype.remove = function(){ - //Remove edge object in the nodes - this.getNodeSource().removeEdge(this); - this.getNodeTarget().removeEdge(this); - - this.deleted.notify(this); -}; - - -EdgeGraphFormatter.prototype.setProperties = ItemGraphFormatter.prototype.setProperties; -EdgeGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; -EdgeGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; -EdgeGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; -EdgeGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; -EdgeGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; -EdgeGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; -EdgeGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; -EdgeGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; - -function EdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ - ItemGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); - - this.getDefault().args.type = "EdgeGraphFormatter"; -}; - - - - -LineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; -LineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; -LineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; -LineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; -LineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; -LineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; -LineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; -LineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; -LineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; - -function LineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ - EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); - this.args.type = "LineEdgeGraphFormatter"; -}; - -/** DIRECTED **/ -DirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; -DirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; -DirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; -DirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; -DirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; -DirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; -DirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; -DirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; -DirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; - -function DirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ - EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); - this.args.type = "DirectedLineEdgeGraphFormatter"; - this.args.arrowSize = "3"; -}; -DirectedLineEdgeGraphFormatter.prototype.getArrowSize = function(){ - return this.args.arrowSize; -}; - -OdirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; -OdirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; -OdirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; -OdirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; -OdirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; -OdirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; -OdirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; -OdirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; -OdirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; - -function OdirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ - EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); - this.args.type = "DirectedLineEdgeGraphFormatter"; - this.args.arrowSize = "3"; -}; - -OdirectedLineEdgeGraphFormatter.prototype.getArrowSize = function(){ - return this.args.arrowSize; -}; - - -/** CUT (inhibition) **/ -CutDirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; -CutDirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; -CutDirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; -CutDirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; -CutDirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; -CutDirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; -CutDirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; -CutDirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; -CutDirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; - -function CutDirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ - EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); - this.args.type = "CutDirectedLineEdgeGraphFormatter"; -}; - - - - -BezierEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; -BezierEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; -BezierEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; -BezierEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; -BezierEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; -BezierEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; -BezierEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; -BezierEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; -BezierEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; -BezierEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; - -function BezierEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ - EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); - this.args.type = "BezierEdgeGraphFormatter"; -}; - - - -DotDirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; -DotDirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; -DotDirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; -DotDirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; -DotDirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; -DotDirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; -DotDirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; -DotDirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; -DotDirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; - -function DotDirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ - EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); - this.args.type = "DotDirectedLineEdgeGraphFormatter"; -}; - - -OdotDirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; -OdotDirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; -OdotDirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; -OdotDirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; -OdotDirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; -OdotDirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; -OdotDirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; -OdotDirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; -OdotDirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; - -function OdotDirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ - EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); - this.args.type = "OdotDirectedLineEdgeGraphFormatter"; -}; - - - -function GraphDataset(){ - DataSet.prototype.constructor.call(this); - this.edges = new Object(); - this.vertices = new Object(); - this.verticesIndex = new Object(); - - //Events - this.newVertex = new Event(this); - this.vertexNameChanged = new Event(this); - this.vertexDeleted = new Event(this); - - this.newEdge = new Event(this); - this.edgeNameChanged = new Event(this); - this.edgeDeleted = new Event(this); - - this.json = new Object(); - this.json.vertices = new Array(); - this.json.edges = new Array(); - this.json.relations = new Array(); -}; - -GraphDataset.prototype.loadFromJSON = DataSet.prototype.loadFromJSON; -GraphDataset.prototype.toJSON = DataSet.prototype.toJSON; -GraphDataset.prototype.validate = DataSet.prototype.validate; - -/** Devuelve el numero de edges incidentes sobre el nodo con mas edges **/ -GraphDataset.prototype.getMaxClass = function(){ - var maxClassNode = 0; - for ( var node in this.vertices) { - if (this.vertices[node].getEdgesCount() > maxClassNode){ - maxClassNode = this.vertices[node].getEdgesCount(); - } - } - return maxClassNode; -}; - -/** Devuelve el numero de edges incidentes sobre el nodo con mas edges **/ -GraphDataset.prototype.getMinClass = function(){ - var minClassNode = Math.min(); - for ( var node in this.vertices) { - if (this.vertices[node].getEdgesCount() < minClassNode){ - minClassNode = this.vertices[node].getEdgesCount(); - } - } - return minClassNode; -}; - -GraphDataset.prototype.getVertexByName = function(nodeName){ - var results = new Array(); - - for (var vertexId in this.verticesIndex[nodeName]){ - var vertexByid = this.getVertexById(this.verticesIndex[nodeName][vertexId]); - results.push(vertexByid); - //* añadido nuevo porque fallaba el anterior codigo - return vertexByid - } - - if (results <= 1){ - return this.getVertexById(this.verticesIndex[nodeName]); - } - else{ - return results; - } -}; - -GraphDataset.prototype.getVertexById = function(id){ - return this.vertices[id]; -}; - -GraphDataset.prototype.toSIF = function(){ - var sifDataAdapter = new SifFileDataAdapter(); - return sifDataAdapter.toSIF(this); -}; - -GraphDataset.prototype.toSIFID = function(){ - var sifDataAdapter = new SifFileDataAdapter(); - return sifDataAdapter.toSIFID(this); -}; - -GraphDataset.prototype.toDOT = function(){ - var dotFileDataAdapter = new DotFileDataAdapter(); - return dotFileDataAdapter.toDOT(this); -}; - -GraphDataset.prototype.toDOTID = function(){ - var dotFileDataAdapter = new DotFileDataAdapter(); - return dotFileDataAdapter.toDOTID(this); -}; - -GraphDataset.prototype._addNode = function(nodeName, args){ - return new Vertex(this._getVerticesCount()-1, nodeName, args); -}; - -GraphDataset.prototype.addNode = function(nodeName, args){ - this.json.vertices.push(nodeName); - this._addVerticesIndex(nodeName, this._getVerticesCount() - 1); - var vertex = this._addNode(nodeName, args); - this.vertices[this._getVerticesCount()-1] = vertex; - this._setNodeEvents(vertex); - this.newVertex.notify(vertex); -}; - -GraphDataset.prototype._addVerticesIndex = function(nodeName, id){ - if (this.verticesIndex[nodeName] == null){ - this.verticesIndex[nodeName] = new Array(); - } - this.verticesIndex[nodeName].push(id); -}; - -GraphDataset.prototype.addEdge = function(edgeName, nodeSourceId, nodeTargetId, args){ - this.json.edges.push(edgeName); - var nodeSource = this.getVertexById(nodeSourceId); - var nodeTarget = this.getVertexById(nodeTargetId); - var index = this.getEdgesCount() - 1; - this.edges[index] = new Edge(index, edgeName, nodeSource, nodeTarget, args); - this.json.relations.push({"index": index, "sourceIndex": nodeSourceId, "targetIndex": nodeTargetId, "args": args }); - - nodeSource.addEdge(this.edges[index]); - nodeTarget.addEdge(this.edges[index]); - this._setEdgeEvents(this.edges[index]); - this.newEdge.notify(this.edges[index]); -}; - -GraphDataset.prototype.getVertices = function(){ - return this.vertices; -}; - -GraphDataset.prototype.getEdges = function(){ - return this.edges; -}; - -GraphDataset.prototype.getEdgeById = function(edgeId){ - return this.edges[edgeId]; -}; - -GraphDataset.prototype._getVerticesCount = function(){ - return this.json.vertices.length; -}; - - -GraphDataset.prototype.getVerticesCount = function(){ - var count = 0; - for ( var vertex in this.getVertices()) { - count ++; - } - return count; -}; - - -GraphDataset.prototype.getEdgesCount = function(){ - return this.json.edges.length; -}; - -GraphDataset.prototype.init = function(){ - this.edges = new Object(); - this.vertices = new Object(); -}; - -GraphDataset.prototype._setNodeEvents = function(node){ - var _this = this; - //NODE EVENTS - node.deleted.attach(function (sender, node){ - _this._removeNode(node); - }); - - node.nameChanged.attach(function (sender, args){ - var item = args.item; - var newName = item.name; - var indexes = _this.verticesIndex[args.previousName]; - for(var i = 0; i < indexes.length; i++){ - if(indexes[i] == item.id) - indexes.splice(i,1); - } - if(indexes.length == 0){ - delete _this.verticesIndex[args.previousName]; - } - _this._addVerticesIndex(newName, item.id); - _this.json.vertices[item.id] = newName; - _this.vertexNameChanged.notify(args); - }); -}; - -GraphDataset.prototype._setEdgeEvents = function(edge){ - var _this = this; - //EDGE EVENTS - edge.nameChanged.attach(function (sender, edge){ - _this.edgeNameChanged.notify(edge); - - }); - - edge.deleted.attach(function (sender, edge){ - _this._removeEdge(edge); - }); -}; - -GraphDataset.prototype._connectVerticesByName = function(nodeNameSource, nodeNameTarget){ - var source = this.getVertexByName(nodeNameSource); - var target = this.getVertexByName(nodeNameTarget); - - if ((source != null)&&(target!=null)){ - this.addEdge(source.getName() +"_" + target.getName(), source.getId(), target.getId(), {}); - } - else{ - if (source == null){ - console.log("No encontrado: " + nodeNameSource) - } - if (target == null){ - console.log("No encontrado: " + nodeNameTarget) - } - } -}; - -GraphDataset.prototype.loadFromJSON = function(json){ - var json = json; - this.init(); - this.json = new Object(); - this.json.vertices = new Array(); - this.json.edges = new Array(); - this.json.relations = new Array(); - - for ( var i = 0; i < json.nodes.length; i++) { - if (json.nodes[i] != null){ - var name = json.nodes[i]; - this.addNode(name); - } - else{ - this.json.vertices.push(null); - } - } - - for ( var i = 0; i < json.edges.length; i++) { - if (json.edges[i] != null){ - if (json.relations[i] != null){ - var name = json.edges[i]; - this.addEdge(name, json.relations[i].sourceIndex, json.relations[i].targetIndex, json.relations[i].args); - } - } - else{ - this.json.edges.push(null); - this.json.relations.push(null); - } - } -}; - -GraphDataset.prototype.prettyPrint = function(){ - for ( var node in this.vertices) { - console.log(this.vertices[node].getName() ); - for ( var j = 0; j < this.vertices[node].getEdgesIn().length; j++) { - console.log(" --> " + this.vertices[node].getEdgesIn()[j].getNodeTarget().getName() ); - } - } -}; - -GraphDataset.prototype._removeEdge = function(edge){ - this.json.edges[edge.getId()] = null; - this.json.relations[edge.getId()] = null; - - delete this.edges[edge.getId()]; - this.edgeDeleted.notify(edge); - - -}; - -GraphDataset.prototype._removeNode = function(node){ - this.json.vertices[node.getId()] = null; - delete this.vertices[node.getId()]; - this.vertexDeleted.notify(node); -}; - -GraphDataset.prototype.toJSON = function(){ - var json = new Object(); - var nodes = new Array(); - json.nodes = this.json.vertices; //nodes; - json.edges = this.json.edges; //edges; - json.relations = this.json.relations; - return json; -}; - -GraphDataset.prototype.clone = function(){ - var dsDataset = new GraphDataset(); - dsDataset.loadFromJSON(this.toJSON()); - return dsDataset; -}; -//GraphDataset.prototype.test = function(){ -// this.loadFromJSON(this.toJSON()); -//}; - -function labels(){ - var names = new Array(); - - var dataset = interactomeViewer.graphEditorWidget.dataset; - var layout = interactomeViewer.graphEditorWidget.layout; - - for ( var vertexId in interactomeViewer.graphEditorWidget.dataset.getVertices()) { - names.push(interactomeViewer.graphEditorWidget.dataset.getVertexById(vertexId).getName()); - } - - var sorted = (names.sort()); - console.log(sorted) - var distance = 0.01; - var altura = 0.6; - for ( var i = 0; i < names.length; i++) { - var id =dataset.getVertexByName(names[i]).getId(); - - layout.getNodeById(id).setCoordenates(distance, altura); - - - distance = parseFloat(distance) + parseFloat(0.03); - - altura = parseFloat(altura) + parseFloat(0.02); - - if (parseFloat(altura) == 0.9800000000000003){ - - altura = 0.6; - distance = distance - 0.51; - } - - } - - -}; - -function GraphItem(id, name, args){ - this.id = id; - this.name = name; - this.type = "NONE"; - - this.args = new Object(); - - - if (args!=null){ - this.args = args; - if (args.type !=null){ - this.type = args.type; - } - } - - //Events - this.nameChanged = new Event(this); - this.deleted = new Event(this); -} - -GraphItem.prototype.getName = function(){ - return this.name; -}; - -GraphItem.prototype.getId = function(){ - return this.id; -}; - -GraphItem.prototype.setName = function(name){ - var oldName = this.getName(); - this.name = name; - this.nameChanged.notify({"item": this, "previousName" : oldName}); -}; - - - - - -function LayoutDataset(){ - this.dataset = null; - this.vertices = new Object(); - this.changed = new Event(this); - - - this.args = new Object(); - - //RANDOM, CIRCLE - this.args.type = "CIRCLE"; -}; - -LayoutDataset.prototype.loadFromJSON = function(dataset, json){ - var _this = this; - this.vertices = new Object(); - this.dataset = dataset; //new GraphDataset(); - for ( var vertex in json) { - this.vertices[vertex] = new NodeLayout(vertex, json[vertex].x, json[vertex].y); - this.vertices[vertex].changed.attach(function (sender, item){ - _this.changed.notify(item); - }); - } - this._attachDatasetEvents(); -}; - - -LayoutDataset.prototype.toJSON = function(){ - var serialize = new Object(); - for ( var vertex in this.vertices) { - serialize[vertex] = new Object(); - serialize[vertex].x = this.vertices[vertex].x; - serialize[vertex].y = this.vertices[vertex].y; - } - serialize.dataset = new Object(); - serialize.dataset =this.dataset.toJSON(); - return serialize; -}; - -LayoutDataset.prototype.dataBind = function(graphDataset){ - this.dataset = graphDataset; - this._attachDatasetEvents(); - this._calculateLayout(); -}; - -LayoutDataset.prototype._removeVertex = function(vertexId){ - delete this.vertices[vertexId]; -}; - -LayoutDataset.prototype._attachDatasetEvents = function(){ - var _this = this; - - this.dataset.vertexDeleted.attach(function (sender, item){ - _this._removeVertex(item.getId()); - }); - - this.dataset.newVertex.attach(function (sender, item){ - _this.vertices[item.getId()] = new NodeLayout(item.getId(), 0.5, 0.5); - _this.vertices[item.getId()].changed.attach(function (sender, item){ - _this.changed.notify(item); - }); - }); -}; - -LayoutDataset.prototype.getType = function(){ - return this.args.type; -}; - -LayoutDataset.prototype._calculateLayoutVertices = function(type, count){ - - if (type == "CIRCLE"){ - var radius = 0.4; - var centerX = 0.5; - var centerY = 0.5; - var verticesCoordinates = new Array(); - for(var i = 0; i < count; i++){ - x = centerX + radius * Math.sin(i * 2 * Math.PI/count); - y = centerY + radius * Math.cos(i * 2 * Math.PI/count); - verticesCoordinates.push({'x':x,'y':y}); - } - return verticesCoordinates; - } -}; - - -LayoutDataset.prototype._calculateLayout = function(){ - var _this = this; - if (this.getType() == "RANDOM"){ - for ( var vertex in this.dataset.getVertices()) { - if (this.vertices[vertex] == null){ - this.vertices[vertex] = new NodeLayout(vertex, 0, 0); - } - this.vertices[vertex].setCoordinates(Math.random(), Math.random()); - this.vertices[vertex].changed.attach(function (sender, item){ - _this.changed.notify(item); - }); - } - } - - if ( this.getType() == "CIRCLE"){ - - var count = this.dataset._getVerticesCount(); - var verticesCoordinates = this._calculateLayoutVertices(this.getType(), count); - - var aux = 0; - for ( var vertex in this.dataset.getVertices()) { - if (this.vertices[vertex] == null){ - this.vertices[vertex] = new NodeLayout(vertex, 0, 0); - } - this.vertices[vertex].setCoordinates(verticesCoordinates[aux].x, verticesCoordinates[aux].y);//{"x":, "y":}; - aux++; - this.vertices[vertex].changed.attach(function (sender, item){ - _this.changed.notify(item); - }); - } - } - - - if (this.getType() == "SQUARE"){ - - var count = this.dataset._getVerticesCount(); - var xMin = 0.1; - var xMax = 0.9; - var yMin = 0.1; - var yMax = 0.9; - - var rows = Math.sqrt(count); - var step = (xMax - xMin) / rows; - - var verticesCoordinates = new Array(); - for(var i = 0; i < rows; i ++){ - for ( var j = 0; j < rows; j++) { - x = i * step + xMin; - y = j * step + yMin; - verticesCoordinates.push({'x':x,'y':y}); - } - } - - var aux = 0; - for ( var vertex in this.dataset.getVertices()) { - if (this.vertices[vertex] == null){ - this.vertices[vertex] = new NodeLayout(vertex, 0, 0); - } - this.vertices[vertex].setCoordinates(verticesCoordinates[aux].x, verticesCoordinates[aux].y);//{"x":, "y":}; - aux++; - this.vertices[vertex].changed.attach(function (sender, item){ - _this.changed.notify(item); - }); - } - } - -}; - -LayoutDataset.prototype.getNodeById = function(id){ - return this.vertices[id]; -}; - -LayoutDataset.prototype.getVerticesByArea = function(x1, y1, x2, y2){ - var vertices = new Array(); - for ( var vertex in this.dataset.getVertices()) { - if ((this.vertices[vertex].x >= x1)&&(this.vertices[vertex].x <= x2)){ - if ((this.vertices[vertex].y >= y1)&&(this.vertices[vertex].y <= y2)){ - vertices.push(this.vertices[vertex]); - } - } - } - return vertices; -}; - - - - -LayoutDataset.prototype.getLayout = function(type){ - - if (type == "CIRCLE"){ - this.args.type = "CIRCLE"; - this._calculateLayout(); - return; - } - - if (type == "SQUARE"){ - this.args.type = "SQUARE"; - this._calculateLayout(); - return; - } - - if (type == "RANDOM"){ - this.args.type = "RANDOM"; - this._calculateLayout(); - return; - } - - - var dotText = this.dataset.toDOTID(); - var url = "http://bioinfo.cipf.es/utils/ws/rest/network/layout/"+type+".coords"; - var _this = this; - - $.ajax({ - async: true, - type: "POST", - url: url, - dataType: "text", - data: { - dot :dotText - }, - cache: false, - success: function(data){ - var response = JSON.parse(data); - for ( var vertexId in response) { - _this.vertices[vertexId].setCoordinates(response[vertexId].x, response[vertexId].y); - } - } - }); - -// $.ajax({ -// async: true, -// type: "POST", -// url: url, -// dataType: "script", -// data: { -// dot :dotText -// }, -// cache: false, -// success: function(data){ -// var response = JSON.parse(data); -// for ( var vertexId in response) { -// _this.vertices[vertexId].setCoordinates(response[vertexId].x, response[vertexId].y); -// } -// } -// }); - -}; - -function NodeLayout(id, x, y, args){ - this.id = id; - this.x = x; - this.y = y; - this.changed = new Event(this); -}; - -NodeLayout.prototype.getId = function(id){ - return this.id; -}; - -NodeLayout.prototype.setCoordinates = function(x, y){ - this.x = x; - this.y = y; - this.changed.notify(this); -}; - - - -function NetworkDataSetFormatter(vertexFormatProperties, defaultEdgeProperties, args){ - DataSet.prototype.constructor.call(this); - - this.args = new Object(); - - this.vertices = new Object(); - this.edges = new Object(); - this.dataset = null; - this.maxClass = 0; - this.minClass = 0; - - /** Coordenates with default Setting */ - this.args.width = 1100; - this.args.height = 500; - - /** Optional parameters */ - this.args.backgroundColor = "#FFFFFF"; - this.args.backgroundImage = null; - this.args.backgroundImageHeight = null; - this.args.backgroundImageWidth = null; - this.args.backgroundImageX = null; - this.args.backgroundImageY = null; - - - this.args.balanceNodes = false; - this.args.nodesMaxSize = 3; - this.args.nodesMinSize = 0.5; - - - /** Zoom **/ - this.args.zoomScale = 1; - this.args.zoomScaleStepFactor = 0.4; - - if (args != null){ - if (args.backgroundImage != null){ - this.args.backgroundImage = args.backgroundImage; - } - - if (args.width != null){ - this.args.width = args.width; - } - - if (args.height != null){ - this.args.height = args.height; - this.args.svgHeight = args.height; - } - - if (args.svgHeight != null){ - this.args.svgHeight = args.svgHeight; - } - - if (args.backgroundColor != null){ - this.args.backgroundColor = args.backgroundColor; - } - - if(args.balanceNodes != null){ - this.args.balanceNodes = args.balanceNodes; - } - - if(args.nodesMaxSize != null){ - this.args.nodesMaxSize = args.nodesMaxSize; - } - if(args.nodesMinSize != null){ - this.args.nodesMinSize = args.nodesMinSize; - } - } - - this.args.defaultEdgeProperties = {"fill":"#000000", "radius":"1", "stroke":"#000000", "size":1, "title":{"fontSize":10, "fontColor":"#000000"}}; - this.args.vertexFormatProperties = { "fill":"#000000", "stroke":"#000000", "stroke-opacity":"#000000"}; - - if (vertexFormatProperties!= null){ - this.args.vertexFormatProperties = vertexFormatProperties; - } - if (defaultEdgeProperties!= null){ - this.args.defaultEdgeProperties = defaultEdgeProperties; - } - - /** Events **/ - this.changed = new Event(this); - this.edgeChanged = new Event(this); - this.resized = new Event(this); - this.backgroundImageChanged= new Event(this); - this.backgroundColorChanged= new Event(this); -}; - -NetworkDataSetFormatter.prototype.loadFromJSON = function(dataset, json){ - this.args = new Object(); - this.vertices = new Object(); - this.args = json; - this._setDataset(dataset); - var _this = this; - - for ( var vertex in json.vertices) { - this.addVertex(vertex, json.vertices[vertex]); - } - - for ( var edgeId in json.edges) { - this.addEdge(edgeId, json.edges[edgeId]); - } -}; - - -NetworkDataSetFormatter.prototype.toJSON = function(){ - - -// this.args.vertices = new Object(); -// this.args.edges = new Object(); -// -// for ( var vertex in this.vertices) { -// this.args.vertices[vertex] = this.getVertexById(vertex).toJSON(); -// } -// for ( var edge in this.edges) { -// this.args.edges[edge] = this.getEdgeById(edge).toJSON(); -// } -// -// return (this.args); - - - var serialize = new Object(); - serialize = JSON.parse(JSON.stringify(this.args)); - serialize.vertices = new Object(); - serialize.edges = new Object(); - - for ( var vertex in this.vertices) { - serialize.vertices[vertex] = this.getVertexById(vertex).toJSON(); - } - for ( var edge in this.edges) { - serialize.edges[edge] = this.getEdgeById(edge).toJSON(); - } - - return (serialize); -}; - - - -NetworkDataSetFormatter.prototype._getNodeSize = function(nodeId){ - if (this.isVerticesBalanced()){ - var total = this.maxClass - this.minClass; - if (total == 0){ total = 1;} - var nodeConnection = this.dataset.getVertexById(nodeId).getEdges().length; - return ((nodeConnection*this.args.nodesMaxSize)/total) + this.args.nodesMinSize; - } - return this.getVertexById(nodeId).getDefault().getSize(); -}; - -NetworkDataSetFormatter.prototype._recalculateSize = function(){ - if (this.isVerticesBalanced()){ - this.maxClass = this.dataset.getMaxClass(); - this.minClass = this.dataset.getMinClass(); - for ( var vertexIdAll in this.vertices) { - var size = this._getNodeSize(vertexIdAll); - this.vertices[vertexIdAll].getDefault().setSize(size); - this.vertices[vertexIdAll].getSelected().setSize(size); - this.vertices[vertexIdAll].getOver().setSize(size); - } - } -}; - - -NetworkDataSetFormatter.prototype.addVertex = function(vertexId, json){ - - - if (json == null){ - this.vertices[vertexId] = new CircleVertexGraphFormatter(vertexId, this.args.vertexFormatProperties.defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); - } - else{ - - /** Cargo los attributos desde el json **/ - if (json.type == null){ - this.vertices[vertexId] = new CircleVertexGraphFormatter(vertexId, this.args.vertexFormatProperties.defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); - } - - if ((json.type == "SquareVertexGraphFormatter")||(json.type == "SquareVertexNetworkFormatter")){ - this.vertices[vertexId] = new SquareVertexGraphFormatter(vertexId); - this.vertices[vertexId].loadFromJSON(json); - } - - if ((json.type == "CircleVertexGraphFormatter")||(json.type == "CircleVertexNetworkFormatter")){ - this.vertices[vertexId] = new CircleVertexGraphFormatter(vertexId); - this.vertices[vertexId].loadFromJSON(json); - } - - if ((json.type == "EllipseVertexGraphFormatter")||(json.type == "EllipseVertexNetworkFormatter")){ - this.vertices[vertexId] = new EllipseVertexGraphFormatter(vertexId); - this.vertices[vertexId].loadFromJSON(json); - } - - if ((json.type == "RectangleVertexGraphFormatter")||(json.type == "RectangleVertexNetworkFormatter")){ - this.vertices[vertexId] = new RectangleVertexGraphFormatter(vertexId); - this.vertices[vertexId].loadFromJSON(json); - } - - if ((json.type == "RoundedVertexGraphFormatter")||(json.type == "RoundedVertexNetworkFormatter")){ - this.vertices[vertexId] = new RoundedVertexGraphFormatter(vertexId); - this.vertices[vertexId].loadFromJSON(json); - } - - } - - - var _this = this; - this.vertices[vertexId].stateChanged.attach(function (sender, item){ - _this.changed.notify(item); - }); - - var size = this._getNodeSize(vertexId); - this.vertices[vertexId].defaultFormat.args.size = size; - this.vertices[vertexId].selected.args.size = size; - this.vertices[vertexId].over.args.size = size; - -}; - -NetworkDataSetFormatter.prototype.addEdge = function(edgeId, json){ - - /** Es un edge nuevo que le doy los atributos por defecto **/ - if (json == null){ - if (this.dataset.getEdgeById(edgeId).getNodeSource().getId() == this.dataset.getEdgeById(edgeId).getNodeTarget().getId()){ - this.edges[edgeId] = new BezierEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - }else{ - this.edges[edgeId] = new DirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - } - } - else{ - /** Cargo los attributos desde el json **/ - if (json.type == null){ - this.edges[edgeId] = new LineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - } - - if ((json.type == "LineEdgeGraphFormatter")||(json.type == "LineEdgeNetworkFormatter")){ - this.edges[edgeId] = new LineEdgeGraphFormatter(edgeId); - this.edges[edgeId].loadFromJSON(json); - } - if ((json.type == "DirectedLineEdgeGraphFormatter")||(json.type == "DirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new DirectedLineEdgeGraphFormatter(edgeId); - this.edges[edgeId].loadFromJSON(json); - } - - if ((json.type == "BezierEdgeGraphFormatter")||(json.type == "BezierEdgeNetworkFormatter")){ - this.edges[edgeId] = new BezierEdgeGraphFormatter(edgeId); - this.edges[edgeId].loadFromJSON(json); - } - - - if ((json.type == "CutDirectedLineEdgeGraphFormatter")||(json.type == "CutDirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new CutDirectedLineEdgeGraphFormatter(edgeId); - this.edges[edgeId].loadFromJSON(json); - } - - if ((json.type == "DotDirectedLineEdgeGraphFormatter")||(json.type == "DotDirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new DotDirectedLineEdgeGraphFormatter(edgeId); - this.edges[edgeId].loadFromJSON(json); - } - if ((json.type == "OdotDirectedLineEdgeGraphFormatter")||(json.type == "OdotDirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new OdotDirectedLineEdgeGraphFormatter(edgeId); - this.edges[edgeId].loadFromJSON(json); - } - - if ((json.type == "OdirectedLineEdgeGraphFormatter")||(json.type == "OdirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new OdirectedLineEdgeGraphFormatter(edgeId); - this.edges[edgeId].loadFromJSON(json); - } - } - - var _this = this; - this.edges[edgeId].stateChanged.attach(function (sender, item){ - _this.edgeChanged.notify(item); - }); - - this._recalculateSize(); -}; - -NetworkDataSetFormatter.prototype._setDataset = function(dataset){ - this.dataset = dataset; - this.maxClass = dataset.getMaxClass(); - this.minClass = dataset.getMinClass(); - this._attachDatasetEvents(); -}; - -NetworkDataSetFormatter.prototype.changeEdgeType = function(edgeId, type){ - if ((type == "LineEdgeGraphFormatter")||(type == "LineEdgeNetworkFormatter")){ - this.edges[edgeId] = new LineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - - } - if ((type == "DirectedLineEdgeGraphFormatter")||(type == "DirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new DirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - } - - if ((type == "CutDirectedLineEdgeGraphFormatter")||(type == "CutDirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new CutDirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - } - - if ((type == "DotDirectedLineEdgeGraphFormatter")||(type == "DotDirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new DotDirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - } - - if ((type == "OdotDirectedLineEdgeGraphFormatter")||(type == "OdotDirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new OdotDirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - } - - if ((type == "OdirectedLineEdgeGraphFormatter")||(type == "OdirectedLineEdgeNetworkFormatter")){ - this.edges[edgeId] = new OdirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); - } - - - - var _this = this; - this.edges[edgeId].stateChanged.attach(function (sender, item){ - _this.edgeChanged.notify(item); - }); - _this.edgeChanged.notify(this.edges[edgeId]); -}; -/* -classe = "SquareNetworkNodeFormatter"; -} -if (value == "circle"){ - classe = "CircleNetworkNodeFormatter"; - **/ -NetworkDataSetFormatter.prototype.changeNodeType = function(vertexId, type){ - var defaultFormat = JSON.parse(JSON.stringify(this.vertices[vertexId].getDefault())); - var selectedFormat = JSON.parse(JSON.stringify(this.vertices[vertexId].getSelected())); - var defaultFormat = JSON.parse(JSON.stringify(this.vertices[vertexId].getDefault())); - var defaultFormat = JSON.parse(JSON.stringify(this.vertices[vertexId].getDefault())); - - if ((type == "SquareVertexGraphFormatter")||(type == "SquareVertexNetworkFormatter")){ - this.vertices[vertexId] = new SquareVertexGraphFormatter(vertexId,defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); - } - - if ((type == "CircleVertexGraphFormatter")||(type == "CircleVertexNetworkFormatter")){ - this.vertices[vertexId] = new CircleVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); - } - - if ((type == "EllipseVertexGraphFormatter")||(type == "EllipseVertexNetworkFormatter")){ - this.vertices[vertexId] = new EllipseVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); - } - - if ((type == "RectangleVertexGraphFormatter")||(type == "RectangleVertexNetworkFormatter")){ - this.vertices[vertexId] = new RectangleVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); - } - - if ((type == "RoundedVertexGraphFormatter")||(type == "RoundedVertexNetworkFormatter")){ - this.vertices[vertexId] = new RoundedVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); - } - - if ((type == "OctagonVertexGraphFormatter")||(type == "OctagonVertexNetworkhFormatter")){ - this.vertices[vertexId] = new OctagonVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); - } - - - var _this = this; - this.vertices[vertexId].stateChanged.attach(function (sender, item){ - _this.changed.notify(item); - }); - _this.changed.notify(this.vertices[vertexId]); -}; - - - -NetworkDataSetFormatter.prototype.dataBind = function(networkDataSet){ - var _this = this; - this._setDataset(networkDataSet); - - for ( var vertex in this.dataset.getVertices()) { - this.addVertex(vertex); - } - - for ( var edge in this.dataset.getEdges()) { - this.addEdge(edge); - } -}; - -NetworkDataSetFormatter.prototype._removeEdge = function(edgeId){ - delete this.edges[edgeId]; -}; - -NetworkDataSetFormatter.prototype._removeVertex = function(vertexId){ - delete this.vertices[vertexId]; -}; - -NetworkDataSetFormatter.prototype._attachDatasetEvents = function(id){ - var _this = this; - this.dataset.vertexDeleted.attach(function (sender, item){ - _this._removeVertex(item.getId()); - }); - - this.dataset.edgeDeleted.attach(function (sender, item){ - _this._removeEdge(item.getId()); - }); - - this.dataset.newVertex.attach(function (sender, item){ - _this.addVertex(item.getId()); - }); - - this.dataset.newEdge.attach(function (sender, item){ - _this.addEdge(item.getId()); - }); -}; - - -NetworkDataSetFormatter.prototype.getVertexById = function(id){ - return this.vertices[id]; -}; - -NetworkDataSetFormatter.prototype.getEdgeById = function(id){ - return this.edges[id]; -}; - -NetworkDataSetFormatter.prototype.makeLabelsBigger = function(){ -for ( var vertexId in this.vertices) { - var fontSize = this.vertices[vertexId].getDefault().getFontSize() + 2; - this.vertices[vertexId].getDefault().setFontSize(fontSize); - } -}; - -NetworkDataSetFormatter.prototype.makeLabelsSmaller = function(){ - for ( var vertexId in this.vertices) { - var fontSize = this.vertices[vertexId].getDefault().getFontSize() - 2; - this.vertices[vertexId].getDefault().setFontSize(fontSize); - } -}; - - -NetworkDataSetFormatter.prototype.resize = function(width, height){ - this.args.width = width; - this.args.height = height; - this.resized.notify(); -}; - -/** ZOOM GETTERS **/ -NetworkDataSetFormatter.prototype.getZoomScaleStepFactor = function(){return this.args.zoomScaleStepFactor;}; -NetworkDataSetFormatter.prototype.setZoomScaleStepFactor = function(scaleFactor){this.args.zoomScaleStepFactor = scaleFactor;}; -NetworkDataSetFormatter.prototype.getZoomScale = function(){return this.args.zoomScale;}; -NetworkDataSetFormatter.prototype.setZoomScale = function(scale){this.args.zoomScale = scale;}; - -NetworkDataSetFormatter.prototype.getNodesMaxSize = function(){return this.args.nodesMaxSize;}; -NetworkDataSetFormatter.prototype.getNodesMinSize = function(){return this.args.nodesMinSize;}; - -/** SIZE SETTERS AND GETTERS **/ -NetworkDataSetFormatter.prototype.isVerticesBalanced = function(){return this.args.balanceNodes;}; -NetworkDataSetFormatter.prototype.getWidth = function(){return this.args.width;}; -NetworkDataSetFormatter.prototype.getHeight = function(){return this.args.height;}; - -/** OPTIONAL PARAMETERS GETTERS AND SETTERS **/ -NetworkDataSetFormatter.prototype.getBackgroundImage = function(){return this.args.backgroundImage;}; -NetworkDataSetFormatter.prototype.setBackgroundImage = function(value){this.args.backgroundImage = value; this.backgroundImageChanged.notify(this);}; - - -NetworkDataSetFormatter.prototype.getBackgroundImageWidth = function(){return this.args.backgroundImageWidth;}; -NetworkDataSetFormatter.prototype.setBackgroundImageWidth = function(value){this.args.backgroundImageWidth = value; this.backgroundImageChanged.notify(this);}; - -NetworkDataSetFormatter.prototype.getBackgroundImageHeight = function(){return this.args.backgroundImageHeight;}; -NetworkDataSetFormatter.prototype.setBackgroundImageHeight = function(value){this.args.backgroundImageHeight = value; this.backgroundImageChanged.notify(this);}; - -NetworkDataSetFormatter.prototype.getBackgroundImageX = function(){return this.args.backgroundImageX;}; -NetworkDataSetFormatter.prototype.setBackgroundImageX = function(value){this.args.backgroundImageX = value; this.backgroundImageChanged.notify(this);}; - -NetworkDataSetFormatter.prototype.getBackgroundImageY = function(){return this.args.backgroundImageX;}; -NetworkDataSetFormatter.prototype.setBackgroundImageY = function(value){this.args.backgroundImageY = value; this.backgroundImageChanged.notify(this);}; - - - -NetworkDataSetFormatter.prototype.getBackgroundColor = function(){return this.args.backgroundColor;}; -NetworkDataSetFormatter.prototype.setBackgroundColor = function(value){this.args.backgroundColor = value; this.backgroundColorChanged.notify(this);}; - -NetworkDataSetFormatter.prototype.getWidth = function(){return this.args.width;}; -NetworkDataSetFormatter.prototype.setWidth = function(value){this.args.width = value;}; - -NetworkDataSetFormatter.prototype.getHeight = function(){return this.args.height;}; -NetworkDataSetFormatter.prototype.setHeight = function(value){this.args.height = value;}; - - - - -Vertex.prototype.getName = GraphItem.prototype.getName; -Vertex.prototype.setName = GraphItem.prototype.setName; -Vertex.prototype.getId = GraphItem.prototype.getId; - -function Vertex(id, name, args){ - GraphItem.prototype.constructor.call(this, id, name, args); - this.edgesIn= new Array(); - this.edgesOut= new Array(); -}; - -Vertex.prototype.getEdges = function(){ - return this.edgesIn.concat(this.edgesOut); -}; - -Vertex.prototype.getEdgesCount = function(){ - return this.getEdges().length; -}; - -Vertex.prototype.getEdgesIn = function(){ - return this.edgesIn; -}; - -Vertex.prototype.getEdgesOut = function(){ - return this.edgesOut; -}; - -Vertex.prototype.addEdge = function(edge){ - if (edge.getNodeSource().getId() == this.id){ - this.edgesIn.push(edge); - } - else{ - this.edgesOut.push(edge); - } -}; - -Vertex.prototype.removeEdge = function(edge){ - for ( var i = 0; i < this.getEdgesIn().length; i++) { - var edgeIn = this.edgesIn[i]; - if (edgeIn.getId() == edge.getId()){ - this.edgesIn.splice(i, 1); - } - } - for ( var i = 0; i < this.getEdgesOut().length; i++) { - var edgeIn = this.edgesOut[i]; - if (edgeIn.getId() == edge.getId()){ - this.edgesOut.splice(i, 1); - } - } -}; - -Vertex.prototype.remove = function(){ - var edges = this.getEdges(); - for ( var i = 0; i < edges.length; i++) { - var edge = edges[i]; - edge.remove(); - } - this.deleted.notify(this); -}; - - - - - -VertexGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; -VertexGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; -VertexGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; -VertexGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; -VertexGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; -VertexGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; -VertexGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; -VertexGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; - - -function VertexGraphFormatter(defaultFormat, selectedFormat, overFormat, draggingFormat){ - ItemGraphFormatter.prototype.constructor.call(this, defaultFormat, selectedFormat, overFormat, draggingFormat); -}; - - -CircleVertexGraphFormatter.prototype.getDefault = VertexGraphFormatter.prototype.getDefault; -CircleVertexGraphFormatter.prototype.getSelected = VertexGraphFormatter.prototype.getSelected; -CircleVertexGraphFormatter.prototype.getOver = VertexGraphFormatter.prototype.getOver; -CircleVertexGraphFormatter.prototype.getDragging = VertexGraphFormatter.prototype.getDragging; -CircleVertexGraphFormatter.prototype.getId = VertexGraphFormatter.prototype.getId; -CircleVertexGraphFormatter.prototype.toJSON = VertexGraphFormatter.prototype.toJSON; -CircleVertexGraphFormatter.prototype.loadFromJSON = VertexGraphFormatter.prototype.loadFromJSON; -CircleVertexGraphFormatter.prototype._setEvents = VertexGraphFormatter.prototype._setEvents; - -function CircleVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ - VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); - this.args.type = "CircleVertexGraphFormatter"; - if (defaultFormat != null){ - if (defaultFormat.radius != null){ - this.defaultFormat.args.radius = defaultFormat.radius; - } - } - - if (selectedFormat != null){ - if (selectedFormat.radius != null){ - this.selected.args.radius = selectedFormat.radius; - } - } - - if (overFormat != null){ - if (overFormat.radius != null){ - this.over.args.radius = overFormat.radius; - } - } - - if (draggingFormat != null){ - if (draggingFormat.radius != null){ - this.dragging.args.draggingFormat = draggingFormat.radius; - } - } -}; - - - -SquareVertexGraphFormatter.prototype.getDefault = VertexGraphFormatter.prototype.getDefault; -SquareVertexGraphFormatter.prototype.getSelected = VertexGraphFormatter.prototype.getSelected; -SquareVertexGraphFormatter.prototype.getOver = VertexGraphFormatter.prototype.getOver; -SquareVertexGraphFormatter.prototype.getDragging = VertexGraphFormatter.prototype.getDragging; -SquareVertexGraphFormatter.prototype.getId = VertexGraphFormatter.prototype.getId; -SquareVertexGraphFormatter.prototype.toJSON = VertexGraphFormatter.prototype.toJSON; -SquareVertexGraphFormatter.prototype.loadFromJSON = VertexGraphFormatter.prototype.loadFromJSON; -SquareVertexGraphFormatter.prototype._setEvents = VertexGraphFormatter.prototype._setEvents; - -function SquareVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ - VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); - this.args.type = "SquareVertexGraphFormatter"; - if (defaultFormat != null){ - if (defaultFormat.radius != null){ - this.defaultFormat.args.radius = defaultFormat.radius; - } - } - - if (selectedFormat != null){ - if (selectedFormat.radius != null){ - this.selected.args.radius = selectedFormat.radius; - } - } - - if (overFormat != null){ - if (overFormat.radius != null){ - this.over.args.radius = overFormat.radius; - } - } - - if (draggingFormat != null){ - if (draggingFormat.radius != null){ - this.dragging.args.draggingFormat = draggingFormat.radius; - } - } -}; - - -EllipseVertexGraphFormatter.prototype.getDefault = VertexGraphFormatter.prototype.getDefault; -EllipseVertexGraphFormatter.prototype.getSelected = VertexGraphFormatter.prototype.getSelected; -EllipseVertexGraphFormatter.prototype.getOver = VertexGraphFormatter.prototype.getOver; -EllipseVertexGraphFormatter.prototype.getDragging = VertexGraphFormatter.prototype.getDragging; -EllipseVertexGraphFormatter.prototype.getId = VertexGraphFormatter.prototype.getId; -EllipseVertexGraphFormatter.prototype.toJSON = VertexGraphFormatter.prototype.toJSON; -EllipseVertexGraphFormatter.prototype.loadFromJSON = VertexGraphFormatter.prototype.loadFromJSON; -EllipseVertexGraphFormatter.prototype._setEvents = VertexGraphFormatter.prototype._setEvents; - -function EllipseVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ - VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); - this.args.type = "EllipseVertexGraphFormatter"; - if (defaultFormat != null){ - if (defaultFormat.radius != null){ - this.defaultFormat.args.radius = defaultFormat.radius; - } - } - - if (selectedFormat != null){ - if (selectedFormat.radius != null){ - this.selected.args.radius = selectedFormat.radius; - } - } - - if (overFormat != null){ - if (overFormat.radius != null){ - this.over.args.radius = overFormat.radius; - } - } - - if (draggingFormat != null){ - if (draggingFormat.radius != null){ - this.dragging.args.draggingFormat = draggingFormat.radius; - } - } -}; - - - -RectangleVertexGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; -RectangleVertexGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; -RectangleVertexGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; -RectangleVertexGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; -RectangleVertexGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; -RectangleVertexGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; -RectangleVertexGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; -RectangleVertexGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; - -function RectangleVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ - VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); - this.args.type = "RectangleVertexGraphFormatter"; - if (defaultFormat != null){ - if (defaultFormat.radius != null){ - this.defaultFormat.args.radius = defaultFormat.radius; - } - } - - if (selectedFormat != null){ - if (selectedFormat.radius != null){ - this.selected.args.radius = selectedFormat.radius; - } - } - - if (overFormat != null){ - if (overFormat.radius != null){ - this.over.args.radius = overFormat.radius; - } - } - - if (draggingFormat != null){ - if (draggingFormat.radius != null){ - this.dragging.args.draggingFormat = draggingFormat.radius; - } - } -}; - - - -RoundedVertexGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; -RoundedVertexGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; -RoundedVertexGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; -RoundedVertexGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; -RoundedVertexGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; -RoundedVertexGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; -RoundedVertexGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; -RoundedVertexGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; - -function RoundedVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ - VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); - this.args.type = "RoundedVertexGraphFormatter"; - if (defaultFormat != null){ - if (defaultFormat.radius != null){ - this.defaultFormat.args.radius = defaultFormat.radius; - } - } - - if (selectedFormat != null){ - if (selectedFormat.radius != null){ - this.selected.args.radius = selectedFormat.radius; - } - } - - if (overFormat != null){ - if (overFormat.radius != null){ - this.over.args.radius = overFormat.radius; - } - } - - if (draggingFormat != null){ - if (draggingFormat.radius != null){ - this.dragging.args.draggingFormat = draggingFormat.radius; - } - } -}; - - - -OctagonVertexGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; -OctagonVertexGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; -OctagonVertexGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; -OctagonVertexGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; -OctagonVertexGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; -OctagonVertexGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; -OctagonVertexGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; -OctagonVertexGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; - -function OctagonVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ - VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); - this.args.type = "OctagonVertexGraphFormatter"; - if (defaultFormat != null){ - if (defaultFormat.radius != null){ - this.defaultFormat.args.radius = defaultFormat.radius; - } - } - - if (selectedFormat != null){ - if (selectedFormat.radius != null){ - this.selected.args.radius = selectedFormat.radius; - } - } - - if (overFormat != null){ - if (overFormat.radius != null){ - this.over.args.radius = overFormat.radius; - } - } - - if (draggingFormat != null){ - if (draggingFormat.radius != null){ - this.dragging.args.draggingFormat = draggingFormat.radius; - } - } -}; - - - -var Colors = new function() -{ - this.hashColor = []; - this.getColorByScoreArrayValue = function (arrayScore) - { - var array = new Array(); - - for (var i = 0; i< arrayScore.length; i++) - { - - var color = this.getColorByScoreValue(arrayScore[i]) - array.push( color); - - } - return array; - }; - - this.getHexStringByScoreArrayValue = function (arrayScore) - { - var arrayColor = this.getColorByScoreArrayValue(arrayScore); - var arrayHex = new Array(); - for (var i = 0; i< arrayColor.length; i++) - { - arrayHex.push( arrayColor[i].HexString()); - } - return arrayHex; - }; - - this.getColorByScoreValue = function (score) - { - - var truncate = score.toString().substr(0,4); - if (this.hashColor[truncate]!=null) - { - return this.hashColor[truncate]; - } - - - if(isNaN(score)) { - return Colors.ColorFromRGB(0,0,0); - } - var value; - - var from, to; - if(score < 0.5) { - from = Colors.ColorFromRGB(0,0,255); - to = Colors.ColorFromRGB(255,255,255); - value = (score * 2); - } else { - from = Colors.ColorFromRGB(255,255,255); - to = Colors.ColorFromRGB(255,0,0); - value = (score * 2) - 1; - } - - var x = value; - var y = 1.0 - value; - var color = Colors.ColorFromRGB(y * from.Red() + x * to.Red(), y * from.Green() + x * to.Green(), y * from.Blue() + x * to.Blue()); - - this.hashColor[truncate] = color; - - return color; - }; - - this.ColorFromHSV = function(hue, sat, val) - { - var color = new Color(); - color.SetHSV(hue,sat,val); - return color; - }; - - this.ColorFromRGB = function(r, g, b) - { - var color = new Color(); - color.SetRGB(r,g,b); - return color; - }; - - this.ColorFromHex = function(hexStr) - { - var color = new Color(); - color.SetHexString(hexStr); - return color; - }; - - function Color() { - //Stored as values between 0 and 1 - var red = 0; - var green = 0; - var blue = 0; - - //Stored as values between 0 and 360 - var hue = 0; - - //Strored as values between 0 and 1 - var saturation = 0; - var value = 0; - - this.SetRGB = function(r, g, b) - { - red = r/255.0; - green = g/255.0; - blue = b/255.0; - calculateHSV(); - }; - - this.Red = function() { return Math.round(red*255); }; - - this.Green = function() { return Math.round(green*255); }; - - this.Blue = function() { return Math.round(blue*255); }; - - this.SetHSV = function(h, s, v) - { - hue = h; - saturation = s; - value = v; - calculateRGB(); - }; - - this.Hue = function() - { return hue; }; - - this.Saturation = function() - { return saturation; }; - - this.Value = function() - { return value; }; - - this.SetHexString = function(hexString) - { - if(hexString == null || typeof(hexString) != "string") - { - this.SetRGB(0,0,0); - return; - } - - if (hexString.substr(0, 1) == '#') - hexString = hexString.substr(1); - - if(hexString.length != 6) - { - this.SetRGB(0,0,0); - return; - } - - var r = parseInt(hexString.substr(0, 2), 16); - var g = parseInt(hexString.substr(2, 2), 16); - var b = parseInt(hexString.substr(4, 2), 16); - if (isNaN(r) || isNaN(g) || isNaN(b)) - { - this.SetRGB(0,0,0); - return; - } - - this.SetRGB(r,g,b); - }; - - this.HexString = function() - { - - var rStr = this.Red().toString(16); - if (rStr.length == 1) - rStr = '0' + rStr; - var gStr = this.Green().toString(16); - if (gStr.length == 1) - gStr = '0' + gStr; - var bStr = this.Blue().toString(16); - if (bStr.length == 1) - bStr = '0' + bStr; - return ('#' + rStr + gStr + bStr).toUpperCase(); - }; - - this.Complement = function() - { - var newHue = (hue >= 180) ? hue - 180 : hue + 180; - var newVal = (value * (saturation - 1) + 1); - var newSat = (value*saturation) / newVal; - var newColor = new Color(); - newColor.SetHSV(newHue, newSat, newVal); - return newColor; - } ; - - function calculateHSV() - { - var max = Math.max(Math.max(red, green), blue); - var min = Math.min(Math.min(red, green), blue); - - value = max; - - saturation = 0; - if(max != 0) - saturation = 1 - min/max; - - hue = 0; - if(min == max) - return; - - var delta = (max - min); - if (red == max) - hue = (green - blue) / delta; - else if (green == max) - hue = 2 + ((blue - red) / delta); - else - hue = 4 + ((red - green) / delta); - hue = hue * 60; - if(hue < 0) - hue += 360; - } - - function calculateRGB() - { - red = value; - green = value; - blue = value; - - if(value == 0 || saturation == 0) - return; - - var tHue = (hue / 60); - var i = Math.floor(tHue); - var f = tHue - i; - var p = value * (1 - saturation); - var q = value * (1 - saturation * f); - var t = value * (1 - saturation * (1 - f)); - switch(i) - { - case 0: - red = value; green = t; blue = p; - break; - case 1: - red = q; green = value; blue = p; - break; - case 2: - red = p; green = value; blue = t; - break; - case 3: - red = p; green = q; blue = value; - break; - case 4: - red = t; green = p; blue = value; - break; - default: - red = value; green = p; blue = q; - break; - } - } - } -} -(); -/* - * Clase gestiona la insercción, eliminación de los elementos en el DOM - * - * Vital hacerla SIEMPRE compatible hacia atrás - * - * Last update: 28-10-2010 - * - */ - - -var DOM = {}; - -DOM.createNewElement = function(type, nodeParent, attributes) -{ - - var node = document.createElement(type); - for (var i=0; i0) - { - parent.removeChild(parent.childNodes[0]); - - } -}; - -DOM.select = function(targetID) -{ - return document.getElementById(targetID); -// return $("#"+targetID); -}; -var Geometry = -{ - - /** From tow points obtains the angles formed with the cartesian side **/ - getAngleBetweenTwoPoints : function(x1, y1, x2, y2){ - //var m = (y1 - y2)/ (x1 - x2); - return Math.atan2(y2-y1, x2-x1); - }, - - getAdjacentSideOfRectangleRight : function(angle, hypotenuse){ - return Math.abs(Math.cos(angle)*hypotenuse); - }, - - getOppositeSideOfRectangleRight : function(angle, hypotenuse){ - return Math.abs(Math.sin(angle)*hypotenuse); - }, - - toDegree: function(radian){ - return radian*180/Math.PI; - - } - - -}; - -var SVG = -{ - svgns : 'http://www.w3.org/2000/svg', - xlinkns : "http://www.w3.org/1999/xlink", - - createSVGCanvas: function(parentNode, attributes) - { - - attributes.push( ['xmlns', SVG.svgns], ['xmlns:xlink', 'http://www.w3.org/1999/xlink']); - var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); - this._setProperties(svg, attributes); - parentNode.appendChild( svg); - return svg; - - }, - - createRectangle : function (x, y, width, height, attributes){ - var rect = document.createElementNS(this.svgns, "rect"); - rect.setAttribute("x",x); - rect.setAttribute("y",y); - rect.setAttribute("width",width); - rect.setAttribute("height",height); - SVG._setProperties(rect, attributes); - return rect; - }, - - drawImage64 : function (x, y, width, height, base64, svgNode, attributes) { - var node = SVG.createImage64(x, y, width, height, base64, attributes); - svgNode.appendChild(node); - return node; - }, - - createImage64 : function (x, y, width, height, base64, attributes) { - var img = document.createElementNS(this.svgns, "image"); - img.setAttribute("x",x); - img.setAttribute("y",y); - img.setAttribute("width",width); - img.setAttribute("height",height); - img.setAttribute("xlink:href",base64); - SVG._setProperties(img, attributes); - return img; - }, - - createLine: function (x1, y1, x2, y2, attributes){ - var line = document.createElementNS(this.svgns,"line"); - line.setAttribute("x1",x1); - line.setAttribute("y1",y1); - line.setAttribute("x2", x2); - line.setAttribute("y2", y2); - SVG._setProperties(line, attributes); - return line; - }, - - createClip: function (id, nodeToClip, attributes){ - var clip = document.createElementNS(this.svgns,"clipPath"); - clip.setAttribute("id",id); - clip.appendChild(nodeToClip); - return clip; - }, - - drawClip : function (id, nodeToClip, svgNode) { - var node = SVG.createClip(id, nodeToClip); - svgNode.appendChild(node); - return node; - }, - - drawRectangle : function (cx, cy, width, height, svgNode, attributes) { - try{ - var node = SVG.createRectangle(cx, cy, width, height, attributes); - svgNode.appendChild(node); - } - catch(e){ - - console.log("-------------------- "); - console.log("Error on drawRectangle " + e); - console.log(attributes); - console.log("-------------------- "); - } - return node; - }, - - createEllipse : function (x, y, rx, ry, attributes){ - var rect = document.createElementNS(this.svgns, "ellipse"); - rect.setAttribute("cx",x); - rect.setAttribute("cy",y); - rect.setAttribute("rx",rx); - rect.setAttribute("ry",ry); - SVG._setProperties(rect, attributes); - return rect; - }, - - drawEllipse : function (cx, cy, rx, ry, svgNode, attributes) { - var node = SVG.createEllipse(cx, cy, rx, ry, attributes); - svgNode.appendChild(node); - return node; - }, - - drawImage : function (x, y, canvasSVG, attributes) { - var image = document.createElementNS(this.svgns, "image"); - image.setAttribute("x",x); - image.setAttribute("y",y); - canvasSVG.appendChild(image); - SVG._setProperties(image, attributes); - }, - - drawLine : function (x1, y1, x2, y2, nodeSVG, attributes) { - try{ - var line = SVG.createLine(x1, y1, x2, y2, attributes); - nodeSVG.appendChild(line); - }catch(e){ - } - return line; - }, - - - drawPath: function (d, nodeSVG, attributes) { - var path = SVG.createPath(d, attributes); - nodeSVG.appendChild(path); - return path; - }, - - createPoligon : function (points, attributes){ - var poligon = document.createElementNS(this.svgns, "polygon"); - poligon.setAttribute("points",points); - SVG._setProperties(poligon, attributes); - return poligon; - }, - - drawPoligon : function (points, canvasSVG, attributes){ - var poligon = SVG.createPoligon(points, attributes); - canvasSVG.appendChild(poligon); - return poligon; - }, - // - - createPath : function (d, attributes){ - var path = document.createElementNS(this.svgns, "path"); - path.setAttribute("d",d); - SVG._setProperties(path, attributes); - return path; - }, - - drawCircle : function (x, y, radio, canvasSVG, attributes) { - - var newText = document.createElementNS(this.svgns,"circle"); - newText.setAttribute("cx",x); - newText.setAttribute("cy",y); - newText.setAttribute("r",radio); - - canvasSVG.appendChild(newText); - attributes["cursor"] = "pointer"; - this._setProperties(newText, attributes); - return newText; - }, - - - _setProperties: function(node, attributes) - { - if (attributes instanceof Array){ - for (var i=0; i< attributes.length; i++) - { - node.setAttribute(attributes[i][0], attributes[i][1]); - } - } - else{ - for ( var key in attributes){ - node.setAttribute(key, attributes[key]); - } - } - }, - -/* drawPath: function(pointsArray, canvasSVG, attributes){ - var path = document.createElementNS(this.svgns,"polyline"); - path.setAttribute ('id', id); - - var d= pointsArray[0].x+ " "+ pointsArray[0].y; - for (var i=1; i< pointsArray.length; i++) - { - d=d+" "+pointsArray[i].x+" "+pointsArray[i].y; - } - path.setAttribute ('points', d); - canvasSVG.appendChild(path); - },*/ - - createText : function (x, y, text, attributes) { - var node = document.createElementNS(this.svgns,"text"); - node.setAttributeNS(null , "x",x); - node.setAttributeNS(null, "y",y); - - var textNode = document.createTextNode(text); - node.appendChild(textNode); - - this._setProperties(node, attributes); - return node; - }, - - drawText : function (x, y, text, canvasSVG, attributes) { - var text = SVG.createText(x, y, text, attributes); - canvasSVG.appendChild(text); - return text; - }, - - - - drawGroup: function(svgNode, attributes) - { - var group = SVG.createGroup(attributes); - svgNode.appendChild(group); - return group; - }, - - createGroup: function(attributes){ - var group = document.createElementNS(this.svgns,"g"); - this._setProperties(group, attributes); - return group; - } - -}; - - - -var CanvasToSVG = { - - convert: function(sourceCanvas, targetSVG, x, y, id, attributes) { - - var img = this._convert(sourceCanvas, targetSVG, x, y, id); - - for (var i=0; i< attributes.length; i++) - { - img.setAttribute(attributes[i][0], attributes[i][1]); - } - }, - - _convert: function(sourceCanvas, targetSVG, x, y, id) { - var svgNS = "http://www.w3.org/2000/svg"; - var xlinkNS = "http://www.w3.org/1999/xlink"; - // get base64 encoded png from Canvas - var image = sourceCanvas.toDataURL(); - - // must be careful with the namespaces - var svgimg = document.createElementNS(svgNS, "image"); - - svgimg.setAttribute('id', id); - - //svgimg.setAttribute('class', class); - //svgimg.setAttribute('xlink:href', image); - svgimg.setAttributeNS(xlinkNS, 'xlink:href', image); - - - - - svgimg.setAttribute('x', x ? x : 0); - svgimg.setAttribute('y', y ? y : 0); - svgimg.setAttribute('width', sourceCanvas.width); - svgimg.setAttribute('height', sourceCanvas.height); - //svgimg.setAttribute('cursor', 'pointer'); - svgimg.imageData = image; - - targetSVG.appendChild(svgimg); - return svgimg; - }, - - importSVG: function(sourceSVG, targetCanvas) { - svg_xml = sourceSVG;//(new XMLSerializer()).serializeToString(sourceSVG); - var ctx = targetCanvas.getContext('2d'); - - var img = new Image(); - img.src = "data:image/svg+xml;base64," + btoa(svg_xml); -// img.onload = function() { - ctx.drawImage(img, 0, 0); -// }; - } - -}; -/* -Graph.prototype.importSVG = function(sourceSVG, targetCanvas) { - sourceSVG = this._svg; - targetCanvas = document.createElementNS('canvas'); - // https://developer.mozilla.org/en/XMLSerializer - svg_xml = (new XMLSerializer()).serializeToString(sourceSVG); - var ctx = targetCanvas.getContext('2d'); - // this is just a JavaScript (HTML) image - var img = new Image(); - // http://en.wikipedia.org/wiki/SVG#Native_support - // https://developer.mozilla.org/en/DOM/window.btoa - img.src = "data:image/svg+xml;base64," + btoa(svg_xml); - img.onload = function() { - // after this, Canvas’ origin-clean is DIRTY - ctx.drawImage(img, 0, 0); - } -}; -*/ - -/* - -Normalizacion de datos para dibujar colores -Issues: - No sé como debería llamarse esta libreria - No sé si ya existe una funciçon en javascript que lo haga - - -*/ - - -var Normalizer = new function() -{ - this.normalizeArray = function (arrayData) - { - - return this.standardizeArray(this.normal(arrayData)); - -// var result = this._getMaxAndMin(arrayData); -// var min =result[0]; -// var max = result[1]; -// -// -// //los hacemos todos positivos -// for (var i = 0; i< arrayData.length; i++) -// { -// arrayData[i]= Math.abs(min) + parseFloat(arrayData[i]); -// } -// -// var result = this._getMaxAndMin(arrayData); -// var min =result[0]; -// var max = result[1]; -// -// -// var resultArray = new Array(); -// for (var i = 0; i< arrayData.length; i++) -// { -// resultArray.push(arrayData[i]*1/max); -// } -// return resultArray; - }; - - this.normal = function(arrayData){ - var mean = this._getMean(arrayData); - var deviation = this._getStdDeviation(arrayData); - var result = this._getMaxAndMin(arrayData); - var min = result[0]; - var max = result[1]; - - var resultArray = new Array(); - for (var i = 0; i< arrayData.length; i++) { - if (deviation!=0){ - resultArray.push((arrayData[i]-mean)/deviation); - }else{ - resultArray.push(arrayData[i]); - } - } - return resultArray; - }; - - this.standardizeArray = function(arrayData) - { - var result = this._getMaxAndMin(arrayData); - var min = result[0]; - var max = result[1]; - - var offset = ( min <= 0 ) ? Math.abs(min) : (-1 * min); - var resultArray = new Array(); - for (var i = 0; i< arrayData.length; i++) { - if(max + offset!=0){ - resultArray.push((arrayData[i] + offset) / (max + offset)); - }else{ - resultArray.push(arrayData[i]+offset); - } - } - return resultArray; - }; - - - this._getMean = function(arrayData) { - var sum = 0; - for (var i = 0; i< arrayData.length; i++) { - sum = sum + parseFloat(arrayData[i]); - } - return sum/arrayData.length; - }; - - this._getStdDeviation = function(arrayData) { - var mean = this._getMean(arrayData); - var acum = 0.0; - for(var i=0; i max) max = parseFloat(arrayData[i]); - } - - return [min, max]; - }; -}; -function GraphCanvas(componentID, targetNode, args) { - this.args = {}; - /** target */ - this.targetID = targetNode.id; - - /** id manage */ - this.id = componentID; - this.args.idGraph = this.id + "main"; - this.args.idBackgroundNode = this.id + "background"; - - this.args.idEdgesGraph = this.id + "edges"; - this.args.idNodesGraph = this.id + "vertices"; - this.args.idLabelGraph = this.id + "label"; - this.args.idBackground = this.id + "background"; - - /** Objects Graph **/ - this.dataset = null; - this.formatter = null; - this.layout = null; - - /** Drawing **/ - this.circleDefaultRadius = 2; - this.squareDefaultSide = this.circleDefaultRadius * 1.5; - - /** Directed Arrow **/ - this.arrowDefaultSize = this.circleDefaultRadius; - - /** Groups **/ - this.GraphGroup = null; - this.GraphNodeGroup = null; - this.GraphLabelGroup = null; - this.GraphBackground = null; - - /** SETTINGS FLAGS **/ - this.args.draggingCanvasEnabled = false; //Flag to set if the canvas can be dragged - this.args.multipleSelectionEnabled = false; - this.args.interactive = false; - this.args.labeled = false; - this.args.linkEnabled = false; - - /** If numberEdge > maxNumberEdgesMoving then only it will move edges when mouse up **/ - this.args.maxNumberEdgesMoving = 3; - this.args.maxNumberEdgesFiringEvents = 50; - - /** Linking edges **/ - this.args.linking = false; - this.linkStartX = 0; - this.linkStartY = 0; - this.linkSVGNode = null; - this.linkNodeSource = null; - this.linkNodeTarget = null; - - /** Dragging Control **/ - this.draggingElement = null; - this.dragging = false; - this.nMouseOffsetX = 0; - this.nMouseOffsetY = 0; - this.dragStartX = 0; - this.dragStartY = 0; - this.desplazamientoX = 0; - this.desplazamientoY = 0; - - /** Selection Control **/ - this.selecting = false; - this.selectorX = null; - this.selectorY = null; - this.selectorSVGNode = null; - - /** Node status **/ - this.args.isVertexSelected = {}; - this.args.selectedVertices = []; - - /** Edges status **/ - this.args.isEdgeSelected = {}; - //this.args.selectedEdges = []; - - if (args != null) { - if (args.multipleSelectionEnabled != null) { - this.args.multipleSelectionEnabled = args.multipleSelectionEnabled; - this.args.draggingCanvasEnabled = !(this.args.multipleSelectionEnabled); - } - if (args.draggingCanvasEnabled != null) { - this.args.draggingCanvasEnabled = args.draggingCanvasEnabled; - this.args.multipleSelectionEnabled = !(this.args.draggingCanvasEnabled); - } - if (args.interactive != null) { - this.args.interactive = args.interactive; - } - if (args.labeled != null) { - this.args.labeled = args.labeled; - } - - } - - /** Hashmap with the svg node labels **/ - this.svgLabels = {}; - - /** EVENTS **/ - this.onVertexOut = new Event(this); - this.onVertexOver = new Event(this); - this.onVertexSelect = new Event(this); - this.onEdgeSelect = new Event(this); - this.onCanvasClicked = new Event(this); - this.onVertexUp = new Event(this); -} - -GraphCanvas.prototype.showLabels = function(value) { - this.args.labeled = value; - this.removeLabels(); - if (value) { - this.renderLabels(); - } -}; - -GraphCanvas.prototype.getSelectedVertices = function() { - return this.args.selectedVertices; -}; - -GraphCanvas.prototype.getSelectedEdges = function() { - var selected = []; - for ( var selectedEdge in this.args.isEdgeSelected) { - selected.push(selectedEdge); - } - return selected; -}; - -GraphCanvas.prototype.createSVGDom = function(targetID, id, width, height, backgroundColor) { - var container = document.getElementById(targetID); - this._svg = SVG.createSVGCanvas(container, [ - [ "style", "background-color:" + backgroundColor + ";" ], [ "id", id ], [ "dragx", 0 ], [ "dragy", 0 ], - [ "height", this.getFormatter().getHeight() ], [ "width", this.getFormatter().getWidth() ] ]); - return this._svg; -}; - -/** MULTIPLE SELECTION **/ -GraphCanvas.prototype.isMultipleSelectionEnabled = function() { - return this.args.multipleSelectionEnabled; -}; - -GraphCanvas.prototype.setMultipleSelection = function(value) { - this.args.multipleSelectionEnabled = value; - this.args.draggingCanvasEnabled = (!value); -}; - -GraphCanvas.prototype.setSelecting = function(value) { - this.selecting = value; -}; - -/** linking **/ -GraphCanvas.prototype.setLinking = function(value) { - this.args.linkEnabled = value; - this.selecting = !value; - this.dragging = !value; -}; - -/** CANVAS MOVING **/ -GraphCanvas.prototype.setDraggingCanvas = function(value) { - this.args.draggingCanvasEnabled = value; - this.args.multipleSelectionEnabled = !value; -}; - -GraphCanvas.prototype.isDraggingCanvasEnabled = function() { - return this.args.draggingCanvasEnabled; -}; -/** ZOOM **/ -GraphCanvas.prototype.getScale = function() { - return this.getFormatter().getZoomScale(); -}; - -GraphCanvas.prototype.setScale = function(scale) { - var graphNode = document.getElementById(this.args.idGraph); - graphNode.setAttribute("transform", graphNode.getAttribute("transform").replace("scale(" + this.getScale() + ")", "scale(" + scale + ")")); - this.getFormatter().setZoomScale(scale); -}; - -GraphCanvas.prototype.zoomIn = function() { - this.setScale(this.getScale() + this.getFormatter().getZoomScaleStepFactor()); -}; - -GraphCanvas.prototype.zoomOut = function() { - this.setScale(this.getScale() - this.getFormatter().getZoomScaleStepFactor()); - -}; - -/** SVG COORDENATES **/ -GraphCanvas.prototype.getSVGCoordenates = function(evt) { - var p = this._svg.createSVGPoint(); - p.x = evt.clientX; - p.y = evt.clientY; - - var m = this._svg.getScreenCTM(document.documentElement); - p = p.matrixTransform(m.inverse()); - return p; -}; - -/** SVG EVENTS **/ -GraphCanvas.prototype.mouseClick = function(event) { - if (event.button == 0) { - if (!this.args.interactive) { - return; - } - - if (this.isVertex(event.target)) { - this.clickNode(this.getVertexIdFromSVGId(event.target.id)); - } - /** Como el evento mouseClick viene despues del mouse up es aqui donde manejo el tema de deseccionar los elementos que estoy dragging **/ - if (this.dragging) { - this.dragging = false; - } - } -}; - -GraphCanvas.prototype.mouseMove = function(evt) { - if (this.selecting) { - this.clearLabels(); - - var width = (this.getSVGCoordenates(evt).x - this.selectorX); - var height = (this.getSVGCoordenates(evt).y - this.selectorY); - if ((width > 0) && (height > 0)) { - this.displaySelection(this.selectorX, this.selectorY, width, height); - } - if ((width > 0) && (height < 0)) { - this.displaySelection(this.selectorX, this.getSVGCoordenates(evt).y, width, Math.abs(height)); - } - if ((width < 0) && (height < 0)) { - this.displaySelection(this.getSVGCoordenates(evt).x, this.getSVGCoordenates(evt).y, Math.abs(width), Math.abs(height)); - } - if ((width < 0) && (height > 0)) { - this.displaySelection(this.selectorX + width, this.selectorY, Math.abs(width), Math.abs(height)); - } - - var x1 = (parseFloat(this.selectorSVGNode.getAttribute("x")) - DOM.select(this.id).getAttribute("dragx")) / this.getFormatter().getWidth(); - var y1 = (parseFloat(this.selectorSVGNode.getAttribute("y")) - DOM.select(this.id).getAttribute("dragy")) / this.getFormatter().getHeight(); - var x2 = (x1 + parseFloat(this.selectorSVGNode.getAttribute("width") / this.getFormatter().getWidth())); - var y2 = (y1 + parseFloat(this.selectorSVGNode.getAttribute("height") / this.getFormatter().getHeight())); - - this.deselectNodes(this.getLayout()); - var verticesSelected = this.getLayout().getVerticesByArea(x1 / this.getFormatter().getZoomScale(), y1 / this.getFormatter().getZoomScale(), - x2 / this.getFormatter().getZoomScale(), y2 / this.getFormatter().getZoomScale()); - for ( var i = 0; i < verticesSelected.length; i++) { - this.selectNode(verticesSelected[i].getId()); - this.renderLabel(verticesSelected[i].getId()); - } - - } - var p = null; - if (this.args.linking) { - p = this.getSVGCoordenates(evt); - if (this.linkSVGNode != null) { - this.linkSVGNode.setAttribute("x2", p.x - 2); - this.linkSVGNode.setAttribute("y2", p.y - 2); - } - } - - if (this.dragging) { - p = this.getSVGCoordenates(evt); - p.x -= this.nMouseOffsetX; - p.y -= this.nMouseOffsetY; - this.desplazamientoX = (this.getSVGCoordenates(evt).x - this.dragStartX);// + parseFloat(DOM.select(this.id).getAttribute("dragx")); - this.desplazamientoY = (this.getSVGCoordenates(evt).y - this.dragStartY);// + parseFloat(DOM.select(this.id).getAttribute("dragy")); - - if (this.draggingElement != null) { - /** Click sobre el recct del banground que provoca que mueva todo el canvas **/ - if (this.isNodeCanvas(this.draggingElement)) { - - p = this.getSVGCoordenates(evt); - p.x = this.desplazamientoX; - p.y = this.desplazamientoY; - - this.draggingElement.setAttribute("dragx", p.x); - this.draggingElement.setAttribute("dragy", p.y); - this.draggingElement = document.getElementById(this.args.idGraph); - this.draggingElement.setAttribute("transform", "translate(" + p.x + "," + p.y + "), scale(" + this.getScale() + ")"); - - DOM.select(this.id).setAttribute("dragx", p.x); - DOM.select(this.id).setAttribute("dragy", p.y); - - if (this.NodeSVGbackgroundImage != null) { - this.NodeSVGbackgroundImage.setAttribute("dragx", p.x); - this.NodeSVGbackgroundImage.setAttribute("dragy", p.y); - } - } else { - if (this.isVertex(this.draggingElement)) { - this.selectNode(this.getVertexIdFromSVGId(this.draggingElement.id)); - this.desplazamientoX = this.desplazamientoX / this.getFormatter().getZoomScale(); - this.desplazamientoY = this.desplazamientoY / this.getFormatter().getZoomScale(); - this.moveSelectedNodes(this.desplazamientoX, this.desplazamientoY); - - this.dragStartX = this.getSVGCoordenates(evt).x; - this.dragStartY = this.getSVGCoordenates(evt).y; - } else { - if (this.isNodeBackground(this.draggingElement)) { - - this.draggingElement.setAttribute("dragx", p.x); - this.draggingElement.setAttribute("dragy", p.y); - this.draggingElement = document.getElementById(this.args.idGraph); - this.draggingElement.setAttribute("transform", "translate(" + p.x + "," + p.y + "), scale(" + this.getScale() + ")"); - } else { - this.draggingElement.setAttribute("transform", "translate(" + p.x + "," + p.y + ")"); - } - } - } - } - } -}; - -GraphCanvas.prototype.moveSelectedNodes = function(offsetX, offsetY) { - for ( var i = 0; i < this.getSelectedVertices().length; i++) { - - var nodeId = this.getSelectedVertices()[i]; - var svgNodeId = this.getSVGNodeId(nodeId); - - var x = parseFloat(DOM.select(svgNodeId).getAttribute("dragx")) + parseFloat(offsetX);// - parseFloat(DOM.select(this.id).getAttribute("dragx")); - var y = parseFloat(DOM.select(svgNodeId).getAttribute("dragy")) + parseFloat(offsetY);// + parseFloat(DOM.select(this.id).getAttribute("dragy")); - - this._movingNode(DOM.select(svgNodeId), x, y); - } -}; - -GraphCanvas.prototype.mouseDown = function(evt) { - if (event.button == 0) { - - /** if !no interactive mouse events do anything **/ - if (!this.args.interactive) { - return; - } - - var p = this.getSVGCoordenates(evt); - - /** When click on canvas or background deselect all **/ - if (this.isNodeCanvas(evt.target) || this.isNodeBackground(evt.target)) { - this.deselectNodes(); - this.deselectEdges(); - this.onCanvasClicked.notify(); - } - - /** if I am linking vertices **/ - if (this.args.linkEnabled) { - - if (!this.args.linking) { - this.args.linking = true; - if (this.isVertex(evt.target)) { - this.linkStartX = p.x; - this.linkStartY = p.y; - this.linkSVGNode = SVG.drawLine(p.x, p.y, p.x, p.y, this._svg, { - "stroke" : "#FF0000" - }); - this.linkNodeSource = this.getVertexIdFromSVGId(evt.target.id); - } - } else { - this.linkNodeTarget = this.getVertexIdFromSVGId(evt.target.id); - this.args.linking = false; - this.args.linkEnabled = false; - if (this.isVertex(evt.target)) { - this.getDataset().addEdge(this.linkNodeSource + "_" + this.linkNodeTarget, this.linkNodeSource, this.linkNodeTarget, {}); - } - this.linkSVGNode.parentNode.removeChild(this.linkSVGNode); - } - return; - } - - /** Id is a vertex or the canvas **/ - if (this.isVertex(evt.target) || this.isNodeCanvas(evt.target) || this.isNodeBackground(evt.target)) { - this._startDragging(evt); - } - /** if i is edge **/ - if (this.isEdge(evt.target)) { - this.selectEdge(this.getEdgeIdFromSVGId(evt.target.getAttribute("id"))); - } - - if (this.args.multipleSelectionEnabled) { - if (!this.dragging) { - this.setSelecting(true); - this.selectorX = p.x; - this.selectorY = p.y; - this.displaySelection(p.x, p.y, 1, 1); - } - } - - } - if (event.button == 1) { - this.setLinking(false); - this.setMultipleSelection(false); - this.selecting = false; - - /** Id is a vertex or the canvas **/ - if (this.isVertex(evt.target) || this.isNodeCanvas(evt.target) || this.isNodeBackground(evt.target)) { - this._startDragging(evt); - } - } -}; - -GraphCanvas.prototype.mouseUp = function(event) { - if (!this.args.interactive) { - return; - } - - if (this.dragging) { - this._stopDragging(event); - if (this.isVertex(event.target)) { - var vertexId = this.getVertexIdFromSVGId(event.target.id); - if (this.getDataset().getVertexById(vertexId).getEdges().length >= this.args.maxNumberEdgesMoving) { - this.moveEdge(vertexId); - } - } - } - - if (this.selecting) { - this.setSelecting(false); - - var x1 = (parseFloat(this.selectorSVGNode.getAttribute("x")) - DOM.select(this.id).getAttribute("dragx")) / this.getFormatter().getWidth(); - var y1 = (parseFloat(this.selectorSVGNode.getAttribute("y")) - DOM.select(this.id).getAttribute("dragy")) / this.getFormatter().getHeight(); - var x2 = (x1 + parseFloat(this.selectorSVGNode.getAttribute("width") / this.formatter.getWidth())); - var y2 = (y1 + parseFloat(this.selectorSVGNode.getAttribute("height") / this.formatter.getHeight())); - - var verticesSelected = this.getLayout().getVerticesByArea(x1 / this.getFormatter().getZoomScale, y1 / this.getFormatter().getZoomScale, - x2 / this.getFormatter().getZoomScale, y2 / this.getFormatter().getZoomScale); - - for ( var i = 0; i < verticesSelected.length; i++) { - this.selectNode(verticesSelected[i].getId()); - } - - if (this.selectorSVGNode != null) { - this._svg.removeChild(this.selectorSVGNode); - } - - if (this.args.labeled) { - this.clearLabels(); - this.renderLabels(); - } - - this.selectorSVGNode = null; - // this.renderLabels(); - } -}; - -/** SELECTION **/ -GraphCanvas.prototype.displaySelection = function(x, y, width, height) { - if (this.selectorSVGNode != null) { - this.selectorSVGNode.setAttribute("x", x); - this.selectorSVGNode.setAttribute("y", y); - this.selectorSVGNode.setAttribute("width", width); - this.selectorSVGNode.setAttribute("height", height); - } else { - this.selectorSVGNode = SVG.drawRectangle(x, y, width, height, this._svg, { - "fill" : "red", - "stroke" : "black", - "opacity" : "0.2", - "stroke-opacity" : "1" - }); - } -}; - -/** DRAGGING **/ -GraphCanvas.prototype._startDragging = function(evt) { - if (!this.isDraggingCanvasEnabled()) { - if (this.isNodeCanvas(evt.target)) { - this.draggingElement = null; - } - } - - if (this.isVertex(evt.target) || (this.isNodeBackground(evt.target) && (this.isDraggingCanvasEnabled()))|| (this.isNodeCanvas(evt.target) && (this.isDraggingCanvasEnabled()))) { - this.clearLabels(); - this.draggingElement = evt.target; - this.dragging = true; - var p = this.getSVGCoordenates(evt); - - this.nMouseOffsetX = p.x - parseInt(evt.target.getAttribute("dragx")); - this.nMouseOffsetY = p.y - parseInt(evt.target.getAttribute("dragy")); - - if (this.isVertex(evt.target)) { - this.dragStartX = parseInt(this.draggingElement.getAttribute("dragx")) * this.getFormatter().getZoomScale() - + parseFloat(DOM.select(this.id).getAttribute("dragx")); - this.dragStartY = parseInt(this.draggingElement.getAttribute("dragy")) * this.getFormatter().getZoomScale() - + parseFloat(DOM.select(this.id).getAttribute("dragy")); - } else { - this.dragStartX = p.x - parseInt(this.draggingElement.getAttribute("dragx"));// + parseFloat(DOM.select(this.id).getAttribute("dragx")); - this.dragStartY = p.y - parseInt(this.draggingElement.getAttribute("dragy"));// + parseFloat(DOM.select(this.id).getAttribute("dragy")); - } - } -}; - -GraphCanvas.prototype._stopDragging = function(event) { - this.nMouseOffsetX = 0; - this.nMouseOffsetX = 0; - /** despues del evento up viene el evento click entonces acabo el dragging en el mouseclick **/ - this.dragging = false; - this.draggingElement = null; - this.renderLabels(); - - this.setLinking(false); - this.setMultipleSelection(true); - this.selecting = false; - -}; - -/** Move the edges of the vertex with the vertexId indicado **/ -GraphCanvas.prototype.moveEdge = function(vertexId) { - var x = this.getLayout().getNodeById(vertexId).x * this.getFormatter().getWidth(); - var y = this.getLayout().getNodeById(vertexId).y * this.getFormatter().getHeight(); - - /** Moving edges out **/ - for ( var i = 0; i < this.getDataset().getVertexById(vertexId).getEdgesOut().length; i++) { - var edgeId = this.getDataset().getVertexById(vertexId).getEdgesOut()[i].getId(); - var svgEdgeId = this.getSVGEdgeId(edgeId); - var edgeFormatter = this.getFormatter().getEdgeById(edgeId); - if (edgeFormatter instanceof LineEdgeGraphFormatter) { - DOM.select(svgEdgeId + "_shadow").setAttribute("x2", x); - DOM.select(svgEdgeId + "_shadow").setAttribute("y2", y); - DOM.select(svgEdgeId).setAttribute("x2", x); - DOM.select(svgEdgeId).setAttribute("y2", y); - } - - if ((edgeFormatter instanceof DirectedLineEdgeGraphFormatter) || (edgeFormatter instanceof OdirectedLineEdgeGraphFormatter) - || (edgeFormatter instanceof OdotDirectedLineEdgeGraphFormatter) || (edgeFormatter instanceof DotDirectedLineEdgeGraphFormatter) - || (edgeFormatter instanceof CutDirectedLineEdgeGraphFormatter)) { - this.removeEdge(edgeId); - this.renderEdge(edgeId); - } - } - - /** Moving edges in **/ - for ( var i = 0; i < this.getDataset().getVertexById(vertexId).getEdgesIn().length; i++) { - var edgeId = this.getDataset().getVertexById(vertexId).getEdgesIn()[i].getId(); - var svgEdgeId = this.getSVGEdgeId(edgeId); - var edgeFormatter = this.getFormatter().getEdgeById(edgeId); - if (edgeFormatter instanceof LineEdgeGraphFormatter) { - DOM.select(svgEdgeId).setAttribute("x1", x); - DOM.select(svgEdgeId).setAttribute("y1", y); - DOM.select(svgEdgeId + "_shadow").setAttribute("x1", x); - DOM.select(svgEdgeId + "_shadow").setAttribute("y1", y); - } - - if ((edgeFormatter instanceof DirectedLineEdgeGraphFormatter) || (edgeFormatter instanceof OdirectedLineEdgeGraphFormatter) - || (edgeFormatter instanceof OdotDirectedLineEdgeGraphFormatter) || (edgeFormatter instanceof DotDirectedLineEdgeGraphFormatter) - || (edgeFormatter instanceof CutDirectedLineEdgeGraphFormatter)) { - this.removeEdge(edgeId); - this.renderEdge(edgeId); - } - - if (edgeFormatter instanceof BezierEdgeGraphFormatter) { - var radius = this.getFormatter().getVertexById(vertexId).getDefault().getSize() * this.getFormatter().getNodesMaxSize(); - var d = this.calculateCoordenatesBezier(radius, x, y); - DOM.select(svgEdgeId).setAttribute("d", d); - } - } -}; - -GraphCanvas.prototype.moveNode = function(vertexId) { - var x = this.getLayout().getNodeById(vertexId).x * this.getFormatter().getWidth(); - var y = this.getLayout().getNodeById(vertexId).y * this.getFormatter().getHeight(); - var svgNodeElement = DOM.select(this.getSVGNodeId(vertexId)); - - svgNodeElement.setAttribute("dragx", x); - svgNodeElement.setAttribute("dragy", y); - svgNodeElement.setAttribute("transform", "translate(" + x + "," + y + ")"); - - if (this.getDataset().getVertexById(vertexId).getEdges().length < this.args.maxNumberEdgesMoving) { - this.moveEdge(vertexId); - } -}; - -GraphCanvas.prototype._movingNode = function(svgNodeElement, x, y) { - var vertexId = this.getVertexIdFromSVGId(svgNodeElement.getAttribute("id")); - this.getLayout().getNodeById(vertexId).setCoordinates(x / this.getFormatter().getWidth(), y / this.getFormatter().getHeight()); - this.desplazamientoX = 0; - this.desplazamientoY = 0; - this.removeLabel(vertexId); - this.renderLabel(vertexId); -}; - -/** INIT **/ -GraphCanvas.prototype.init = function() { - - this._svg = this.createSVGDom(this.targetID, this.id, this.getFormatter().getWidth(), this.getFormatter().getHeight(), this.getFormatter() - .getBackgroundColor()); - this.GraphGroup = SVG.drawGroup(this._svg, [ [ "id", this.args.idGraph ], [ "transform", "translate(0,0), scale(1)" ] ]); - this.GraphBackground = SVG.drawGroup(this.GraphGroup, [ [ "id", this.args.idBackground ] ]); - this.GraphEdgeGroup = SVG.drawGroup(this.GraphGroup, [ [ "id", this.args.idEdgesGraph ] ]); - this.GraphNodeGroup = SVG.drawGroup(this.GraphGroup, [ [ "id", this.args.idNodesGraph ] ]); - this.GraphLabelGroup = SVG.drawGroup(this.GraphGroup, [ [ "id", this.args.idLabelGraph ] ]); - - if ((this.getFormatter().getBackgroundImage() != null) && (this.getFormatter().getBackgroundImage() != "")) { - this.setBackgroundImage(this.getFormatter().getBackgroundImage()); - } - /** SVG Events listener */ - var _this = this; - this._svg.addEventListener("click", function(event) { - _this.mouseClick(event); - }, false); - this._svg.addEventListener("mousemove", function(event) { - _this.mouseMove(event, _this); - }, false); - this._svg.addEventListener("mousedown", function(event) { - _this.mouseDown(event, _this); - }, false); - this._svg.addEventListener("mouseup", function(event) { - _this.mouseUp(event, _this); - }, false); -}; - -/* - GraphCanvas.prototype.backgroungToSVG = function(){ - var _this = this; - var canvas = document.createElement('canvas'); - canvas.setAttribute("id", "canvas"); - canvas.width = this.formatter.getWidth(); - canvas.height = this.formatter.getHeight(); - - this._svg.parentNode.parentNode.appendChild(canvas); - var ctx = document.getElementById('canvas').getContext('2d'); - var img = new Image(); - - img.src = this.formatter.getBackgroundImage(); - ctx.drawImage(img,0,0 ,_this.formatter.getWidth(), _this.formatter.getHeight()); - - - img.onload = function() { - canvas.parentNode.removeChild(canvas); - } - - this.NodeSVGbackgroundImage.setAttribute("xlink:href", document.getElementById("canvas").toDataURL()); - this.NodeSVGbackgroundImage.removeAttribute("href"); - - // - - };*/ - -GraphCanvas.prototype.setBackgroundImage = function() { - if (this.NodeSVGbackgroundImage != null) { - this.NodeSVGbackgroundImage.parentNode.removeChild(this.NodeSVGbackgroundImage); - } - $('#' + this.targetID).svg(); - $('#' + this.targetID).svg("get"); - - $('#' + this.targetID).svg("get")._svg = document.getElementById(this.id); - - var svg = $('#' + this.targetID).svg("get"); - this.NodeSVGbackgroundImage = svg.image(0, 0, this.getFormatter().getWidth(), this.getFormatter().getHeight(), this.getFormatter() - .getBackgroundImage()); - this.NodeSVGbackgroundImage.setAttribute("id", this.args.idBackgroundNode); - - this.NodeSVGbackgroundImage.setAttribute("x", 0); - this.NodeSVGbackgroundImage.setAttribute("y", 0); - - this.NodeSVGbackgroundImage.setAttribute("dragx", 0); - this.NodeSVGbackgroundImage.setAttribute("dragy", 0); - - if (this.getFormatter().args.backgroundImageHeight != null) { - this.NodeSVGbackgroundImage.setAttribute("height", this.getFormatter().args.backgroundImageHeight); - } - if (this.getFormatter().args.backgroundImageWidth != null) { - this.NodeSVGbackgroundImage.setAttribute("width", this.getFormatter().args.backgroundImageWidth); - } - - if (this.getFormatter().args.backgroundImageX != null) { - this.NodeSVGbackgroundImage.setAttribute("x", this.getFormatter().args.backgroundImageX); - } - if (this.getFormatter().args.backgroundImageY != null) { - this.NodeSVGbackgroundImage.setAttribute("y", this.getFormatter().args.backgroundImageY); - } - - this.GraphBackground.appendChild(this.NodeSVGbackgroundImage); - this.NodeSVGbackgroundImage.removeAttribute("href"); - this.NodeSVGbackgroundImage.setAttribute("xlink:href", this.getFormatter().getBackgroundImage()); -}; - -GraphCanvas.prototype.removeBackgroundImage = function() { - if (this.NodeSVGbackgroundImage != null) { - this.NodeSVGbackgroundImage.parentNode.removeChild(this.NodeSVGbackgroundImage); - } -}; - -GraphCanvas.prototype._setBackgroundColor = function(color) { - var attributes = [ [ "fill", color ] ]; - SVG.drawRectangle(0, 0, this.getFormatter().getWidth(), this.getFormatter().getHeight(), this.GraphBackground, attributes); -}; - -/** Serialize **/ -GraphCanvas.prototype.toJSON = function() { - var json = {}; - json.dataset = {}; - json.formatter = {}; - json.layout = {}; - json.dataset = this.getDataset().toJSON(); - json.formatter = this.getFormatter().toJSON(); - json.layout = this.getLayout().toJSON(); - return json; -}; - -GraphCanvas.prototype.toHTML = function() { - //this.backgroungToSVG(); - var html = this._svg.parentElement.innerHTML; - - var start = html.indexOf("") + 6; - - return html.substr(start, end); -}; - -/** DRAW **/ -GraphCanvas.prototype.draw = function(graphdataset, graphformatter, graphlayout) { - this.setDataset(graphdataset); - this.setFormatter(graphformatter); - this.setLayout(graphlayout); - - var _this = this; - this.getFormatter().changed.attach(function(sender, item) { - _this.removeNode(item.getId()); - _this.renderNode(item.getId()); - if (_this.args.labeled) { - _this.removeLabel(item.getId()); - _this.renderLabel(item.getId()); - } - - }); - //TODO - this.getFormatter().edgeChanged.attach(function(sender, item) { - _this.removeEdge(item.getId()); - _this.renderEdge(item.getId()); - }); - - this.getFormatter().resized.attach(function(sender, item) { - _this.resize(_this.getFormatter().getWidth(), _this.getFormatter().getHeight()); - }); - - this.getFormatter().backgroundImageChanged.attach(function(sender, item) { - _this.setBackgroundImage(_this.getFormatter().getBackgroundImage()); - }); - - this.getFormatter().backgroundColorChanged.attach(function(sender, item) { - _this._setBackgroundColor(_this.getFormatter().getBackgroundColor()); - }); - - this.getLayout().changed.attach(function(sender, item) { - _this.moveNode(item.getId()); - _this.moveEdge(item.getId()); - if (_this.args.labeled) { - _this.removeLabel(item.getId()); - _this.renderLabel(item.getId()); - } - }); - - this.getDataset().newVertex.attach(function(sender, item) { - - _this.renderNode(item.getId()); - if (_this.args.labeled) { - _this.renderLabel(item.getId()); - } - }); - - this.getDataset().newEdge.attach(function(sender, item) { - _this.renderEdge(item.getId()); - }); - - this.getDataset().vertexDeleted.attach(function(sender, item) { - _this.removeNode(item.getId()); - if (_this.args.labeled) { - _this.removeLabel(item.getId()); - } - }); - - this.getDataset().edgeDeleted.attach(function(sender, item) { - _this.removeEdge(item.getId()); - }); - - this.getDataset().vertexNameChanged.attach(function(sender, args) { - if (_this.args.labeled) { - _this.removeLabel(args.item.getId()); - _this.removeLabel(args.item.getId()); - _this.renderLabel(args.item.getId()); - } - }); - this.init(); - this.render(); -}; - -GraphCanvas.prototype.render = function() { - for ( var id in this.getDataset().getVertices()) { - this.renderNode(id); - } - this.renderLabels(); - this.renderEdges(); -}; - -GraphCanvas.prototype.renderLabels = function() { - if (this.args.labeled) { - for ( var id in this.getDataset().getVertices()) { - this.renderLabel(id); - } - } -}; - -GraphCanvas.prototype.removeLabels = function() { - for ( var id in this.getDataset().getVertices()) { - this.removeLabel(id); - } -}; - -/** Utilities method for nodes **/ -GraphCanvas.prototype.isNodeCanvas = function(node) { - return ((node.id == this.args.idGraph) || (node.id == this.id)); -}; - -GraphCanvas.prototype.isNodeBackground = function(node) { - return ((node.id == this.args.idBackgroundNode)); -}; - -GraphCanvas.prototype.isVertex = function(node) { - if (node.getAttribute("id") != null) { - if (node.getAttribute("id").indexOf("_v_") != -1) { - return true; - } - } - return false; -}; - -GraphCanvas.prototype.isLabel = function(node) { - if (node.getAttribute("id") != null) { - if (node.getAttribute("id").indexOf("_l_") != -1) { - return true; - } - } - return false; -}; - -GraphCanvas.prototype.isEdge = function(node) { - if (node.getAttribute("id") != null) { - if (node.getAttribute("id").indexOf("_e_") != -1) { - return true; - } - } - return false; -}; - -/** Resize **/ -GraphCanvas.prototype.resize = function(width, height) { - // this._svg.setAttribute("width", width); - // this._svg.setAttribute("height", height); - if (this.NodeSVGbackgroundImage != null) { - this.NodeSVGbackgroundImage.setAttribute("width", width); - this.NodeSVGbackgroundImage.setAttribute("height", height); - } - - this._svg.setAttribute("width", width); - this._svg.setAttribute("height", height); - - this.clearCanvas(); - this.render(); -}; - -GraphCanvas.prototype.clearCanvas = function() { - DOM.removeChilds(this.GraphEdgeGroup.getAttribute("id")); - DOM.removeChilds(this.GraphNodeGroup.getAttribute("id")); - this.clearLabels(); -}; - -GraphCanvas.prototype.clearLabels = function() { - DOM.removeChilds(this.GraphLabelGroup.getAttribute("id")); -}; - -/** ID'S converter **/ -GraphCanvas.prototype.getSVGNodeId = function(nodeId) { - return this.id + "_v_" + nodeId; -}; - -GraphCanvas.prototype.getSVGEdgeId = function(edgeId) { - return this.id + "_e_" + edgeId; -}; - -GraphCanvas.prototype.getSVGArrowEdgeId = function(edgeId) { - return this.id + "_arrow_" + edgeId; -}; - -GraphCanvas.prototype.getSVGLabelId = function(edgeId) { - return this.id + "_l_" + edgeId; -}; - -GraphCanvas.prototype.blinkVertexById = function(vertexId) { - $("#" + this.getSVGNodeId(vertexId)).fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut(); -}; - -GraphCanvas.prototype.getVertexIdFromSVGId = function(svgVertexId) { - return svgVertexId.replace(this.id, "").replace("_v_", ""); -}; - -GraphCanvas.prototype.getEdgeIdFromSVGId = function(svgEdgeId) { - return svgEdgeId.replace(this.id, "").replace("_e_", ""); -}; - -/** VERTEX **/ -GraphCanvas.prototype.getVertexById = function(id) { - return document.getElementById(this.getSVGNodeId(id)); -}; - -GraphCanvas.prototype.renderNodes = function() { - for ( var id in this.getDataset().getVertices()) { - this.renderNode(id); - } -}; - -GraphCanvas.prototype.overNode = function(nodeId) { - if (!this.args.interactive) { - return; - } - /** If selected we don't change the format **/ - if (this.args.isVertexSelected[nodeId] == null) { - var args = this.getFormatter().getVertexById(nodeId).getOver(); - args.args["cursor"] = 'pointer'; - this.changeVertexFormat(nodeId, args); - } -}; - -GraphCanvas.prototype.outNode = function(nodeId) { - if (!this.args.interactive) { - return; - } - - /** If selected we don't change the format **/ - if (this.args.isVertexSelected[nodeId] == null) { - this.changeVertexFormat(nodeId, this.getFormatter().getVertexById(nodeId).getDefault()); - } -}; - -GraphCanvas.prototype.overLabel = function(nodeId) { - this.overNode(nodeId); - // this.svgLabels[nodeId].setAttribute("cursor", "pointer"); -}; - -GraphCanvas.prototype.outLabel = function(nodeId) { - this.outNode(nodeId); - // this.svgLabels[nodeId].setAttribute("cursor", ""); -}; - -GraphCanvas.prototype.clickNode = function(nodeId) { - if (!this.args.interactive) { - return; - } - - /** si el evento se dispara oprque estaba dragging entonces no activo nada **/ - if (this.args.isVertexSelected[nodeId] == null) { - this.selectNode(nodeId); - } else { - this.deselectNode(nodeId); - } -}; - -GraphCanvas.prototype.selectNode = function(nodeId) { - for ( var i = 0; i < this.args.selectedVertices.length; i++) { - var format = this.getFormatter().getVertexById(nodeId).getSelected(); - format.opacity = 0.2; - this.changeVertexFormat(nodeId, this.getFormatter().getVertexById(nodeId).getSelected()); - } - - if (this.args.isVertexSelected[nodeId] == null) { - var format = this.getFormatter().getVertexById(nodeId).getSelected(); - format.opacity = 1; - this.changeVertexFormat(nodeId, this.getFormatter().getVertexById(nodeId).getSelected()); - this.args.selectedVertices.push(nodeId); - this.args.isVertexSelected[nodeId] = this.args.selectedVertices.length - 1; - this.onVertexSelect.notify(nodeId); - } -}; - -GraphCanvas.prototype.selectAllEdges = function() { - this.deselectNodes(); - this.deselectEdges(); - - for ( var edgesId in this.getDataset().edges) { - this.selectEdge(edgesId); - } -}; - -GraphCanvas.prototype.selectAllNodes = function() { - this.deselectNodes(); - this.deselectEdges(); - - for ( var vertexId in this.getDataset().vertices) { - this.selectNode(vertexId); - } -}; - -GraphCanvas.prototype.selectAll = function() { - this.deselectNodes(); - this.deselectEdges(); - - for ( var vertexId in this.getDataset().vertices) { - this.selectNode(vertexId); - } - - for ( var edgesId in this.getDataset().edges) { - this.selectEdge(edgesId); - } -}; - -GraphCanvas.prototype.selectEdge = function(edgeId) { - if (this.args.isEdgeSelected[edgeId] == null) { - this.changeEdgeFormat(edgeId, this.getFormatter().getEdgeById(edgeId).getSelected()); - //this.args.selectedEdges.push(edgeId); - this.args.isEdgeSelected[edgeId] = true; //this.args.selectedEdges.length - 1; - this.onEdgeSelect.notify(edgeId); - } -}; - -GraphCanvas.prototype.selectEdges = function(edges) { - - for ( var i = 0; i < edges.length; i++) { - this.selectEdge(edges[i]); - } -}; - -GraphCanvas.prototype.deselectNode = function(nodeId) { - if (this.args.isVertexSelected[nodeId] != null) { - this.changeVertexFormat(nodeId, this.getFormatter().getVertexById(nodeId).getDefault()); - this.args.selectedVertices.splice(this.args.isVertexSelected[nodeId], 1); - var index = this.args.isVertexSelected[nodeId]; - delete this.args.isVertexSelected[nodeId]; - - for ( var vertex in this.args.isVertexSelected) { - if (this.args.isVertexSelected[vertex] > index) { - this.args.isVertexSelected[vertex] = this.args.isVertexSelected[vertex] - 1; - } - } - } -}; - -GraphCanvas.prototype.deselectNodes = function() { - var selected = JSON.parse(JSON.stringify(this.getSelectedVertices())); - for ( var i = 0; i < selected.length; i++) { - this.deselectNode(selected[i]); - } -}; -GraphCanvas.prototype.selectNodes = function(idNodes) { - - for ( var i = 0; i < idNodes.length; i++) { - this.selectNode(idNodes[i]); - } - - // for ( var vertex in this.args.isVertexSelected) { - // if (this.args.isVertexSelected[vertex] > index){ - // this.args.isVertexSelected[vertex] = this.args.isVertexSelected[vertex] - 1; - // } - // } - -}; - -GraphCanvas.prototype.changeVertexFormat = function(nodeId, format) { - var svgNode = DOM.select(this.getSVGNodeId(nodeId)); - if (svgNode != null) { - var properties = format.toJSON(); - for ( var item in properties) { - svgNode.setAttribute(item, properties[item]); - } - - if (this.getFormatter().getVertexById(nodeId) instanceof CircleVertexGraphFormatter) { - var transform = "translate(" + svgNode.getAttribute("dragx") + "," + svgNode.getAttribute("dragy") + "), scale(" + format.getSize() + ")"; - svgNode.setAttribute("transform", transform); - } - } -}; - -GraphCanvas.prototype.renderLabel = function(nodeId) { - var x = Math.ceil(this.getLayout().getNodeById(nodeId).x * this.getFormatter().getWidth()); - var y = Math.ceil(this.getLayout().getNodeById(nodeId).y * this.getFormatter().getHeight()); - - var svgAttributesNode = JSON.parse(JSON.stringify(this.getFormatter().getVertexById(nodeId).getDefault().toJSON().title)); - svgAttributesNode.id = this.getSVGLabelId(this.getDataset().getVertexById(nodeId).getId()); - svgAttributesNode.dx = (-1) * (this.getDataset().getVertexById(nodeId).getName().length * svgAttributesNode["font-size"]) / 4 - 4; - - svgAttributesNode.dy = parseFloat((this.getFormatter().getVertexById(nodeId).getDefault().getSize())) - + parseFloat(svgAttributesNode["font-size"]) + parseFloat(this.getFormatter().getVertexById(nodeId).getDefault().getStrokeWidth()) - 4; - svgAttributesNode.dragx = Math.ceil(this.getLayout().getNodeById(nodeId).x * this.getFormatter().getWidth()); - - var gragy = parseFloat(this.getFormatter().getVertexById(nodeId).getDefault().getSize()) - + Math.ceil(this.getLayout().getNodeById(nodeId).y * this.getFormatter().getHeight()); - svgAttributesNode.dragy = gragy; - svgAttributesNode.transform = "translate(" + svgAttributesNode.dragx + "," + svgAttributesNode.dragy + ")";//, scale("+this.formatter.getVertexById(nodeId).getDefault().getSize()+")"; - - var nodeSVG = SVG.drawText(0, 0, this.getDataset().getVertexById(nodeId).getName(), this.GraphLabelGroup, svgAttributesNode); - - this.svgLabels[nodeId] = nodeSVG; - - /** Events for the SVG node **/ - var _this = this; - if (nodeSVG != null) { - nodeSVG.addEventListener("mouseover", function() { - _this.overLabel(nodeId); - }, false); - nodeSVG.addEventListener("mouseout", function() { - _this.outLabel(nodeId); - }, false); - } - -}; - -GraphCanvas.prototype.removeLabel = function(labelId) { - if (DOM.select(this.getSVGLabelId(labelId)) != null) { - DOM.select(this.getSVGLabelId(labelId)).parentNode.removeChild(DOM.select(this.getSVGLabelId(labelId))); - } -}; - -GraphCanvas.prototype.renderNode = function(nodeId) { - var svgAttributesNode = JSON.parse(JSON.stringify(this.getFormatter().getVertexById(nodeId).getDefault().toJSON())); - svgAttributesNode.dragx = Math.ceil(this.getLayout().getNodeById(nodeId).x * this.getFormatter().getWidth()); - svgAttributesNode.dragy = Math.ceil(this.getLayout().getNodeById(nodeId).y * this.getFormatter().getHeight()); - svgAttributesNode.transform = "translate(" + svgAttributesNode.dragx + "," + svgAttributesNode.dragy + ")"; - svgAttributesNode.id = this.getSVGNodeId(nodeId); - /*svgAttributesNode["stroke-width"] = 3 ; - svgAttributesNode["stroke-opacity"] = 1 ; - svgAttributesNode["fill-opacity"] = svgAttributesNode["opacity"] ; - svgAttributesNode["opacity"] = 1 ;*/ - this.circleDefaultRadius = this.getFormatter().getVertexById(nodeId).getDefault().getSize(); - var nodeSVG; - - if (this.getFormatter().getVertexById(nodeId) instanceof CircleVertexGraphFormatter) { - nodeSVG = SVG.drawCircle(0, 0, this.circleDefaultRadius, this.GraphNodeGroup, svgAttributesNode); - } - - if (this.getFormatter().getVertexById(nodeId) instanceof SquareVertexGraphFormatter) { - //nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius) ,0 - (this.formatter.getVertexById(nodeId).getDefault().getSize()) , (this.getFormatter().getVertexById(nodeId).getDefault().getSize()*2), (this.getFormatter().getVertexById(nodeId).getDefault().getSize()*2), this.GraphNodeGroup, svgAttributesNode); - nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius), 0 - (this.circleDefaultRadius), (this.circleDefaultRadius * 2), - (this.circleDefaultRadius * 2), this.GraphNodeGroup, svgAttributesNode); - } - - if (this.getFormatter().getVertexById(nodeId) instanceof EllipseVertexGraphFormatter) { - nodeSVG = SVG.drawEllipse(0, 0, this.circleDefaultRadius * 1.5, this.circleDefaultRadius, this.GraphNodeGroup, svgAttributesNode); - } - - if (this.getFormatter().getVertexById(nodeId) instanceof RectangleVertexGraphFormatter) { - //nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius) ,0 - ((this.circleDefaultRadius*2)/2) , (this.circleDefaultRadius*2), (this.circleDefaultRadius), this.GraphNodeGroup, svgAttributesNode); - nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius * 1.5), 0 - (this.circleDefaultRadius), (this.circleDefaultRadius * 2 * 1.5), - (this.circleDefaultRadius * 2), this.GraphNodeGroup, svgAttributesNode); - - } - - if (this.getFormatter().getVertexById(nodeId) instanceof RoundedVertexGraphFormatter) { - svgAttributesNode.ry = 2;// this.formatter.getVertexById(nodeId).getDefault().getSize()/4; - svgAttributesNode.rx = 2;// this.formatter.getVertexById(nodeId).getDefault().getSize()/4; - nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius * 1.5), 0 - (this.circleDefaultRadius), (this.circleDefaultRadius * 2 * 1.5), - (this.circleDefaultRadius * 2), this.GraphNodeGroup, svgAttributesNode); - } - - // - - if (this.getFormatter().getVertexById(nodeId) instanceof OctagonVertexGraphFormatter) { - svgAttributesNode.ry = 2; - svgAttributesNode.rx = 2; - nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius * 1.5), 0 - (this.circleDefaultRadius), (this.circleDefaultRadius * 2 * 1.5), - (this.circleDefaultRadius * 2), this.GraphNodeGroup, svgAttributesNode); - } - - nodeSVG.internalId = nodeId; - // - var _this = this; - - /** Events for the SVG node **/ - if (nodeSVG != null) { - nodeSVG.addEventListener("mouseover", function() { - _this.onVertexOver.notify(nodeId); - _this.overNode(nodeId); - }, false); - nodeSVG.addEventListener("mouseout", function() { - _this.onVertexOut.notify(nodeId); - _this.outNode(nodeId); - }, false); - //nodeSVG.addEventListener("click", function(){_this.clickNode(nodeId);}, false); - // - nodeSVG.addEventListener("mouseup", function() { - _this.onVertexUp.notify(nodeId); - }, false); - } -}; - -GraphCanvas.prototype.removeNode = function(nodeId) { - DOM.select(this.getSVGNodeId(nodeId)).parentNode.removeChild(DOM.select(this.getSVGNodeId(nodeId))); - if (this.args.labeled) { - this.removeLabel(nodeId); - } -}; - -/** REMOVING **/ -GraphCanvas.prototype.removeSelected = function() { - /** El orden importa **/ - this.removeSelectedEdges(); - this.removeSelectedNode(); - -}; - -GraphCanvas.prototype.removeSelectedNode = function() { - var selected = JSON.parse(JSON.stringify(this.getSelectedVertices())); - this.deselectNodes(); - var sorted = selected.sort(function(a, b) { - return a - b - }); - for ( var i = 0; i < sorted.length; i++) { - if (this.getDataset().getVertexById(sorted[i]) != null) { - this.getDataset().getVertexById(sorted[i]).remove(); - } - } -}; - -/** EDGES **/ -GraphCanvas.prototype.removeEdge = function(edgeId) { - if (DOM.select(this.getSVGEdgeId(edgeId)) != null) { - DOM.select(this.getSVGEdgeId(edgeId)).parentNode.removeChild(DOM.select(this.getSVGEdgeId(edgeId))); - } - - if (DOM.select(this.getSVGEdgeId(edgeId) + "_shadow") != null) { - DOM.select(this.getSVGEdgeId(edgeId) + "_shadow").parentNode.removeChild(DOM.select(this.getSVGEdgeId(edgeId) + "_shadow")); - } - - if (DOM.select(this.getSVGArrowEdgeId(edgeId)) != null) { - DOM.select(this.getSVGArrowEdgeId(edgeId)).parentNode.removeChild(DOM.select(this.getSVGArrowEdgeId(edgeId))); - } -}; - -GraphCanvas.prototype.overEdge = function(edgeId) { - if ((!this.args.interactive) || this.dragging || this.selecting) { - return; - } - - /** If selected we don't change the format **/ - if (this.args.isEdgeSelected[edgeId] == null) { - var format = this.getFormatter().getEdgeById(edgeId).getOver(); - format.args["cursor"] = "pointer"; - this.changeEdgeFormat(edgeId, format); - } -}; - -GraphCanvas.prototype.outEdge = function(edgeId) { - if (!this.args.interactive) { - return; - } - - /** If selected we don't change the format **/ - if (this.args.isEdgeSelected[edgeId] == null) { - this.changeEdgeFormat(edgeId, this.getFormatter().getEdgeById(edgeId).getDefault()); - } -}; - -GraphCanvas.prototype.changeEdgeFormat = function(edgeId, format) { - var svgEdge = DOM.select(this.getSVGEdgeId(edgeId) + "_shadow"); - if (svgEdge != null) { - var properties = format.toJSON(); - for ( var item in properties) { - svgEdge.setAttribute(item, properties[item]); - } - } -}; - -GraphCanvas.prototype.deselectEdge = function(edgeID) { - if (this.args.isEdgeSelected[edgeID] != null) { - this.changeEdgeFormat(edgeID, this.getFormatter().getEdgeById(edgeID).getDefault()); - var index = this.args.isEdgeSelected[edgeID]; - delete this.args.isEdgeSelected[edgeID]; - } -}; - -GraphCanvas.prototype.deselectEdges = function() { - var selected = JSON.parse(JSON.stringify(this.getSelectedEdges())); - for ( var i = 0; i < selected.length; i++) { - this.deselectEdge(selected[i]); - } -}; - -GraphCanvas.prototype.removeSelectedEdges = function() { - var selected = JSON.parse(JSON.stringify(this.getSelectedEdges())); - this.deselectEdges(); - for ( var i = 0; i < selected.length; i++) { - if (this.getDataset().getEdgeById(selected[i]) != null) { - this.getDataset().getEdgeById(selected[i]).remove(); - } - } -}; - -GraphCanvas.prototype.renderEdge = function(edgeId) { - var svgAttributesEdge = this.getFormatter().getEdgeById(edgeId).getDefault().toJSON(); - var edge = this.getDataset().getEdgeById(edgeId); - - var svgNodeTarget = this.getVertexById(edge.getNodeTarget().getId()); - var svgNodeSource = this.getVertexById(edge.getNodeSource().getId()); - svgAttributesEdge.id = this.getSVGEdgeId(edge.getId()) + "_shadow"; - - var svgEdge = null; - - if (this.getFormatter().getEdgeById(edgeId) instanceof LineEdgeGraphFormatter) { - var coordenateSourceX = svgNodeSource.getAttribute("dragx"); - var coordenateSourceY = svgNodeSource.getAttribute("dragy"); - var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); - var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); - - SVG.drawLine(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, this.GraphEdgeGroup, svgAttributesEdge); - var attributesShadow = {}; - attributesShadow.id = this.getSVGEdgeId(edge.getId()); - attributesShadow["stroke-opacity"] = 0; - attributesShadow["stroke-width"] = 4; - attributesShadow["stroke"] = "black"; - svgEdge = SVG.drawLine(svgNodeSource.getAttribute("dragx"), svgNodeSource.getAttribute("dragy"), svgNodeTarget.getAttribute("dragx"), - svgNodeTarget.getAttribute("dragy"), this.GraphEdgeGroup, attributesShadow); - } - - if (this.getFormatter().getEdgeById(edgeId) instanceof BezierEdgeGraphFormatter) { - var nodeId = edge.getNodeTarget().getId(); - var nodeSize = this.formatter.getVertexById(nodeId).getDefault().getSize() * this.getFormatter().getNodesMaxSize(); - svgAttributesEdge.fill = "none"; - svgAttributesEdge.id = this.getSVGEdgeId(edgeId); - var d = this.calculateCoordenatesBezier(nodeSize, svgNodeSource.getAttribute("dragx"), svgNodeSource.getAttribute("dragy")); - svgEdge = SVG.drawPath(d, this.GraphEdgeGroup, svgAttributesEdge); - } - ; - - if ((this.getFormatter().getEdgeById(edgeId) instanceof DirectedLineEdgeGraphFormatter) - || (this.getFormatter().getEdgeById(edgeId) instanceof CutDirectedLineEdgeGraphFormatter) - || (this.getFormatter().getEdgeById(edgeId) instanceof DotDirectedLineEdgeGraphFormatter) - || (this.getFormatter().getEdgeById(edgeId) instanceof OdotDirectedLineEdgeGraphFormatter) - || (this.getFormatter().getEdgeById(edgeId) instanceof OdirectedLineEdgeGraphFormatter)) { - var coordenateSourceX = svgNodeSource.getAttribute("dragx"); - var coordenateSourceY = svgNodeSource.getAttribute("dragy"); - var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); - var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); - - var offset = parseFloat(this.getFormatter().getVertexById(this.getDataset().getEdgeById(edgeId).getNodeTarget().getId()).getDefault() - .getSize() - * this.circleDefaultRadius); - var point = this._calculateEdgePointerPosition(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, offset); - coordenateTargetX = point.x; - coordenateTargetY = point.y; - SVG.drawLine(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, this.GraphEdgeGroup, svgAttributesEdge); - - var attributesShadow = {}; - attributesShadow.id = this.getSVGEdgeId(edge.getId()); - attributesShadow["stroke-opacity"] = 0; - attributesShadow["stroke-width"] = 4; - attributesShadow["stroke"] = "black"; - svgEdge = SVG.drawLine(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, this.GraphEdgeGroup, attributesShadow); - } - - if (this.getFormatter().getEdgeById(edgeId) instanceof DirectedLineEdgeGraphFormatter - || (this.getFormatter().getEdgeById(edgeId) instanceof OdirectedLineEdgeGraphFormatter)) { - var coordenateSourceX = svgNodeSource.getAttribute("dragx"); - var coordenateSourceY = svgNodeSource.getAttribute("dragy"); - var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); - var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); - - var point = this._calculateEdgePointerPosition(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, offset); - coordenateTargetX = point.x; - coordenateTargetY = point.y; - - var angle = Geometry.toDegree(point.angle) + 90; - this.arrowDefaultSize = this.getFormatter().getEdgeById(edgeId).getArrowSize(); //getDefault().getArrowSize(); - var d = "-" + this.arrowDefaultSize + ",0 0,-" + parseFloat(this.arrowDefaultSize) * 2 + " " + this.arrowDefaultSize + ",0"; - - var attributes; - - if (this.getFormatter().getEdgeById(edgeId) instanceof DirectedLineEdgeGraphFormatter) { - attributes = [ - [ "fill", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], - [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], [ "id", this.getSVGArrowEdgeId(edgeId) ] ]; - } else { - attributes = [ - [ "fill", "#FFFFFF" ], [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], - [ "id", this.getSVGArrowEdgeId(edgeId) ] ]; - } - - var flechaSVGNode = SVG.drawPoligon(d, this.GraphEdgeGroup, attributes);//, ["transform", "rotate("+angle+"), translate(0,0)"]]); - flechaSVGNode.setAttribute("transform", " translate(" + coordenateTargetX + ", " + coordenateTargetY + "), rotate(" + angle + ")"); - } - ; - - if (this.getFormatter().getEdgeById(edgeId) instanceof CutDirectedLineEdgeGraphFormatter) { - var coordenateSourceX = svgNodeSource.getAttribute("dragx"); - var coordenateSourceY = svgNodeSource.getAttribute("dragy"); - var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); - var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); - - var point = this._calculateEdgePointerPosition(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, offset); - coordenateTargetX = point.x; - coordenateTargetY = point.y; - - var angle = Geometry.toDegree(point.angle) + 90; - - //this.arrowDefaultSize = 2; //getDefault().getArrowSize(); - var d = "-4,0 4,0 4,-2 -4,-2"; - - var flechaSVGNode = SVG.drawPoligon(d, this.GraphEdgeGroup, [ - [ "fill", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], - [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], [ "id", this.getSVGArrowEdgeId(edgeId) ] ]);//, ["transform", "rotate("+angle+"), translate(0,0)"]]); - flechaSVGNode.setAttribute("transform", " translate(" + coordenateTargetX + ", " + coordenateTargetY + "), rotate(" + angle + ")"); - } - ; - - if ((this.getFormatter().getEdgeById(edgeId) instanceof DotDirectedLineEdgeGraphFormatter) - || (this.getFormatter().getEdgeById(edgeId) instanceof OdotDirectedLineEdgeGraphFormatter)) { - var coordenateSourceX = svgNodeSource.getAttribute("dragx"); - var coordenateSourceY = svgNodeSource.getAttribute("dragy"); - var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); - var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); - var point = this._calculateEdgePointerPosition(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, offset); - coordenateTargetX = point.x; - coordenateTargetY = point.y; - var angle = Geometry.toDegree(point.angle) + 90; - // this.arrowDefaultSize = this.formatter.getEdgeById(edgeId).getArrowSize(); //getDefault().getArrowSize(); - var attributes = []; - if (this.getFormatter().getEdgeById(edgeId) instanceof OdotDirectedLineEdgeGraphFormatter) { - attributes = [ - [ "fill", "#FFFFFF" ], [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], - [ "id", this.getSVGArrowEdgeId(edgeId) ] ]; - } else { - attributes = [ - [ "fill", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], - [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], [ "id", this.getSVGArrowEdgeId(edgeId) ] ]; - } - var flechaSVGNode = SVG.drawCircle(0, 0, 4, this.GraphEdgeGroup, attributes); - flechaSVGNode.setAttribute("transform", " translate(" + coordenateTargetX + ", " + coordenateTargetY + "), rotate(" + angle + ")"); - } - ; - - var _this = this; - /** Events for the SVG edge **/ - if (svgEdge != null) { - if (this.getDataset().getEdgesCount() < this.args.maxNumberEdgesFiringEvents) { - svgEdge.addEventListener("mouseover", function() { - _this.overEdge(edgeId); - }, false); - svgEdge.addEventListener("mouseout", function() { - _this.outEdge(edgeId); - }, false); - } - } -}; - -GraphCanvas.prototype._calculateEdgePointerPosition = function(sourceX, sourceY, targetX, targetY, radius) { - var angle = Geometry.getAngleBetweenTwoPoints(sourceX, sourceY, targetX, targetY); - - /** Suponiendo el node source que este a la derecha **/ - if ((targetX - sourceX) < 0) { - var b = Geometry.getAdjacentSideOfRectangleRight(angle, radius); - targetX = parseFloat(targetX) + parseFloat(b); - arrowX = parseFloat(targetX) + parseFloat(b) + this.arrowDefaultSize / 2; - } else { - var b = Geometry.getAdjacentSideOfRectangleRight(angle, radius); - targetX = parseFloat(targetX) - parseFloat(b); - arrowX = parseFloat(targetX) - parseFloat(b) - this.arrowDefaultSize / 2; - } - - /** Suponiendo el node source que este a la arriba **/ - if ((targetY - sourceY) > 0) { - var a = Geometry.getOppositeSideOfRectangleRight(angle, radius); - targetY = parseFloat(targetY) - parseFloat(a); - arrowY = parseFloat(targetY) - parseFloat(a) - this.arrowDefaultSize / 2; - } else { - var a = Geometry.getOppositeSideOfRectangleRight(angle, radius); - targetY = parseFloat(targetY) + parseFloat(a); - arrowY = parseFloat(targetY) + parseFloat(a) - this.arrowDefaultSize / 2; - - } - - return { - "x" : arrowX, - "y" : arrowY, - "angle" : angle - }; -}; - -GraphCanvas.prototype.calculateCoordenatesBezier = function(nodeSize, x1, y1) { - var x11 = x1 - (nodeSize / 2); - var y11 = y1 - (nodeSize / 2); - - var x12 = parseFloat(x1) + parseFloat(nodeSize / 2); - var y12 = y1 - (nodeSize / 2); - - var curvePointX = (x12 - x11) / 2 + x11; - var curvePointY = y1 - (nodeSize * 2); - var d = "M" + x11 + "," + y11 + " T" + curvePointX + "," + curvePointY + " " + x12 + "," + y12; - return d; - -}; - -GraphCanvas.prototype.renderEdges = function() { - for ( var edge in this.getDataset().getEdges()) { - this.renderEdge(this.getDataset().getEdgeById(edge).getId()); - - } -}; - -GraphCanvas.prototype.getLastSelectedNode = function() { - var node = null; - if (this.getSelectedVertices().length > 0) { - var nodeId = this.getSelectedVertices()[this.getSelectedVertices().length - 1]; - node = this.getDataset().getVertexById(nodeId); - } - return node; -}; -/* - GraphCanvas.prototype.getNodeByNameAndIndex = function(node, index){ - var nodeId = this.getDataset().verticesIndex[node][index]; - var nodeItem = this.getDataset().getVertexById(nodeId); - return nodeItem; - }; - */ - -GraphCanvas.prototype.setDataset = function(dataset) { - this.dataset = dataset; -}; - -GraphCanvas.prototype.setFormatter = function(formatter) { - this.formatter = formatter; -}; - -GraphCanvas.prototype.setLayout = function(layout) { - this.layout = layout; -}; - -/** API **/ -GraphCanvas.prototype.getDataset = function() { - return this.dataset; -}; - -GraphCanvas.prototype.getFormatter = function() { - return this.formatter; -}; - -GraphCanvas.prototype.getLayout = function() { - return this.layout; -}; - -/** API DATASET **/ -GraphCanvas.prototype.addVertex = function(name, args) { - this.getDataset().addNode(name, args); -}; - -GraphCanvas.prototype.removeVertex = function(vertexId) { - this.getDataset().getVertexById(vertexId).remove(); -}; - -GraphCanvas.prototype.addEdge = function(edgeName, nodeSourceId, nodeTargetId, args) { - this.getDataset().addEdge(edgeName, nodeSourceId, nodeTargetId, args); -}; -/* - GraphCanvas.prototype.removeEdge = function(edgeId){ - this.getDataset().getEdgeById(edgeId).remove(); - }; - */ - -/** API FORMATTER **/ -GraphCanvas.prototype.getWidth = function() { - return this.getFormatter().getWidth(); -}; - -GraphCanvas.prototype.getHeight = function() { - return this.getFormatter().getHeight(); -}; - -GraphCanvas.prototype.getBackgroundImage = function() { - return this.getFormatter().getBackgroundImage(); -}; +/** + * Example form + * + * @witdh + * @height + */ +function ExampleForm(args) { + this.id = BUI.id(); + this.width = 700; + this.height = 500; + + if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } + } +} + +ExampleForm.prototype._getItems = function() { + return [{ + fieldLabel : 'First Name', + name : 'first', + allowBlank : false + }, { + fieldLabel : 'Last Name', + name : 'last', + allowBlank : false + } ]; +}; + +ExampleForm.prototype._getItems = function() { + return [ ]; +}; + +ExampleForm.prototype._getButtons = function() { + return [ ]; +}; + +ExampleForm.prototype.getPanel = function() { + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + margin : 10, + border : 1, + defaultType : 'textfield', + items : this._getItems(), + buttons : this._getButtons() + }); + return this.panel; +}; + +/** It populates the form **/ +ExampleForm.prototype.refresh = function(macromolecule) { +}; -//GraphCanvas.prototype.setBackgroundImage = function(value){ -// this.getFormatter().setBackgroundImage(value); -//}; +function ExperimentForm(args) { + this.id = BUI.id(); + + if (args != null) { + } + + this.onSaved = new Event(this); +} + +ExperimentForm.prototype._getItems = function(experiment) { + this.experiment = experiment; + var typeCombo = Ext.create('Ext.form.ComboBox', { + id : this.id + 'type', + fieldLabel : 'Type', + store : [ "STATIC", "CALIBRATION", "HPLC" ], + queryMode : 'local', + labelWidth : 120, + displayField : 'name', + valueField : 'name', + value : experiment.json.type, + disabled : (experiment.json.type == 'TEMPLATE') + }); + + var items = []; + + + if (experiment.json.type == "HPLC" ){ + var typeMacromolecule = BIOSAXS_COMBOMANAGER.getComboMacromoleculeByMacromolecules(BIOSAXS.proposal.getMacromolecules(), {labelWidth : 120, width: "120px"}); + if (experiment.getHPLCMacromolecule() != null){ + typeMacromolecule.setValue(experiment.getHPLCMacromolecule().macromoleculeId); + items.push(typeMacromolecule); + } + } + + + items.push(typeCombo, { + id : this.id + 'name', + xtype : 'textfield', + fieldLabel : 'Name', + labelWidth : 120, + width : '100%', + value : experiment.json.name + }, { + id : this.id + 'comments', + xtype : 'textareafield', + name : 'comments', + fieldLabel : 'Comments', + labelWidth : 120, + height : 120, + width : '100%', + value : experiment.json.comments + }); + return items; +}; +ExperimentForm.prototype.getPanel = function(experiment) { + var _this = this; + + this.panel = Ext.createWidget({ + xtype : 'container', + layout : 'vbox', + border : 0, + style : { + padding : '10px' + }, + fieldDefaults : { + labelAlign : 'left', + labelWidth : 50 + }, + items : this._getItems(experiment) + }); + return this.panel; +}; + +ExperimentForm.prototype.input = function() { + return new ExperimentHeaderForm().input(); +}; + +ExperimentForm.prototype.test = function(targetId) { + var experimentForm = new ExperimentForm(); + var panel = experimentForm.getPanel(new Experiment(experimentForm.input().experiment)); + panel.render(targetId); +}; -GraphCanvas.prototype.getBackgroundColor = function() { - return this.getFormatter().getBackgroundColor(); -}; +/** + * Shows the header for the experiments changing the color and parameters depending on experiment type + * + */ +function ExperimentHeaderForm(args) { + this.id = BUI.id(); + this.backgroundColor = '#FFFFFF'; +} + +ExperimentHeaderForm.prototype.getHTMLSource = function(experiment) { + var html = BUI.createFormLabel("Name :", experiment.json.name, 75, 400, this.backgroundColor); + if (experiment.json.type == "HPLC") { + if (experiment.getHPLCMacromolecule() != null){ + html = html + BUI.createFormLabel("Molecule :", experiment.getHPLCMacromolecule().acronym, 75, 400, this.backgroundColor); + } + } + else{ + html = html + BUI.createFormLabel("Type :", experiment.json.type, 75, 400, this.backgroundColor); + } + + html = html + BUI.createFormLabel("Date :", experiment.json.creationDate, 75, 400, this.backgroundColor); + return html; +}; + +ExperimentHeaderForm.prototype.getHTMLDownload = function(experiment) { + var bgcolor = "background-color:" + this.backgroundColor + ";"; + var html = "
"; + if ((experiment.json.type == "CALIBATION") || (experiment.json.type == "STATIC")) { + html = html + " Download Source File
"; + html = html + + ""; + } + if (experiment.json.type == "TEMPLATE") { + html = html + + " Download Source File"; + } + + if (experiment.json.type == "HPLC") { + html = html + " Download h5 File"; + } + + return html; +}; + +ExperimentHeaderForm.prototype.getTopPanel = function(experiment) { + return { + xtype : 'container', + layout : 'hbox', + items : [ { + margin : "0 0 0 0", + width : 475, + border : 0, + html : this.getHTMLSource(experiment) + }, { + margin : "0 0 0 0", + width : 475, + border : 0, + html : this.getHTMLDownload(experiment) + } ] + }; +}; + +ExperimentHeaderForm.prototype.getButton = function(experiment) { + var _this = this; + return Ext.create('Ext.Button', { + text : 'EDIT', + minWidth : '100', + margin : '10 0 0 30', + handler : function() { + var experimentWindow = new ExperimentWindow(); + experimentWindow.onSaved.attach(function(sender, data) { + _this.experiment.json.name = data.name; + _this.experiment.json.type = data.type; + _this.experiment.json.comments = data.comments; + _this.panel.remove(_this.panel.items.items[0]); + _this.panel.remove(_this.panel.items.items[0]); + _this.panel.insert(_this.getTopPanel(_this.experiment)); + _this.panel.insert(_this.getBottomPanel(_this.experiment)); + }); + experimentWindow.show(experiment); + } + }); +}; + +ExperimentHeaderForm.prototype.getBottomPanel = function(experiment) { + return { + xtype : 'container', + layout : 'hbox', + margin : '10 0 0 0', + items : [ this.getComments(experiment), this.getButton(experiment) ] + }; +}; + +ExperimentHeaderForm.prototype.getComments = function(experiment) { + return { + xtype : 'textareafield', + labelStyle : 'font-weight: bold;', + name : 'comments', + fieldLabel : 'Comments', + labelWidth : 70, + height : 40, + minWidth : '450', + readOnly : true, + value : experiment.json.comments + }; +}; + +ExperimentHeaderForm.prototype.getPanel = function(experiment) { + this.experiment = experiment; + + if (experiment.json.type == 'CALIBRATION') { + this.backgroundColor = '#EFFBFB'; + } + if (experiment.json.type == 'TEMPLATE') { + this.backgroundColor = '#E0F8E6'; + } + + this.panel = Ext.create('Ext.container.Container', { + frame : false, + layout : 'vbox', + padding : 5, + bodyPadding : '5 5 0 0', + width : 890, + margin : '0 0 10 0', + height : 120, + style : { + borderColor : '#99bce8', + borderStyle : 'solid', + borderWidth : '1px', + 'background-color' : this.backgroundColor + }, + fieldDefaults : { + msgTarget : 'side', + labelWidth : 100 + }, + items : [ this.getTopPanel(experiment), this.getBottomPanel(experiment) ] + }); + return this.panel; +}; + +ExperimentHeaderForm.prototype.input = function() { + return { + experiment : DATADOC.getExperiment_10() + }; +}; + +ExperimentHeaderForm.prototype.test = function(targetId) { + var experimentHeaderForm = new ExperimentHeaderForm(); + var panel = experimentHeaderForm.getPanel(new Experiment(experimentHeaderForm.input().experiment)); + panel.render(targetId); + +}; -GraphCanvas.prototype.setBackgroundColor = function() { - this.getFormatter().setBackgroundColor(value); -}; +/** + * Macromolecule form with the general parameters of a macromolecule + * + * @witdh + * @height + * + * #onSave button save has been clicked + * #onClose button close has been clicked + */ +function MacromoleculeForm(args) { + this.id = BUI.id(); + this.width = 700; + this.height = 500; + + if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } + } + + /** Events **/ + this.onSave = new Event(this); + this.onClose = new Event(this); +} + +/** Type : is the Ext type then requiredtext or textfield * */ +MacromoleculeForm.prototype._getFieldTextWithHelp = function(type, fieldLabel, fieldName, help) { + return Ext.create('Ext.container.Container', { + margin : "10 0 0 10", + items : [ { + xtype : type, + fieldLabel : fieldLabel, + name : fieldName, + id : this.id + fieldName + }, { + xtype : 'label', + forId : 'myFieldId', + text : help, + margin : "5 0 0 105", + cls : "inline-help" + } ] + }); +}; + +MacromoleculeForm.prototype._getNumericWithHelp = function(type, fieldLabel, fieldName, help) { + return Ext.create('Ext.container.Container', { + margin : "0 0 0 10", + items : [ { + xtype : type, + fieldLabel : fieldLabel, + name : fieldName, + id : this.id + fieldName, + decimalPrecision : 6, + width : 220 + }, { + xtype : 'label', + forId : 'myFieldId', + text : help, + margin : "5 0 0 10", + cls : "inline-help" + } ] + }); +}; + +MacromoleculeForm.prototype._getButtons = function() { + var _this = this; + return [ { + text : 'Save', + handler : function() { + _this._save(); + } + },{ + text : 'Close', + handler : function() { + _this.onClose.notify(); + + } + } ]; +}; + +/** It persits the macromolecule in the database **/ +MacromoleculeForm.prototype._persist = function(macromoleculeId, acronym, name, molecularMass, extintionCoefficient, comments, refractiveIndex, solventViscosity) { + + /** Checking not duplicated acronym **/ + if (((macromoleculeId == null) && (BIOSAXS.proposal.getMacromoleculeByAcronym(acronym) != null))== true){ + BUI.showError("Duplicated acronym"); + return; + } + + + if (macromoleculeId == null){ + /** new macromolecule **/ + this.macromolecule = {}; + this.macromolecule.macromoleculeId = null; + } + else{ + this.macromolecule.macromoleculeId = macromoleculeId; + } + + this.macromolecule["acronym"] = acronym; + this.macromolecule["name"] = name; + this.macromolecule["molecularMass"] = molecularMass; + this.macromolecule["extintionCoefficient"] = extintionCoefficient; + this.macromolecule["comments"] = comments; + this.macromolecule["symmetry"] = Ext.getCmp(this.id + 'comboSym').getValue(); + this.macromolecule["refractiveIndex"] = refractiveIndex; + this.macromolecule["solventViscosity"] = solventViscosity; + + var _this = this; + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, proposal) { + /** Updating the proposal global object **/ + BIOSAXS.proposal.setItems(proposal); + _this.panel.setLoading(false); + + var saved = BIOSAXS.proposal.getMacromoleculeByAcronym(acronym); + /** Refreshing to check that everything is ok **/ + _this.refresh(saved); + _this.onSave.notify(saved); + }); + + this.panel.setLoading("Saving Macromolecule") + adapter.saveMacromolecule(this.macromolecule); +}; + +/** Save the macromolecule in the DB **/ +MacromoleculeForm.prototype._save = function() { + + var _this = this; + + var acronym = this._getField("acronym"); + var name = this._getField("name"); + var molecularMass = this._getField("molecularMass"); + var extintionCoefficient = this._getField("extintionCoefficient"); + var comments = this._getField("comments"); + + var refractiveIndex = this._getField("refractiveIndex"); + var solventViscosity = this._getField("solventViscosity"); + + /** Checking required fields **/ + if (name == "") { + BUI.showError("Name field is mandatory"); + return; + } + if (acronym == "") { + BUI.showError("Acroynm field is mandatory"); + return; + } + + if (this.macromolecule != null){ + /** Checking if it is a new macromolecule **/ + if (this.macromolecule.macromoleculeId == null){ + /** Check if the acronym exists already **/ + this._persist(null, acronym, name, molecularMass, extintionCoefficient, comments, refractiveIndex, solventViscosity); + } + else{ + /** It is an update **/ + this._persist(this.macromolecule.macromoleculeId, acronym, name, molecularMass, extintionCoefficient, comments, refractiveIndex, solventViscosity); + } + } + else{ + /** It is a new macromolecule **/ + this._persist(null, acronym, name, molecularMass, extintionCoefficient, comments, refractiveIndex, solventViscosity); + } +}; + + + +MacromoleculeForm.prototype._getItems = function() { + var _this = this; + /** Symmetry combo box **/ + var symmetry = Ext.create('Ext.data.Store', { + fields : [ 's' ], + data : this._getSymmetries() + }); + + this.symmetryComboBox = Ext.create('Ext.form.ComboBox', { + fieldLabel : 'Symmetry', + store : symmetry, + id : this.id + 'comboSym', + queryMode : 'local', + displayField : 's', + valueField : 's', + value : "P1", + margin : "0 0 0 30", + width : 220 + }); + + return [this._getFieldTextWithHelp("requiredtext", "Name", "name", "Long name. i.e: Bovine serum albumin"), + this._getFieldTextWithHelp("requiredtext", "Acronym", "acronym", "Acronym will be used in the files and analisys. i.e: BSA"), + this._getFieldTextWithHelp("textfield", "Mol. Mass (Da)", "molecularMass", "Atomic mass estimation measured in Da"), + { + xtype : 'container', + layout : 'hbox', + margin : "10 0 0 0", + items :[ + this._getNumericWithHelp("numberfield", "Extinction coef.", "extintionCoefficient", ""), + this.symmetryComboBox + ] + }, + { + xtype : 'container', + layout : 'hbox', + margin : "5 0 0 0", + items :[ + this._getNumericWithHelp("numberfield", "Refractive Index", "refractiveIndex", "How radiation propagates through the medium"), + this._getNumericWithHelp("numberfield", "Solvent Viscosity", "solventViscosity", "") + ] + }, + { + id : this.id + "comments", + xtype : 'textareafield', + name : 'comments', + margin : '35 0 0 10', + fieldLabel : 'Comments', + width : this.width - 100 + } ]; +}; + +MacromoleculeForm.prototype._getSymmetries = function() { + return [ { + "s" : "P1" + }, { + "s" : "P2" + }, { + "s" : "P3" + }, { + "s" : "P4" + }, { + "s" : "P5" + }, { + "s" : "P6" + }, { + "s" : "P32" + }, { + "s" : "P42" + }, { + "s" : "P52" + }, { + "s" : "P62" + }, { + "s" : "P222" + } ] +}; + +MacromoleculeForm.prototype.getPanel = function() { + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + margin : 10, + border : 1, + defaultType : 'textfield', + items : this._getItems(), + buttons : this._getButtons() + }); + return this.panel; +}; + + +/** Populates each text field by field name and value **/ +MacromoleculeForm.prototype._populateField = function(fieldName, value) { + if (value != null){ + Ext.getCmp(this.id + fieldName).setValue(value); + } +}; + +/** Gets the value of a textfield **/ +MacromoleculeForm.prototype._getField = function(fieldName) { + return Ext.getCmp(this.id + fieldName).getValue(); +}; + + +/** It populates the form **/ +MacromoleculeForm.prototype.refresh = function(macromolecule) { + this.macromolecule = macromolecule; + if (macromolecule != null){ + this._populateField("name", macromolecule.name); + this._populateField("acronym", macromolecule.acronym); + this._populateField("extintionCoefficient", macromolecule.extintionCoefficient); + this._populateField("molecularMass", macromolecule.molecularMass); + this._populateField("comments", macromolecule.comments); + this._populateField("refractiveIndex", macromolecule.refractiveIndex); + this._populateField("solventViscosity", macromolecule.solventViscosity); + if (macromolecule.symmetry != null){ + Ext.getCmp(this.id + 'comboSym').setValue(macromolecule.symmetry); + } + } +}; + + +MacromoleculeForm.prototype.input = function() { + return {}; +}; + + +/** It populates the form **/ +MacromoleculeForm.prototype.test = function(targetId) { + var macromoleculeForm = new MacromoleculeForm(); + macromoleculeForm.onClose.attach(function(sender){ + alert("Click on close"); + }); + var panel = macromoleculeForm.getPanel(); + panel.render(targetId); +}; + + -//GraphCanvas.prototype.setEdgeFill = function(edgeId, value){ -// this.getFormatter().getEdgeById(edgeId).getDefault().setFill(value); -//}; -// -//GraphCanvas.prototype.getEdgeFill = function(edgeId){ -// return this.getFormatter().getEdgeById(edgeId).getDefault().getFill(); -//}; + + +function ModelVisualizerForm(args){ + this.id =BUI.id(); + this.width = 600; + this.height = 400; + if (args!= null){ + if (args.width != null){ + this.width = args.width; + } + if (args.height != null){ + this.height = args.height; + } + } +}; + +ModelVisualizerForm.prototype._getFirHTML = function(modelId, width, height, type, desc) { + var html = ""; + html = html + ''; + html = html + ''; + html = html + ''; + html = html + '
dammin.' + type + '
' + desc + '
'; + return html; +}; + +ModelVisualizerForm.prototype.getItems = function(modelPanel){ + _this = this; + var height = _this.height/2 - 60; + var width = _this.width/2 - 10; + + return Ext.create('Ext.container.Container', { + layout: { + type: 'vbox', // Arrange child items vertically + }, + items: [ + modelPanel, + { + xtype : 'container', + layout: { + type: 'hbox', // Arrange child items vertically + }, + items : [{ + html : this._getFirHTML("id", width, height, "fir", "Fit of the simulated scattering curve versus a smoothed experimental data (spline interpolation)"), + height :height, + width : width, + padding: 2 + }, + { + html : this._getFirHTML("id", width, height, "fit", "Fit of the simulated scattering curve versus the experimental data."), + height : height, + width : width, + padding: 2 + }] + } + + ] + }); +}; + +ModelVisualizerForm.prototype.refresh = function(models){ + var input = []; +// var colors = ["008000", "F0A804", "0000FF", "800080", "C0C0C0"]; + for (var i = 0; i < models.length; i++) { + console.log(BUI.rainbow(models.length, i).replace("#", "0x")); + input.push({ + color: BUI.rainbow(models.length, i).replace("#", "0x"), + modelId: models[i].modelId, + opacity: 0.8, + radius: 3, + title: BUI.getFileNameByPath(models[i].pdbFile), + type: "SHAPEDETERMINATIONMODEL" + + }); + } + + this.panel.removeAll(); + this.panel.add( + _this.getItems( + new PDBViewer({ + width : this.width - 10, + height : (this.height/2) - 10, + title : "" + }).draw(input) + ) + ); + + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, data) { + var splitted = data.toString().split("\n"); + var array = []; + for ( var i = 0; i < splitted.length; i++) { + var line = splitted[i].trim(); + var line_splited = line.split(/\s*[\s,]\s*/); + if (line_splited.length == 4) { + array.push([ Number(line_splited[0]), BUI.getStvArray(line_splited[1], line_splited[2]), BUI.getStvArray(line_splited[3], 0) ]); + } + } + + var id = (_this.id + "firid"); + var dygraphWidget = new StdDevDyGraph(id, { + width : (_this.width/2) - 10, + height :(_this.height/2) -110, + xlabel : 'q(nm-1)' + }); + dygraphWidget.draw(array, [ "#FF0000", "#0000FF", "#FF00FF" ], [ 's', 'I(exp)', 'I(sim)' ]); + }); + + adapter.getModelFile("FIR", models[0].modelId); + + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, data) { + var splitted = data.toString().split("\n"); + var array = []; + for ( var i = 0; i < splitted.length; i++) { + var line = splitted[i].trim(); + var line_splited = line.split(/\s*[\s,]\s*/); + if (line_splited.length == 3) { + array.push([ Number(line_splited[0]), BUI.getStvArray(line_splited[1], 0), BUI.getStvArray(line_splited[2], 0) ]); + } + } + + var id = (_this.id + "fitid"); + + var dygraphWidget = new StdDevDyGraph(id, { + width : (_this.width/2) - 10, + height : (_this.height/2) - 110, + xlabel : 'q(nm-1)' + }); + dygraphWidget.draw(array, [ "#FF0000", "#0000FF" ], [ "s", "I(exp)", "I(sim)" ]); + }); + adapter.getModelFile("FIT", models[0].modelId); +}; + +ModelVisualizerForm.prototype.getPanel = function(modelList){ + _this = this; + this.modelList = modelList; + this.panel = Ext.create('Ext.Panel', { + title: 'Results', + width: this.width, + height: this.height, + layout: { + type: 'vbox', // Arrange child items vertically +// align: 'stretch' // Each takes up full width + }, + items: [ + + ], + listeners : { + afterrender : function(grid, eOpts) { +// alert(_this.modelList) + } + } + }); + + return this.panel; + +}; + -/** VERTICES FORMATTER **/ -GraphCanvas.prototype.setVertexSize = function(vertexId, value) { - this.getFormatter().getVertexById(vertexId).getDefault().setSize(value); -}; +/** + * Example form + * + * @witdh + * @height + */ +function MolarityForm(args) { + this.id = BUI.id(); + this.width = 700; + this.height = 500; + + if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } + } + + this.onSave = new Event(this); + this.onClose = new Event(this); +} + + +MolarityForm.prototype._getNumericWithHelp = function(type, fieldLabel, fieldName, help) { + return Ext.create('Ext.container.Container', { + margin : "10 0 0 10", + items : [ { + xtype : type, + fieldLabel : fieldLabel, + name : fieldName, + id : this.id + fieldName, + decimalPrecision : 6 + }, { + xtype : 'label', + forId : 'myFieldId', + text : help, + margin : "5 0 0 105", + cls : "inline-help" + } ] + }); +}; + + +MolarityForm.prototype._getItems = function() { + this.macromoleculeCombo = BIOSAXS_COMBOMANAGER.getComboMacromoleculeByMacromolecules(this.getMacromuleculesCandidates(this.macromolecule), { + width : 250, + labelWidth : 100, + margin : 10 + }); + + return [ { + xtype : 'container', + flex : 1, + margin : '10 0 0 10', + border : 0, + layout : 'anchor', + defaultType : 'requiredtext', + items : [ this.macromoleculeCombo, + this._getNumericWithHelp("textfield", "Ratio", "ratio", "Number in assymmetric units") + ] + } ]; +}; + +MolarityForm.prototype._persist = function() { + var _this = this; + var macromoleculeId = this.macromoleculeCombo.getValue(); + var ratio = Ext.getCmp(this.id + "ratio").getValue(); + var comments = "Not used yet"; + var dataAdapter = new BiosaxsDataAdapter(); + this.panel.setLoading("Saving"); + dataAdapter.onSuccess.attach(function(sender, args) { + _this.onSave.notify(); + }); + dataAdapter.saveStoichiometry(this.macromolecule.macromoleculeId, macromoleculeId, ratio, comments); +}; + +MolarityForm.prototype._getButtons = function() { + var _this = this; + + function onClose() { + _this.onClose.notify(); + } + + return [ { + text : 'Save', + handler : function() { + _this._persist(); + } + }, { + text : 'Cancel', + handler : function() { + onClose(); + } + } ]; +}; + +MolarityForm.prototype.getPanel = function() { + this.panel = Ext.create('Ext.form.Panel', { +// width : null, + height : this.height, + margin : 2, + border : 1, + defaultType : 'requiredtext', + items : this._getItems(), + buttons : this._getButtons() + }); + return this.panel; +}; + +/** macromolecules contains all macromolecules except this one **/ +MolarityForm.prototype.getMacromuleculesCandidates = function(macromolecule) { + var macromolecules = []; + if ( BIOSAXS.proposal.macromolecules){ + for (var i = 0; i < BIOSAXS.proposal.macromolecules.length; i++) { + var m = BIOSAXS.proposal.macromolecules[i]; + if (this.macromolecule != null){ + if (m.macromoleculeId != this.macromolecule.macromoleculeId) { + macromolecules.push(m); + } + } + } + } + return macromolecules; +}; + + +/** It populates the form **/ +MolarityForm.prototype.refresh = function(macromolecule) { + this.macromolecule = macromolecule; + +}; + + +MolarityForm.prototype.input = function() { + return {}; +}; + + +/** It populates the form **/ +MolarityForm.prototype.test = function(targetId) { + var macromoleculeForm = new MolarityForm(); + var panel = macromoleculeForm.getPanel(); + panel.render(targetId); +}; -GraphCanvas.prototype.getVertexSize = function(vertexId) { - return this.getFormatter().getVertexById(vertexId).getDefault().getSize(); -}; +///** +// * +// * @witdh +// * @height +// */ +//function MacromoleculeForm(args) { +// this.id = BUI.id(); +// this.width = 700; +// this.height = 500; +// +// if (args != null) { +// if (args.width != null) { +// this.width = args.width; +// } +// if (args.height != null) { +// this.height = args.height; +// } +// } +// +// this.onClose = new Event(this); +//} +// +//MacromoleculeForm.prototype.getMacromolecule = function() { +// this.macromolecule.name = Ext.getCmp(this.panel.getItemId()).getValues().name; +// this.macromolecule.acronym = Ext.getCmp(this.panel.getItemId()).getValues().acronym; +// this.macromolecule.comments = Ext.getCmp(this.panel.getItemId()).getValues().comments; +// this.macromolecule.extintionCoefficient = Ext.getCmp(this.panel.getItemId()).getValues().extintionCoefficient; +// this.macromolecule.molecularMass = Ext.getCmp(this.panel.getItemId()).getValues().molecularMass; +// return this.macromolecule; +//}; +// +//MacromoleculeForm.prototype.setMacromolecule = function(macromolecule) { +// this.pdbStore.loadData(macromolecule.structure3VOs); +// +//}; +// +//MacromoleculeForm.prototype.getForm = function(macromolecule) { +// this.panel = Ext.createWidget('form', { +// frame : false, +// border : 0, +// padding : 15, +// width : 550, +// height : 350, +// items : [ { +// xtype : 'container', +// layout : 'hbox', +// items : [ { +// xtype : 'container', +// flex : 1, +// border : false, +// layout : 'anchor', +// defaultType : 'requiredtext', +// items : [ { +// fieldLabel : 'Name', +// name : 'name', +// anchor : '95%', +// tooltip : "Name of the macromolecule", +// value : macromolecule.name +// }, { +// fieldLabel : 'Acronym', +// name : 'acronym', +// anchor : '95%', +// value : macromolecule.acronym +// } ] +// }, { +// xtype : 'container', +// flex : 1, +// layout : 'anchor', +// defaultType : 'textfield', +// items : [ { +// xtype : 'numberfield', +// fieldLabel : 'Mol. Mass (Da)', +// name : 'molecularMass', +// value : macromolecule.molecularMass, +// decimalPrecision : 6 +// }, { +// xtype : 'numberfield', +// fieldLabel : 'Extinction coef.', +// name : 'extintionCoefficient', +// value : macromolecule.extintionCoefficient, +// decimalPrecision : 6 +// } ] +// } ] +// }, { +// xtype : 'textareafield', +// name : 'comments', +// fieldLabel : 'Comments', +// value : macromolecule.comments, +// width : this.width - 10 +// }, +// +// { +// html : BUI.getWarningHTML("The macromolecule is unsaved. Save the macromolecule to get access to other tabs"), +// margin : "150 10 10 10", +// id : this.id + "unsavedWarning", +// hidden : !(!macromolecule.macromoleculeId) +// } +// +// ] +// }); +// return this.panel; +//}; +// +//MacromoleculeForm.prototype.save = function() { +// var _this = this; +// +// var adapter = new BiosaxsDataAdapter(); +// adapter.onSuccess.attach(function(sender, proposal) { +// BIOSAXS.proposal.setItems(proposal); +// _this.panel.setLoading(false); +// +// Ext.getCmp(_this.id + "assembly").enable() +// Ext.getCmp(_this.id + "advanced").enable(); +// Ext.getCmp(_this.id + "unsavedWarning").hide(); +// }); +// +// if (this.getMacromolecule().name == "") { +// BUI.showError("Name field is mandatory"); +// return; +// } +// if (this.getMacromolecule().acronym == "") { +// BUI.showError("Acroynm field is mandatory"); +// return; +// } +// +// /** Check if acronym is unique * */ +// if (this.getMacromolecule().macromoleculeId == null) { +// if (BIOSAXS.proposal.getMacromoleculeByAcronym(this.getMacromolecule().acronym) == null) { +// this.panel.setLoading("ISPyB: Saving Macromolecule") +// adapter.saveMacromolecule(this.getMacromolecule()); +// } else { +// alert("There is already an existing macromolecule with the same acronym"); +// +// } +// } else { +// this.panel.setLoading("ISPyB: Saving Macromolecule") +// adapter.saveMacromolecule(this.getMacromolecule()); +// } +// +//}; +// +//MacromoleculeForm.prototype.getPanel = function(macromolecule) { +// var _this = this; +// this.macromolecule = macromolecule; +// return Ext.createWidget('tabpanel', { +// height : this.height, +// margin : 5, +// plain : true, +// style : { +// padding : 5 +// }, +// items : [ { +// tabConfig : { +// title : "General", +// disabled : false +// }, +// items : [ this.getForm(macromolecule) ], +// bbar : [ "->", { +// text : 'Save', +// cls : 'btn-with-border', +// style : { +// +// border : 1 +// }, +// handler : function() { +// _this.save(); +// } +// }, { +// text : 'Close', +// cls : 'btn-with-border', +// handler : function() { +// _this.onClose.notify(); +// } +// } ] +// }, { +// tabConfig : { +// id : this.id + "assembly", +// title : "Assembly", +// tooltip : 'Description of subunits present in the macromolecule', +// // hidden : (!macromolecule.macromoleculeId), +// disabled : (!macromolecule.macromoleculeId) +// }, +// items : [ this.getMolarityGrid(macromolecule) ] +// }, { +// tabConfig : { +// id : this.id + "advanced", +// title : "Advanced Modeling", +// // hidden : (!macromolecule.macromoleculeId), +// tooltip : 'Definition of the description contacts and symetries', +// disabled : (!macromolecule.macromoleculeId) +// }, +// items : [ this.getRigidBodyForm(macromolecule) ] +// } ] +// }); +//}; +// +//MacromoleculeForm.prototype.getRigidBodyForm = function(macromolecule) { +// var _this = this; +// +// // [P1, P2, P3, P4 ,P5 ,P6 ,32, P42, P52, P62] + P222 +// var symmetry = Ext.create('Ext.data.Store', { +// fields : [ 's' ], +// data : [ { +// "s" : "P1" +// }, { +// "s" : "P2" +// }, { +// "s" : "P3" +// }, { +// "s" : "P4" +// }, { +// "s" : "P5" +// }, { +// "s" : "P6" +// }, { +// "s" : "P32" +// }, { +// "s" : "P42" +// }, { +// "s" : "P52" +// }, { +// "s" : "P62" +// }, { +// "s" : "P222" +// } ] +// }); +// +// if (macromolecule.symmetry == null) { +// macromolecule.symmetry = "P1"; +// } +// var comboBox = Ext.create('Ext.form.ComboBox', { +// fieldLabel : 'Symmetry', +// store : symmetry, +// id : 'comboSym', +// queryMode : 'local', +// displayField : 's', +// valueField : 's', +// value : macromolecule.symmetry, +// margin : "10 0 0 0", +// listeners : { +// change : function(combo, newValue, oldValue, eOpts) { +// macromolecule.symmetry = newValue; +// } +// } +// }); +// +// this.rigidBodyPanel = Ext.createWidget('form', { +// frame : false, +// border : 0, +// padding : 10, +// width : 550, +// height : 400, +// items : [ { +// xtype : 'container', +// layout : 'hbox', +// items : [ { +// xtype : 'container', +// border : false, +// layout : 'hbox', +// items : [ { +// xtype : 'label', +// forId : 'myFieldId', +// text : 'Contact Desc:', +// width : 105, +// margin : '0 0 0 0' +// }, { +// xtype : 'textfield', +// hideLabel : true, +// id : "contactsDescriptionFilePath", +// margin : '0 0 0 0', +// width : 300, +// value : macromolecule.contactsDescriptionFilePath +// }, { +// text : 'Upload', +// xtype : 'button', +// margin : "0 0 0 20", +// width : 100, +// handler : function() { +// _this._openUploadDialog(macromolecule.macromoleculeId, "CONTACTS", "Upload Contact Description File"); +// } +// } ] +// } ] +// }, +// +// comboBox, { +// xtype : 'checkbox', +// margin : '10 0 0 5', +// boxLabel : "I want rigid body modeling run on this stuff", +// checked : true, +// width : 300 +// }, _this.getPDBGrid(macromolecule) ] +// }); +// return this.rigidBodyPanel; +//}; +// +//MacromoleculeForm.prototype.update = function() { +// var _this = this; +// BIOSAXS.proposal.onInitialized.attach(function() { +// if (BIOSAXS.proposal != null) { +// var macromolecules = BIOSAXS.proposal.macromolecules; +// for (var i = 0; i < macromolecules.length; i++) { +// if (macromolecules[i].macromoleculeId == _this.macromolecule.macromoleculeId) { +// _this.macromolecule = macromolecules[i]; +// _this.setMacromolecule(_this.macromolecule); +// _this.molarityStore.loadData(_this.parseMolarityData(_this.macromolecule)); +// _this.pdbGrid.setLoading(false); +// Ext.getCmp("contactsDescriptionFilePath").setValue(_this.macromolecule.contactsDescriptionFilePath) +// _this.molarityGrid.setLoading(false); +// +// } +// } +// } +// }); +// this.molarityGrid.setLoading("Updating"); +// this.pdbGrid.setLoading("Updating"); +// BIOSAXS.proposal.init(); +//}; +// +///******************************************************************************* +// * MOLARITY GRID +// ******************************************************************************/ +// +//MacromoleculeForm.prototype.parseMolarityData = function(macromolecule) { +// var data = []; +// if (macromolecule.stoichiometry != null) { +// for (var i = 0; i < macromolecule.stoichiometry.length; i++) { +// data.push({ +// ratio : macromolecule.stoichiometry[i].ratio, +// acronym : macromolecule.stoichiometry[i].macromolecule3VO.acronym, +// comments : macromolecule.stoichiometry[i].macromolecule3VO.comments, +// stoichiometryId : macromolecule.stoichiometry[i].stoichiometryId, +// name : macromolecule.stoichiometry[i].macromolecule3VO.name +// }); +// } +// } +// return data; +//}; +// +//MacromoleculeForm.prototype.getMolarityGrid = function(macromolecule) { +// var _this = this; +// +// this.molarityStore = Ext.create('Ext.data.Store', { +// fields : [ 'acronym', 'ratio', 'comments', 'stoichiometryId', 'name' ], +// data : this.parseMolarityData(macromolecule), +// sorters : { +// property : 'ratio', +// direction : 'DESC' +// } +// }); +// +// this.molarityGrid = Ext.create('Ext.grid.Panel', { +// store : this.molarityStore, +// height : 350, +// padding : 5, +// columns : [ +// +// { +// text : 'Subunit', +// columns : [ { +// text : "Acronym", +// width : 100, +// hidden : false, +// dataIndex : 'acronym', +// sortable : true +// }, { +// text : "Name", +// width : 100, +// hidden : false, +// dataIndex : 'name', +// sortable : true +// }, { +// text : "Comments", +// width : 100, +// dataIndex : 'comments', +// sortable : true +// } ] +// }, { +// text : "Number
in assymmetric units", +// width : 150, +// dataIndex : 'ratio', +// tooltip : 'Number of times this subunit is present in the macromolecule', +// sortable : true +// }, { +// id : this.id + 'MOLARITY_REMOVE', +// flex : 0.1, +// sortable : false, +// renderer : function(value, metaData, record, rowIndex, colIndex, store) { +// return BUI.getRedButton('REMOVE'); +// } +// } ], +// listeners : { +// cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { +// if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'MOLARITY_REMOVE') { +// var dataAdapter = new BiosaxsDataAdapter(); +// dataAdapter.onSuccess.attach(function() { +// _this.molarityGrid.setLoading(false); +// _this.update(); +// }); +// dataAdapter.removeStoichiometry(record.data.stoichiometryId); +// _this.molarityGrid.setLoading("Removing Structure"); +// } +// } +// }, +// buttons : [ { +// text : 'Add molarity', +// handler : function() { +// +// function onClose() { +// w.destroy(); +// _this.update(); +// } +// var w = Ext.create('Ext.window.Window', { +// title : 'Molarity', +// height : 300, +// width : 500, +// modal : true, +// buttons : [ { +// text : 'Save', +// handler : function() { +// var macromoleculeId = (_this.macromoleculeCombo.getValue()); +// var ratio = Ext.getCmp(_this.id + "ratio").getValue(); +// var comments = ""; +// var dataAdapter = new BiosaxsDataAdapter(); +// dataAdapter.onSuccess.attach(function(sender, args) { +// _this.update(); +// w.destroy(); +// }); +// dataAdapter.saveStoichiometry(_this.macromolecule.macromoleculeId, macromoleculeId, ratio, comments); +// } +// }, { +// text : 'Cancel', +// handler : function() { +// onClose(); +// } +// } ], +// items : [ _this.getMolarityForm(macromolecule) ], +// listeners : { +// onEsc : function() { +// onClose(); +// }, +// close : function() { +// onClose(); +// } +// } +// }).show(); +// } +// } ] +// }); +// return this.molarityGrid; +//}; +// +///******************************************************************************* +// * PDB GRID +// ******************************************************************************/ +// +//MacromoleculeForm.prototype._openUploadDialog = function(macromoleculeId, type, title) { +// var _this = this; +// function onClose() { +// w.destroy(); +// _this.update(); +// } +// +// var w = Ext.create('Ext.window.Window', { +// title : title, +// height : 200, +// width : 400, +// modal : true, +// buttons : [ { +// text : 'Close', +// handler : function() { +// onClose(); +// } +// } ], +// layout : 'fit', +// items : { +// html : "" +// }, +// listeners : { +// onEsc : function() { +// onClose(); +// }, +// close : function() { +// onClose(); +// } +// } +// }).show(); +//}; +// +//MacromoleculeForm.prototype._getPlugins = function() { +// var _this = this; +// var plugins = []; +// // if (this.updateRowEnabled) { +// plugins.push(Ext.create('Ext.grid.plugin.RowEditing', { +// clicksToEdit : 1, +// listeners : { +// validateedit : function(grid, e) { +// /** Comments are always updatable* */ +// e.record.raw.symmetry = e.newValues.symmetry; +// e.record.raw.multiplicity = e.newValues.multiplicity; +// +// var adapter = new BiosaxsDataAdapter(); +// adapter.onSuccess.attach(function(sender, measurement) { +// // _this.grid.setLoading(false); +// }); +// adapter.onError.attach(function() { +// alert("Error"); +// // _this.grid.setLoading(false); +// }); +// +// // _this.grid.setLoading(); +// adapter.saveStructure(e.record.raw); +// } +// } +// })); +// // } +// return plugins; +//}; +// +//MacromoleculeForm.prototype.getPDBGrid = function(macromolecule) { +// var _this = this; +// +// var data = macromolecule.structure3VOs; +// +// // /** Getting PDB from subunits **/ +// // if (macromolecule != null){ +// // if (macromolecule.stoichiometry != null){ +// // for (var i =0; i < macromolecule.stoichiometry.length; i++){ +// // var stoichiometry = macromolecule.stoichiometry[i]; +// // if (stoichiometry.macromolecule3VO != null){ +// // if (stoichiometry.macromolecule3VO.structure3VOs != null){ +// // for (var j = 0; j < stoichiometry.macromolecule3VO.structure3VOs.length; +// // j++) { +// // var structure = stoichiometry.macromolecule3VO.structure3VOs[j]; +// // structure["isSubunit"] = stoichiometry.macromolecule3VO.acronym; +// // data.push(structure) +// // } +// // } +// // } +// // } +// // } +// // } +// +// this.pdbStore = Ext.create('Ext.data.Store', { +// fields : [ 'filePath', 'structureId', 'structureType', 'symmetry', 'structureId', 'name', 'multiplicity' ], +// data : macromolecule.structure3VOs, +// groupField : 'structureType', +// sorters : { +// property : 'structureId', +// direction : 'DESC' +// } +// }); +// +// var groupingFeature = Ext.create('Ext.grid.feature.Grouping', { +// groupHeaderTpl : Ext.create('Ext.XTemplate', +// "
{name:this.formatName}
", { +// formatName : function(name) { +// return name; +// } +// }), +// hideGroupedHeader : true, +// startCollapsed : false +// }); +// +// this.pdbGrid = Ext.create('Ext.grid.Panel', { +// margin : "15 0 0 5", +// height : 250, +// store : this.pdbStore, +// plugins : _this._getPlugins(), +// buttons : [ { +// // text : 'Add PDB file', +// text : 'Add Modeling Option', +// handler : function() { +// _this._openUploadDialog(macromolecule.macromoleculeId, "PDB", 'Upload PDB File'); +// } +// } +// +// ], +// columns : [ +// { +// text : "structureId", +// flex : 0.2, +// hidden : true, +// dataIndex : 'structureId', +// sortable : true +// }, +// { +// text : "File", +// flex : 0.5, +// dataIndex : 'filePath', +// sortable : true, +// hidden : true +// }, +// { +// text : "PDB", +// flex : 0.4, +// dataIndex : 'name', +// sortable : true +// }, +// { +// text : "Symmetry", +// flex : 0.4, +// dataIndex : 'symmetry', +// sortable : true, +// editor : { +// xtype : 'combobox', +// typeAhead : true, +// triggerAction : 'all', +// selectOnTab : true, +// store : [ [ "P1", "P1" ], [ "P2", "P2" ], [ "P3", "P3" ], [ "P4", "P4" ], [ "P5", "P5" ], [ "P6", "P6" ], [ "P32", "P32" ], [ "P42", "P42" ], +// [ "P52", "P52" ], [ "P62", "P62" ], [ "P222", "P222" ] ], +// } +// }, { +// text : "Multiplicity", +// flex : 0.4, +// dataIndex : 'multiplicity', +// sortable : true, +// editor : { +// xtype : 'textfield' +// } +// +// }, { +// text : "Subunit", +// flex : 0.2, +// dataIndex : 'isSubunit', +// sortable : true, +// hidden : true +// }, { +// text : "Type", +// flex : 0.2, +// dataIndex : 'structureType', +// sortable : true, +// hidden : true +// }, +// +// { +// id : this.id + 'REMOVE', +// flex : 0.2, +// hidden : true, +// sortable : false, +// renderer : function(value, metaData, record, rowIndex, colIndex, store) { +// return BUI.getRedButton('REMOVE'); +// } +// }, ], +// +// listeners : { +// itemdblclick : function(dataview, record, item, e) { +// _this._editExperiment(record.raw.experimentId); +// }, +// cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { +// +// if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'REMOVE') { +// var dataAdapter = new BiosaxsDataAdapter(); +// dataAdapter.onSuccess.attach(function() { +// _this.pdbGrid.setLoading(false); +// _this.update(); +// }); +// dataAdapter.removeStructure(record.data.structureId); +// _this.pdbGrid.setLoading("Removing PDB file"); +// } +// +// } +// }, +// viewConfig : { +// getRowClass : function(record, rowIdx, params, store) { +// if (record.raw.isSubunit != null) { +// return "blue-row"; +// } +// } +// } +// }); +// +// return this.pdbGrid; +//}; +// +//MacromoleculeForm.prototype.getMolarityForm = function(macromolecule) { +// var _this = this; +// var data = []; +// for (var i = 0; i < BIOSAXS.proposal.macromolecules.length; i++) { +// var m = BIOSAXS.proposal.macromolecules[i]; +// if (m.macromoleculeId != macromolecule.macromoleculeId) { +// data.push(m); +// } +// +// } +// this.macromoleculeCombo = BIOSAXS_COMBOMANAGER.getComboMacromoleculeByMacromolecules(data, { +// width : 250, +// labelWidth : 100, +// margin : 10 +// }); +// +// return Ext.createWidget('form', { +// +// frame : false, +// border : 0, +// // padding : 15, +// width : 550, +// height : 350, +// items : [ { +// xtype : 'container', +// flex : 1, +// border : false, +// layout : 'anchor', +// defaultType : 'requiredtext', +// items : [ this.macromoleculeCombo, { +// xtype : 'numberfield', +// name : 'Ratio', +// id : _this.id + "ratio", +// fieldLabel : 'Number in assymmetric units', +// value : 1, +// decimalPrecision : 6, +// margin : 10 +// }, { +// xtype : 'textareafield', +// name : 'comments', +// fieldLabel : 'Comments', +// margin : 10, +// width : 400, +// value : "" +// +// } ] +// } ] +// }); +// +//}; +// +///******************************************************************************* +// * JAVASCRIPT DOC +// ******************************************************************************/ +//MacromoleculeForm.prototype.input = function() { +// return { +// macromolecule : DATADOC.getMacromolecule_10() +// }; +//}; +// +//MacromoleculeForm.prototype.test = function(targetId) { +// var macromoleculeForm = new MacromoleculeForm(); +// var panel = macromoleculeForm.getPanel(macromoleculeForm.input().macromolecule); +// panel.render(targetId); +//}; -GraphCanvas.prototype.setVertexStroke = function(vertexId, value) { - this.getFormatter().getVertexById(vertexId).getDefault().setStroke(value); -}; +function ResultSummaryForm() { + this.radiationDamageThreshold = BUI.getRadiationDamageThreshold(); + this.qualityThreshold = BUI.getQualityThreshold(); + + /** Data clusters with bufers **/ + this.clusterByBuffers = false; + + /** Visualization are groupeb by concenttrations. Ex: 4.5mg/ml and 4.7mg/ml will be clusterized together **/ + this.collapseConcentrations = true; + + this.summaryHeight = 350; + this.id = BUI.id(); + + var _this = this; + + this.qualityControlResultsWidget = new QualityControlResultsWidget({ + qualityThreshold : this.radiationDamageThreshold, + radiationDamageThreshold : this.qualityThreshold + + }); + this.qualityControlResultsWidget.onQualityChanged.attach(function(sender, value) { + _this.qualityThreshold = value; + _this.thresholdsChanged(); + }); + + this.qualityControlResultsWidget.onRadiationDatamageChanged.attach(function(sender, value) { + _this.radiationDamageThreshold = value; + _this.thresholdsChanged(); + + }); + this.concentrationHTMLTableWidget = new ConcentrationHTMLTableWidget({ + height : 250, + showBufferColumns : this.clusterByBuffers + }); + + this.plot = new BoxWhiskerGraph({ + targetId : _this.id + '_boxPlot', + height : 350, + width : 450, + maxBoxWidth : 25 + }); + + this.rangePlot = new RangeWhiskerGraph({ + targetId : _this.id + '_rangePlot', + height : 350, + width : 450, + maxBoxWidth : 25 + }); +} + +ResultSummaryForm.prototype.thresholdsChanged = function() { + var parsedData = this.prepareData(this.rawData); + + var filtered = JSON.parse(JSON.stringify(parsedData)); + filtered.concentration.concentrations = []; + for ( var conc in parsedData.concentration.concentrations) { + if (parsedData.concentration.concentrations[conc].calculation.rgGnom.validNumber > 0) { + filtered.concentration.concentrations.push(parsedData.concentration.concentrations[conc]); + } + } + + this.plotWhisker(filtered); + this.plotRange(filtered); + + this.concentrationHTMLTableWidget.refresh(parsedData); +}; + +/** Given a frame object (object returned by analyzeFrames()) and depending of the threshold indicates if a datacollection has radiation damage **/ +ResultSummaryForm.prototype.hasRadiationDamage = function(frameObject) { + var bb = frameObject.bufferBeforeFramesMerged / frameObject.framesCount; + var ba = frameObject.bufferAfterFramesMerged / frameObject.framesCount; + var mol = frameObject.framesMerge / frameObject.framesCount; + return !((bb >= this.radiationDamageThreshold) && (ba >= this.radiationDamageThreshold) && (mol >= this.radiationDamageThreshold)); +}; + +/** Return (frameObject) an object with the information about the frames for a data collection**/ +ResultSummaryForm.prototype.analyzeFrames = function(dataCollectionRow) { + return { + bufferAfterFramesMerged : dataCollectionRow.bufferAfterFramesMerged, + bufferBeforeFramesMerged : dataCollectionRow.bufferBeforeFramesMerged, + framesCount : dataCollectionRow.framesCount, + framesMerge : dataCollectionRow.framesMerge + }; +}; + +ResultSummaryForm.prototype.detectDataCollectionWarnings = function(dataCollectionRow) { + var frameObject = this.analyzeFrames(dataCollectionRow); + var warnings = { + count : 0, + type : [] + }; + + if (this.hasRadiationDamage(frameObject)) { + warnings.count = warnings.count + 1; + warnings.type.push("RADIATION DAMAGE"); + } + + if (Number(dataCollectionRow.quality) < this.qualityThreshold) { + warnings.count = 1;//warnings.count + 1; + warnings.type.push("Quality <" + this.qualityThreshold); + } + return warnings; +}; + +/** Return array composed by {concentration} objects **/ +ResultSummaryForm.prototype.getConcentrations = function(data) { + var concentrationsId = {}; + + for ( var i = 0; i < data.length; i++) { + var warning = this.detectDataCollectionWarnings(data[i]); + var id = data[i].conc;// + "_" + data[i].bufferId; + if (this.clusterByBuffers) { + id = data[i].conc + "_" + data[i].bufferId; + } + + if (concentrationsId[id] == null) { + concentrationsId[id] = { + id : id, + concentration : Number(data[i].conc).toFixed(2), + bufferId : data[i].bufferId, + bufferAcronym : data[i].bufferAcronym, + rgGuinier : [], + i0Guinier : [], + rgGnom : [], + dMax : [], + quality : [], + frames : [], + frames_warning : warning.count + }; + } else { + concentrationsId[id].frames_warning = concentrationsId[id].frames_warning + warning.count; + } + + concentrationsId[id].frames.push(data[i]); + + if (warning.count == 0) { + concentrationsId[id].rgGuinier.push(data[i].rgGuinier); + concentrationsId[id].i0Guinier.push(data[i].I0); + concentrationsId[id].quality.push(data[i].quality); + concentrationsId[id].rgGnom.push(data[i].rgGnom); + concentrationsId[id].dMax.push(data[i].dmax); + } + + } + var concentrations = []; + for ( var item in concentrationsId) { + if (concentrationsId.hasOwnProperty(item)) { + concentrations.push({ + concentration : concentrationsId[item].concentration, + id : item, + bufferId : Number(concentrationsId[item].bufferId).toFixed(2), + bufferAcronym : concentrationsId[item].bufferAcronym, + rgGuinier : concentrationsId[item].rgGuinier, + /** Frames **/ + frames : concentrationsId[item].frames, + frames_warning : concentrationsId[item].frames_warning, + /** Calculation **/ + calculation : { + rgGuinier : BUI.getStandardDeviation(concentrationsId[item].rgGuinier), + i0Guinier : BUI.getStandardDeviation(concentrationsId[item].i0Guinier), + quality : BUI.getStandardDeviation(concentrationsId[item].quality), + rgGnom : BUI.getStandardDeviation(concentrationsId[item].rgGnom), + dMax : BUI.getStandardDeviation(concentrationsId[item].dMax) + + } + }); + } + } + + return { + concentrations : concentrations + }; +}; + +ResultSummaryForm.prototype.prepareData = function(data) { + /** Return array composed by {acronym, bufferId} objects **/ + function getBuffers(data) { + var buffersId = {}; + for ( var i = 0; i < data.length; i++) { + buffersId[data[i].bufferId] = data[i].acronym; + } + var buffers = []; + for ( var id in buffersId) { + if (buffersId.hasOwnProperty(id)) { + buffers.push({ + acronym : buffersId[id], + bufferId : id + }); + } + } + return buffers; + } + + /** Get a string with all the concentrations **/ + function getConcentrationString(parseConcentrations) { + var concentrations = []; + for ( var i = 0; i < parseConcentrations.concentrations.length; i++) { + concentrations.push(parseConcentrations.concentrations[i].concentration + " mg/ml "); + } + return concentrations.toString(); + } + + var parseConcentrations = this.getConcentrations(data); + + return { + dataCollectionCount : data.length, + buffers : getBuffers(data), + concentration : parseConcentrations, + concentrationLabel : getConcentrationString(parseConcentrations) + }; +}; + +ResultSummaryForm.prototype.getDataForWhisker = function(data) { + var clusters = []; + + var concentrations = {}; + var i = 0; + var conc = 0; + if (this.collapseConcentrations) { + for (i = 0; i < data.concentration.concentrations.length; i++) { + conc = data.concentration.concentrations[i]; + var concentration = Number(conc.concentration).toFixed(0); + if (concentrations[concentration] == null) { + concentrations[concentration] = {}; + concentrations[concentration].concentration = concentration; + concentrations[concentration].calculation = {}; + concentrations[concentration].calculation.rgGuinier = {}; + concentrations[concentration].calculation.rgGuinier.values = []; + concentrations[concentration].calculation.rgGuinier.values = conc.calculation.rgGuinier.values; + concentrations[concentration].calculation.rgGnom = {}; + concentrations[concentration].calculation.rgGnom.values = []; + concentrations[concentration].calculation.rgGnom.values = conc.calculation.rgGnom.values; + } else { + concentrations[concentration].calculation.rgGuinier.values = concentrations[concentration].calculation.rgGuinier.values + .concat(conc.calculation.rgGuinier.values); + concentrations[concentration].calculation.rgGnom.values = concentrations[concentration].calculation.rgGnom.values + .concat(conc.calculation.rgGnom.values); + } + } + + /** From object to array **/ + var array = []; + for ( var key in concentrations) { + if (concentrations.hasOwnProperty(key)) { + array.push(concentrations[key]); + } + } + data.concentration.concentrations = array; + } + + for (i = 0; i < data.concentration.concentrations.length; i++) { + conc = data.concentration.concentrations[i]; + clusters.push({ + name : conc.concentration + "mg/ml", + concentration : Number(conc.concentration), + x : Number(conc.concentration), + classes : [] + }); + clusters[clusters.length - 1].classes.push({ + name : "Guinier", + color : '#9A2EFE', + values : conc.calculation.rgGuinier.values + + }); + clusters[clusters.length - 1].classes.push({ + name : "P(r)", + color : '#2E64FE', + values : conc.calculation.rgGnom.values + + }); + } + return { + clusters : clusters.sort(function(a, b) { + return a.concentration - b.concentration; + }) + }; +}; + +ResultSummaryForm.prototype.getDataForWhiskerQuality = function(data) { + var clusters = []; + + for ( var i = 0; i < data.concentration.concentrations.length; i++) { + var conc = data.concentration.concentrations[i]; + clusters.push({ + name : conc.concentration + "mg/ml", + classes : [] + }); + clusters[clusters.length - 1].classes.push({ + name : "Quality", + values : conc.calculation.quality.values + + }); + } + + return { + clusters : clusters + }; +}; + +ResultSummaryForm.prototype.plotQualityWhisker = function(parsedData) { + this.qualityPlot.refresh(this.getDataForWhiskerQuality(parsedData)); +}; + +ResultSummaryForm.prototype.plotWhisker = function(parsedData) { + this.plot.refresh(this.getDataForWhisker(parsedData)); +}; + +ResultSummaryForm.prototype.plotRange = function(parsedData) { + this.rangePlot.refresh(this.getDataForWhisker(parsedData)); +}; + +ResultSummaryForm.prototype.getPanel = function(data) { + var _this = this; + _this.rawData = data; + var parsedData = this.prepareData(data); + + this.panel = Ext + .createWidget( + 'form', + { + bodyPadding : 20, + frame : false, + border : 0, + width : this.width, + height : this.summaryHeight + 1000, + items : [ { + xtype : 'container', + layout : 'hbox', + items : [ { + xtype : 'container', + flex : 1, + border : false, + layout : 'anchor', + defaultType : 'textfield', + items : [ + _this.qualityControlResultsWidget.getPanel(), + { + xtype : 'fieldset', + width : 950, + margin : "20, 0 0 0", + height : this.summaryHeight + 500, + items : [ + { + html : "
Concentration Analysis
", + border : 0, + width : 900 + + }, + { + html : this.concentrationHTMLTableWidget.getPanel(parsedData), + border : 0, + width : 900, + margin : "10, 0 0 10" + + }, + { + xtype : 'container', + layout : 'vbox', + border : 5, + items : [ + { + html : "
Rg based on Guinier and Gnom
", + border : 8, + width : 900, + margin : "20 0 0 10" + + }, { + xtype : 'container', + layout : 'hbox', + items : [ { + xtype : 'container', + layout : 'vbox', + items : [ { + html : "
", + border : 0, + width : this.plot.width, + padding : "10 0 0 20", + listeners : { + afterrender : function() { + _this.plotWhisker(parsedData); + + } + } + }, { + html : "
Concentration (mg/ml)
", + width : 450, + border : 0, + margin : "-50 0 0 0" + + } ] + }, { + xtype : 'container', + layout : 'vbox', + items : [ { + html : "
", + border : 0, + width : this.rangePlot.width, + padding : "10 0 0 10", + listeners : { + afterrender : function() { + _this.plotRange(parsedData); + } + } + }, { + html : "
Concentration (mg/ml)
", + width : 450, + border : 0, + margin : "-50 0 0 0" + + } ] + } ] + } ] + } ] + } ] + } + + ] + } ] + }); + return this.panel; + +}; + +ResultSummaryForm.prototype.input = function() { + return { + data : DATADOC.getData_3367() + }; +}; + +ResultSummaryForm.prototype.test = function(targetId) { + var resultSummaryForm = new ResultSummaryForm(); + var panel = resultSummaryForm.getPanel(resultSummaryForm.input().data); + panel.render(targetId); + +}; -GraphCanvas.prototype.getVertexStroke = function(vertexId) { - return this.getFormatter().getVertexById(vertexId).getDefault().getStroke(); -}; +/** + * Example form + * + * @witdh + * @height + */ +function RigibBodyModelingForm(args) { + this.id = BUI.id(); + this.width = 700; + this.height = 500; + + if (args != null) { + if (args.width != null) { + this.width = args.width; + } + if (args.height != null) { + this.height = args.height; + } + } + + var _this = this; + this.rigidBodyGrid = new AprioriRigidBodyGrid(); + + this.rigidBodyGrid.onUploadFile.attach(function(sender, type, title){ + _this._openUploadDialog(_this.macromolecule.macromoleculeId, type, title); + }); + + this.rigidBodyGrid.onRemove.attach(function(sender, type, title){ + _this._update(); + }); + + this.onSave = new Event(this); + +} + +RigibBodyModelingForm.prototype._getItems = function() { + var _this = this; + + + return [ { + xtype : 'label', + forId : 'myFieldId', + text : 'Information for model fit, mixture analysis and rigid body modeling', + margin : '15 0 20 10', + cls : "inline-help" + }, + this.rigidBodyGrid.getPanel(), + { + xtype : 'label', + forId : 'myFieldId', + text : 'Distance restraints may be imposed on the model using contacts conditions file (OPTIONAL)', + margin : '25 0 5 10', + cls : "inline-help" + }, + { + xtype : 'container', + layout : 'hbox', + items : [ { + xtype : 'container', + border : false, + layout : 'hbox', + items : [ { + xtype : 'label', + forId : 'myFieldId', + text : 'Contact Description File: (Optional)', + width : 150, + margin : '10 0 0 10' + }, { + id : this.id + "contactsDescriptionFilePath", + xtype : 'textfield', + hideLabel : true, + margin : '10 0 0 0', + width : 200, + disabled: true + }, { + text : 'Upload', + xtype : 'button', + margin : "10 0 0 10", + width : 80, + handler : function() { + + _this._openUploadDialog(_this.macromolecule.macromoleculeId, "CONTACTS", "Upload Contact Description File"); + } + }, { + text : 'Remove', + id : _this.id + "_remove", + xtype : 'button', + margin : "10 0 0 10", + width : 80, + handler : function() { + _this.macromolecule.contactsDescriptionFilePath = null; + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, proposal) { + /** Updating the proposal global object **/ + BIOSAXS.proposal.setItems(proposal); + _this.panel.setLoading(false); + + var saved = BIOSAXS.proposal.getMacromoleculeByAcronym(_this.macromolecule.acronym); + /** Refreshing to check that everything is ok **/ + _this.refresh(saved); + _this.onSave.notify(saved); + }); + + _this.panel.setLoading("Saving Macromolecule") + adapter.saveMacromolecule(_this.macromolecule); + } + } ] + } ] + }, { + xtype : 'panel', + html : "Go to SASREF manual for further information", + margin : "10 0 0 160", + border : 0 + + }, + { + xtype : 'checkbox', + margin : '10 0 0 5', + boxLabel : "I want rigid body modeling run on this stuff", + checked : true, + width : 300 + } ] + +}; + +/** Because update is a jsp page we don't know if the user has uploaded a file or not then we need to refresh **/ +RigibBodyModelingForm.prototype._update = function(macromoleculeId, type, title) { + var _this = this; + BIOSAXS.proposal.onInitialized.attach(function() { + if (BIOSAXS.proposal != null) { + _this.refresh(BIOSAXS.proposal.getMacromoleculeById(_this.macromolecule.macromoleculeId)); + _this.panel.setLoading(false); + } + }); + this.panel.setLoading(); + BIOSAXS.proposal.init(); +}; + +RigibBodyModelingForm.prototype._openUploadDialog = function(macromoleculeId, type, title) { + var _this = this; + function onClose() { + w.destroy(); + _this._update(); + + } + + var w = Ext.create('Ext.window.Window', { + title : title, + height : 200, + width : 400, + modal : true, + buttons : [ { + text : 'Close', + handler : function() { + onClose(); + } + } ], + layout : 'fit', + items : { + html : "" + }, + listeners : { + onEsc : function() { + onClose(); + }, + close : function() { + onClose(); + } + } + }).show(); +}; + +RigibBodyModelingForm.prototype._getButtons = function() { + return []; +}; + +RigibBodyModelingForm.prototype.getPanel = function() { + var _this = this; + this.panel = Ext.create('Ext.form.Panel', { + width : this.width, + height : this.height, + margin : 10, + border : 1, + defaultType : 'textfield', + items : this._getItems(), + buttons : this._getButtons(), + listeners : { + afterrender : function(){ + _this._populate(); + + } + } + }); + return this.panel; +}; + +/** Populates could be call when the DOM is not filled yet **/ +RigibBodyModelingForm.prototype._populate = function() { + if (this.macromolecule != null){ + if (Ext.getCmp(this.id + "contactsDescriptionFilePath") != null){ + if (this.macromolecule.contactsDescriptionFilePath != null){ + Ext.getCmp(this.id + "contactsDescriptionFilePath").setValue(this.macromolecule.contactsDescriptionFilePath); + Ext.getCmp(this.id + "_remove").enable(); + } + else{ + Ext.getCmp(this.id + "_remove").disable(); + Ext.getCmp(this.id + "contactsDescriptionFilePath").setValue(""); + + } + } + } +}; + +/** It populates the form * */ +RigibBodyModelingForm.prototype.refresh = function(macromolecule) { + this.macromolecule = macromolecule; + this.rigidBodyGrid.refresh(macromolecule); + this._populate(); +}; + +RigibBodyModelingForm.prototype.input = function() { + return {}; +}; + + +/** It populates the form **/ +RigibBodyModelingForm.prototype.test = function(targetId) { + var macromoleculeForm = new RigibBodyModelingForm(); + var panel = macromoleculeForm.getPanel(); + panel.render(targetId); +}; + -GraphCanvas.prototype.setVertexStrokeOpacity = function(vertexId, value) { - this.getFormatter().getVertexById(vertexId).getDefault().setStrokeOpacity(value); -}; +/** + * Same form as MX part + * + * @creationMode if true a create button appears instead of save + * @showTitle true or false + */ +function ShipmentForm(args) { + this.id = BUI.id(); + + this.creationMode = false; + this.showTitle = true; + if (args != null) { + if (args.creationMode != null) { + this.creationMode = args.creationMode; + } + if (args.showTitle != null) { + this.showTitle = args.showTitle; + } + } + + this.onSaved = new Event(this); +} + +ShipmentForm.prototype.fillStores = function() { + this.panel.setLoading("Loading Labcontacts from database"); + this.labContactForSendingStore.loadData(BIOSAXS.proposal.getLabcontacts(), false); + this.labContactForReturnStore.loadData(BIOSAXS.proposal.getLabcontacts(), false); + this.panel.setLoading(false); + if (this.shipment != null) { + this.setShipment(this.shipment); + } +}; + +ShipmentForm.prototype.draw = function(targetId) { + this.getPanel().render(targetId); +}; + +ShipmentForm.prototype.setShipment = function(shipment) { + this.shipment = shipment; + var _this = this; + Ext.getCmp(_this.id + "shippingName").setValue(shipment.json.shippingName); + Ext.getCmp(_this.id + "shippingStatus").setValue(shipment.json.shippingStatus); + Ext.getCmp(_this.id + "comments").setValue(shipment.json.comments); + if (shipment.json.sendingLabContactVO != null) { + this.labContactsSendingCombo.setValue(shipment.json.sendingLabContactVO.labContactId); + } + if (shipment.json.returnLabContactVO != null) { + this.labContactsReturnCombo.setValue(shipment.json.returnLabContactVO.labContactId); + } + +}; + +ShipmentForm.prototype._saveShipment = function() { + var _this = this; + var shippingId = null; + if (this.shipment != null) { + shippingId = this.shipment.json.shippingId; + } + var json = { + shippingId : shippingId, + name : Ext.getCmp(_this.id + "shippingName").getValue(), + status : Ext.getCmp(_this.id + "shippingStatus").getValue(), + sendingLabContactId : Ext.getCmp(_this.id + "shipmentform_sendingLabContactId").getValue(), + returnLabContactId : Ext.getCmp(_this.id + "returnLabContactId").getValue(), + returnCourier : Ext.getCmp(_this.id + "returnCourier").getValue(), + courierAccount : Ext.getCmp(_this.id + "courierAccount").getValue(), + BillingReference : Ext.getCmp(_this.id + "BillingReference").getValue(), + dewarAvgCustomsValue : Ext.getCmp(_this.id + "dewarAvgCustomsValue").getValue(), + dewarAvgTransportValue : Ext.getCmp(_this.id + "dewarAvgTransportValue").getValue(), + comments : Ext.getCmp(_this.id + "comments").getValue() + }; + + var dataAdapter = new BiosaxsDataAdapter(); + dataAdapter.onSuccess.attach(function(sender, shipment) { + window.location = BUI.getShippingURL(shipment.shippingId); + }); + + dataAdapter.onError.attach(function(sender, error) { + _this.onError.notify(error); + }); + + /** Cheking params **/ + if (json.name == "") { + BUI.showError("Name field is mandatory"); + return; + } + + if (json.sendingLabContactId == null) { + BUI.showError("Lab contact for sending field is mandatory"); + return; + } + + if (json.returnLabContactId == null) { + BUI.showError("Lab contact for return field is mandatory"); + return; + } + + dataAdapter.createShipment(json.shippingId, json.name, json.status, json.comments, json.sendingLabContactId, json.returnLabContactId, + json.returnCourier, json.courierAccount, json.BillingReference, json.dewarAvgCustomsValue, json.dewarAvgTransportValue); + +}; + +ShipmentForm.prototype.getPanel = function(shipment) { + var _this = this; + this.shipment = shipment; + var required = '*'; + var buttons = []; + + if (_this.creationMode) { + buttons.push({ + text : 'Create', + scope : this, + handler : function() { + _this._saveShipment(); + } + }); + } else { + buttons.push({ + text : 'Save', + scope : this, + handler : function() { + _this._saveShipment(); + } + }); + + } + + this.labContactForSendingStore = Ext.create('Ext.data.Store', { + fields : [ 'cardName', 'labContactId' ] + }); + + this.labContactForReturnStore = Ext.create('Ext.data.Store', { + fields : [ 'cardName', 'labContactId' ] + }); + + // Create the combo box, attached to the states data store + this.labContactsSendingCombo = Ext.create('Ext.form.ComboBox', { + id : _this.id + "shipmentform_sendingLabContactId", + fieldLabel : 'Lab contact for sending', + afterLabelTextTpl : required, + store : this.labContactForSendingStore, + queryMode : 'local', + labelWidth : 200, + displayField : 'cardName', + valueField : 'labContactId' + }); + + this.labContactsReturnCombo = Ext.create('Ext.form.ComboBox', { + id : _this.id + "returnLabContactId", + fieldLabel : 'If No, Lab-Contact for Return', + afterLabelTextTpl : required, + store : this.labContactForReturnStore, + queryMode : 'local', + labelWidth : 200, + displayField : 'cardName', + valueField : 'labContactId', + listeners : { + change : function(x, newValue) { + for ( var i = 0; i < x.getStore().data.items.length; i++) { + if (x.getStore().data.items[i].raw.labContactId == newValue) { + Ext.getCmp(_this.id + "returnCourier").setValue(x.getStore().data.items[i].raw.defaultCourrierCompany); + Ext.getCmp(_this.id + "courierAccount").setValue(x.getStore().data.items[i].raw.courierAccount); + Ext.getCmp(_this.id + "BillingReference").setValue(x.getStore().data.items[i].raw.billingReference); + Ext.getCmp(_this.id + "dewarAvgCustomsValue").setValue(x.getStore().data.items[i].raw.dewarAvgCustomsValue); + Ext.getCmp(_this.id + "dewarAvgTransportValue").setValue(x.getStore().data.items[i].raw.dewarAvgTransportValue); + } + } + } + } + }); + + if (this.panel == null) { + this.panel = Ext.create('Ext.form.Panel', { + bodyPadding : 5, + width : 600, + border : 1, + items : [ { + xtype : 'fieldset', + title : 'Details', + collapsible : false, + defaultType : 'textfield', + layout : 'anchor', + defaults : { + anchor : '100%' + }, + items : [ { + xtype : 'requiredtext', + fieldLabel : 'Shipment Label', + allowBlank : false, + name : 'shippingName', + id : _this.id + 'shippingName', + value : '', + anchor : '50%' + }, { + + xtype : 'textareafield', + name : 'comments', + id : _this.id + 'comments', + fieldLabel : 'Comments', + value : '' + }, { + fieldLabel : 'Status', + readOnly : true, + id : _this.id + 'shippingStatus', + value : 'Opened', + anchor : '50%' + } ] + }, { + xtype : 'fieldset', + title : 'Lab-Contacts', + collapsible : false, + defaultType : 'textfield', + layout : 'anchor', + defaults : { + anchor : '100%' + }, + items : [ this.labContactsSendingCombo, this.labContactsReturnCombo ] + }, { + border : 0, + html : BUI.getWarningHTML("These informations are relevant for all shipments") + }, { + xtype : 'fieldset', + title : 'Courier accounts details for return', + collapsible : false, + layout : 'anchor', + defaults : { + anchor : '100%' + }, + items : [ { + xtype : 'textfield', + labelWidth : 400, + fieldLabel : 'Courier company for return (if ESRF sends a dewar back)', + id : _this.id + 'returnCourier', + value : '' + }, { + xtype : 'textfield', + labelWidth : 400, + fieldLabel : 'Courier account', + id : _this.id + 'courierAccount', + value : '' + }, { + xtype : 'textfield', + labelWidth : 400, + fieldLabel : 'Billing reference', + id : _this.id + 'BillingReference', + value : '' + }, { + xtype : 'numberfield', + labelWidth : 400, + fieldLabel : 'Average Customs value of a dewar (Euro)', + id : _this.id + 'dewarAvgCustomsValue', + value : '' + }, { + xtype : 'numberfield', + labelWidth : 400, + fieldLabel : 'Average Transport value of a dewar (Euro)', + id : _this.id + 'dewarAvgTransportValue', + value : '' + } ] + } ], + buttons : buttons + }); + } + this.fillStores(); + if (this.showTitle) { + this.panel.setTitle('Create a new Shipment'); + } + return this.panel; +}; + +ShipmentForm.prototype.input = function() { + return { + proposal : DATADOC.getProposal_10() + + }; +}; + +ShipmentForm.prototype.test = function(targetId) { + var shipmentForm = new ShipmentForm({ + creationMode : true + + }); + BIOSAXS.proposal = new Proposal(shipmentForm.input().proposal); + shipmentForm.getPanel().render(targetId); +}; -GraphCanvas.prototype.getVertexStrokeOpacity = function(vertexId) { - return this.getFormatter().getVertexById(vertexId).getDefault().getStrokeOpacity(); -}; +/** + * #onSaved + */ +function StockSolutionForm(args) { + this.id = BUI.id(); + this.actions = []; + + if (args != null) { + if (args.actions != null) { + this.actions = args.actions; + } + } + this.onSaved = new Event(this); +} + +StockSolutionForm.prototype.getStockSolution = function() { + if (this.stockSolution != null) { + this.stockSolution.concentration = Ext.getCmp(this.id + "stockSolution_concentration").getValue(); + this.stockSolution.storageTemperature = Ext.getCmp(this.id + "stockSolution_storageTemperature").getValue(); + this.stockSolution.volume = Ext.getCmp(this.id + "stockSolution_volume").getValue(); + this.stockSolution.comments = Ext.getCmp(this.id + "stockSolution_comments").getValue(); + this.stockSolution.name = Ext.getCmp(this.id + "stockSolution_name").getValue(); + this.stockSolution.bufferId = this.bufferCombo.getValue(); + + if (this.macromoleculeCombo.getValue() != null) { + this.stockSolution.macromoleculeId = this.macromoleculeCombo.getValue(); + } else { + this.stockSolution.macromolecule3VO = null; + } + + } else { + return { + concentration : Ext.getCmp(this.id + "stockSolution_concentration").getValue(), + storageTemperature : Ext.getCmp(this.id + "stockSolution_storageTemperature").getValue(), + volume : Ext.getCmp(this.id + "stockSolution_volume").getValue(), + comments : Ext.getCmp(this.id + "stockSolution_comments").getValue(), + name : Ext.getCmp(this.id + "stockSolution_name").getValue(), + bufferId : this.bufferCombo.getValue(), + macromoleculeId : this.macromoleculeCombo.getValue() + }; + } + return this.stockSolution; +}; + +StockSolutionForm.prototype.setStockSolution = function(stockSolution) { + if (stockSolution != null) { + if (stockSolution.macromoleculeId != null) { + this.macromoleculeCombo.setValue(stockSolution.macromoleculeId); + } + this.bufferCombo.setValue(stockSolution.bufferId); + Ext.getCmp(this.id + "stockSolution_concentration").setValue(this.stockSolution.concentration); + Ext.getCmp(this.id + "stockSolution_storageTemperature").setValue(this.stockSolution.storageTemperature); + Ext.getCmp(this.id + "stockSolution_volume").setValue(this.stockSolution.volume); + Ext.getCmp(this.id + "stockSolution_name").setValue(this.stockSolution.name); + Ext.getCmp(this.id + "stockSolution_comments").setValue(this.stockSolution.comments); + } +}; + +StockSolutionForm.prototype.getBufferCombo = function() { + this.bufferCombo = BIOSAXS_COMBOMANAGER.getComboBuffers(BIOSAXS.proposal.getBuffers(), { + labelWidth : 120, + margin : '0 0 10 0', + width : 220 + + }); + return this.bufferCombo; +}; + +StockSolutionForm.prototype.getMacromoleculeCombo = function() { + this.macromoleculeCombo = BIOSAXS_COMBOMANAGER.getComboMacromoleculeByMacromolecules(BIOSAXS.proposal.getMacromolecules(), { + labelWidth : 120, + margin : '0 0 10 0', + width : 220 + + }); + return this.macromoleculeCombo; +}; + +StockSolutionForm.prototype.refresh = function() { +}; + +StockSolutionForm.prototype._getTopPanel = function() { + return { + xtype : 'container', + layout : 'hbox', + border : 0, + items : [ { + xtype : 'container', + layout : 'hbox', + items : [ { + xtype : 'container', + flex : 1, + border : false, + layout : 'anchor', + defaultType : 'textfield', + items : [ + + this.getMacromoleculeCombo(), { + xtype : 'requiredtext', + id : this.id + 'stockSolution_name', + fieldLabel : 'Acronym', + labelWidth : 120, + width : 250 + }, { + xtype : 'requiredtext', + id : this.id + 'stockSolution_concentration', + fieldLabel : 'Conc. (mg/ml)', + labelWidth : 120, + width : 250 + }, + + { + id : this.id + 'stockSolution_storageTemperature', + fieldLabel : 'Storage Temp.(C)', + labelWidth : 120, + width : 250 + }, { + xtype : 'requiredtext', + id : this.id + 'stockSolution_volume', + fieldLabel : 'Volume in Well (µl)', + labelWidth : 120, + width : 250 + } ] + } ] + }, { + xtype : 'container', + flex : 1, + layout : 'anchor', + defaultType : 'textfield', + margin : '0 0 0 10', + items : [ this.getBufferCombo() ] + } ] + }; + +}; + +StockSolutionForm.prototype.getPanel = function(stockSolution) { + this.stockSolution = stockSolution; + this.panel = Ext.createWidget({ + xtype : 'container', + layout : 'vbox', + border : 0, + style : { + padding : '10px' + }, + fieldDefaults : { + labelAlign : 'left', + labelWidth : 50 + }, + items : [ this._getTopPanel(stockSolution), { + id : this.id + 'stockSolution_comments', + xtype : 'textareafield', + name : 'comments', + fieldLabel : 'Comments', + labelWidth : 120, + width : '100%' + } ] + }); + + this.setStockSolution(stockSolution); + return this.panel; +}; + +StockSolutionForm.prototype.input = function() { + return { + stock : { + "stockSolutionId" : 6, + "proposalId" : 3124, + "macromoleculeId" : 5933, + "bufferId" : 811, + "instructionSet3VO" : null, + "boxId" : 305861, + "storageTemperature" : "20", + "volume" : "300", + "concentration" : "1.2", + "comments" : "Buffer EDTA with A", + "name" : "A_EDTA_1.2", + "samples" : [], + "buffer" : "EDTA", + "macromolecule" : "A" + }, + proposal : new MeasurementGrid().input().proposal + }; +}; + +StockSolutionForm.prototype.test = function(targetId) { + var stockSolutionForm = new StockSolutionForm(); + BIOSAXS.proposal = new Proposal(stockSolutionForm.input().proposal); + var panel = stockSolutionForm.getPanel(new Shipment(stockSolutionForm.input().stock)); + panel.render(targetId); +}; -GraphCanvas.prototype.setVertexOpacity = function(vertexId, value) { - this.getFormatter().getVertexById(vertexId).getDefault().setOpacity(value); -}; + +BoxWhiskerGraph.prototype.cleanArray = GenericGraph.prototype.cleanArray; +BoxWhiskerGraph.prototype.plotAxes = GenericGraph.prototype.plotAxes; +BoxWhiskerGraph.prototype.plotRuler = GenericGraph.prototype.plotRuler; +BoxWhiskerGraph.prototype.drawSVGVerticalText = GenericGraph.prototype.drawSVGVerticalText; +BoxWhiskerGraph.prototype.getClassColor = GenericGraph.prototype.getClassColor; +BoxWhiskerGraph.prototype.getDimensions = GenericGraph.prototype.getDimensions; +BoxWhiskerGraph.prototype.calculate = GenericGraph.prototype.calculate; +BoxWhiskerGraph.prototype.getMedian = GenericGraph.prototype.getMedian; +BoxWhiskerGraph.prototype.pointToPixel = GenericGraph.prototype.pointToPixel; +BoxWhiskerGraph.prototype.maxValueWhisker = GenericGraph.prototype.maxValueWhisker; +BoxWhiskerGraph.prototype.refresh = GenericGraph.prototype.refresh; + +/** + * Subclass of GenericGraph + * + * @maxBoxWidth + */ +function BoxWhiskerGraph(args){ + this.maxBoxWidth = 25; + + if (args == null){ + args = new Object(); + } + args["plotHorizontalByCluster"] = true; + + GenericGraph.call(this, args); + + if (args.maxBoxWidth != null){ + this.maxBoxWidth = args.maxBoxWidth; + } +}; + + + +/** +There are several different methods for calculating quartiles.[1] This calculator uses a method described by Moore and McCabe to find quartile values. +The same method also used by The TI-83 to calculate quartile values. +With this method, the first quartile is the median of the numbers below the median, the third quartile is the median of the numbers above the median. + +http://www.miniwebtool.com/quartile-calculator/ +http://www.alcula.com/calculators/statistics/box-plot/ +**/ +BoxWhiskerGraph.prototype.getQ1 = function(array){ + array = array.slice(0, array.length/2); + return this.getMedian(array); +}; + +BoxWhiskerGraph.prototype.getQ3 = function(array){ + array = array.slice((array.length + 1)/2); + return this.getMedian(array); + +}; + +BoxWhiskerGraph.prototype.getQ2 = function(array){ + return this.getMedian(array); +}; + +BoxWhiskerGraph.prototype.getBelowOutliers = function(belowLimit, array){ + var points = new Array(); + for (var i = 0; i < array.length; i++){ + if (array[i] <= belowLimit){ + points.push(array[i]); + } + } + return points; +}; + +BoxWhiskerGraph.prototype.getAboveOutliers = function(aboveLimit, array){ + var points = new Array(); + for (var i = 0; i < array.length; i++){ + if (array[i] >= aboveLimit){ + points.push(array[i]); + } + } + return points; +}; + + +BoxWhiskerGraph.prototype.minValueWhisker = function(belowLimit, q1, array){ + var points = new Array(); + + for (var i = 0; i < array.length; i++){ + if ((array[i] < q1) && (array[i]) > belowLimit){ + points.push(array[i]); + } + } + + if (points.length > 0){ + points.sort(function(a, b){return a - b;}); + return points[0]; + } + return null; +}; + +BoxWhiskerGraph.prototype.isNumber = function(value){ + if (value=="") return false; + + var d = parseInt(value); + if (!isNaN(d)) return true; else return false; + +}; + +BoxWhiskerGraph.prototype.plotBoxWhisker = function(boxProperties){ + if (this.maxBoxWidth != null){ + if (boxProperties.width > this.maxBoxWidth){ + boxProperties.x = boxProperties.x + (boxProperties.width/2) - (this.maxBoxWidth/2); + boxProperties.width = this.maxBoxWidth; + } + + } + + if (this.plotPoints){ + for(var i = 0; i < boxProperties.values.length; i++){ + var value = boxProperties.values[i]; + var toPixel = this.pointToPixel(value, boxProperties); + SVG.drawCircle(boxProperties.x + (boxProperties.width/2) + 2, toPixel, this.pointRadius, this.svg, [["fill", "green"], ["fill-opacity", this.fillOpacityPoint],['stroke-opacity', this.strokeOpacityPoint], ["stroke", "black"]]); + } + } + + + var boxColor = this.getClassColor(boxProperties.name); + var result = this.calculate(boxProperties.values); + /** Q1 **/ + + if (this.isNumber(result.Q1)){ + SVG.drawLine(boxProperties.x, this.pointToPixel(result.Q1, boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result.Q1, boxProperties), this.svg, [["stroke", boxColor]]); + } + /** Q2 **/ + if (this.isNumber(result.Q2)){ + SVG.drawLine(boxProperties.x, this.pointToPixel(result.Q2, boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result.Q2, boxProperties), this.svg, [["stroke", "blue"], ["stroke-width", "2"]]); + } + + /** Q3 **/ + if (this.isNumber(result.Q3)){ + SVG.drawLine(boxProperties.x, this.pointToPixel(result.Q3, boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result.Q3, boxProperties), this.svg, [["stroke", boxColor]]); + } + + /** Concenting Q1 and Q3 **/ + if (this.isNumber(result.Q1)&&this.isNumber(result.Q3)){ + SVG.drawLine(boxProperties.x, this.pointToPixel(result.Q1, boxProperties), boxProperties.x, this.pointToPixel(result.Q3, boxProperties), this.svg, [["stroke", boxColor]]); + SVG.drawLine(boxProperties.x + boxProperties.width, this.pointToPixel(result.Q1, boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result.Q3, boxProperties), this.svg, [["stroke", boxColor]]); + } + + /** min-whisker **/ + if (result["min-whisker"] != null){ + if (this.isNumber(result.Q1)){ + SVG.drawLine(boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result.Q1, boxProperties), boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result["min-whisker"], boxProperties), this.svg, [["stroke", boxColor]]); + } + SVG.drawLine(boxProperties.x,this.pointToPixel(result["min-whisker"], boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result["min-whisker"], boxProperties) , this.svg, [["stroke", boxColor]]); + + } + + /** max-whisker **/ + if (result["max-whisker"] != null){ + if (this.isNumber(result.Q3)){ + SVG.drawLine(boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result.Q3, boxProperties), boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result["max-whisker"], boxProperties), this.svg, [["stroke", boxColor]]); + } + SVG.drawLine(boxProperties.x , this.pointToPixel(result["max-whisker"], boxProperties), boxProperties.x + boxProperties.width, this.pointToPixel(result["max-whisker"], boxProperties), this.svg, [["stroke", boxColor]]); + + } + + /** outliners **/ + if (result["above-outliers"] != null){ + for (var point in result["above-outliers"]){ + SVG.drawCircle(boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result["above-outliers"][point], boxProperties), this.pointRadius, this.svg, [["fill", "red"], ["fill-opacity", "1"]]); + //SVG.drawText(boxProperties.x + (boxProperties.width/2) - 2, this.pointToPixel(result["above-outliers"][point], boxProperties) + 2, "x",this.svg, [["fill", "black"], ["font-size", "x-small"]]); + } + } + if (result["below-outliers"] != null){ + for (var point in result["below-outliers"]){ + SVG.drawCircle(boxProperties.x + (boxProperties.width/2) + 2, this.pointToPixel(result["below-outliers"][point], boxProperties), this.pointRadius, this.svg, [["fill", "red"], ["fill-opacity", "1"]]); + //SVG.drawText(boxProperties.x + (boxProperties.width/2) - 2, this.pointToPixel(result["below-outliers"][point], boxProperties) + 2, "x",this.svg, [["fill", "black"], ["font-size", "x-small"]]); + } + } +}; + + + +BoxWhiskerGraph.prototype.plotClusterTitles = function(properties){ + /** Cluster Titles **/ + var posX = this.left + this.rulerWidth; + var data = this.data; + for(var i = 0; i < data.clusters.length; i++ ){ + /** title for the clusters **/ + posX = posX + this.interClustersSpace; + + /** Drawing title of classes **/ + var cluster = data.clusters[i]; + var posXClasses = posX; + for(var j = 0; j < cluster.classes.length; j++){ + //SVG.drawRectangle(posXClasses, this.height - (this.bottom + this.clusterTitleHeight + this.rulerHeight), properties.classWidth, this.rulerHeight, this.svg, [["fill", "green"]]); +// SVG.drawText(posXClasses + 1/6*properties.classWidth, this.height - (this.bottom + this.clusterTitleHeight + (this.rulerHeight*1/4)), cluster.classes[j].name, this.svg, [["style", "font-size:xx-small"]]); + var color = cluster.classes[j].color; + this.drawSVGVerticalText(posXClasses + 1/2*(properties.classWidth), this.height - (this.bottom - this.clusterTitleHeight + (this.rulerHeight)), cluster.classes[j].name , [["style", "font-size:x-small;"], ["fill", color]]); + + // SVG.drawRectangle(posXClasses, this.height - (this.bottom + this.clusterTitleHeight), properties.classWidth, 2, this.svg, [["fill", "black"]]); + posXClasses = posXClasses + properties.classWidth + this.interClassesSpace; + } + + var clusterTitleSpace = (data.clusters[i].classes.length * properties.classWidth) + ((data.clusters[i].classes.length - 1) * this.interClassesSpace); + //SVG.drawRectangle(posX, this.height - (this.bottom + this.clusterTitleHeight), clusterTitleSpace, this.clusterTitleHeight, this.svg, [["fill", "pink"]]); + SVG.drawRectangle(posX, this.height - (this.clusterTitleHeight+this.bottom), clusterTitleSpace, 1, this.svg, []); + +// var transform = ["translate", "(" + posX + 1/3*clusterTitleSpace +", " + this.height - (this.bottom + (this.clusterTitleHeight*1/4)) +")"], ["transform", "rotate(180)"]; +// var transform = ["transform", "translate(" + (posX + 1/3*clusterTitleSpace) +", " + (this.height - (this.bottom + (this.clusterTitleHeight*1/4))) + "), rotate(-90) "]; +// this.drawSVGVerticalText(posX + 1/3*clusterTitleSpace, this.height - (this.bottom + (this.clusterTitleHeight*1/4)),data.clusters[i].name, [["style", "font-size:x-small"]]); + SVG.drawText(posX , this.height - (this.bottom + (this.clusterTitleHeight*1/4)),data.clusters[i].name ,this.svg, [["style", "font-size:x-small"]]); + posX = posX + clusterTitleSpace; + } +}; + +BoxWhiskerGraph.prototype.plotWhisters = function(data, properties){ + var colors = ["yellow", "orange", "green"]; + var posX = this.left + this.rulerWidth; + for(var i = 0; i < data.clusters.length; i++ ){ + var cluster = data.clusters[i]; + /** inter cluster space **/ + //SVG.drawRectangle(posX, this.top, this.interClustersSpace, this.height - this.top - this.bottom - this.clusterTitleHeight - this.rulerHeight, this.svg, [["fill", "black"]]); + posX = posX + this.interClustersSpace; + + for (var j = 0; j < cluster.classes.length; j ++){ + + //SVG.drawRectangle(posX, this.top, properties.classWidth, this.height - this.top - this.bottom - this.clusterTitleHeight - this.rulerHeight, this.svg, [["fill", colors[j]]]); + this.plotBoxWhisker( + { + name : cluster.classes[j].name, + values : cluster.classes[j].values, + minPoint : properties.minPoint, + maxPoint : properties.maxPoint, + x : posX, + y : this.top, + width : properties.classWidth, + height : this.height - this.top - this.bottom - this.clusterTitleHeight - this.rulerHeight + + + } + ); + posX = posX + properties.classWidth; + //SVG.drawRectangle(posX, this.top, this.interClassesSpace, this.height - this.top - this.bottom - this.clusterTitleHeight - this.rulerHeight, this.svg, [["fill", "black"]]); + if (j < cluster.classes.length - 1){ + posX = posX + this.interClassesSpace; + } + } + } +}; + +BoxWhiskerGraph.prototype.draw = function(targetId, data){ + this.targetId = targetId; + var properties = (this.getDimensions(data)); + this.svg = SVG.createSVGCanvas(document.getElementById(this.targetId), [["width", this.width], ["height", this.height]]); + this.plotAxes(properties); + this.plotClusterTitles(properties); + this.plotWhisters(data,properties); +}; + +BoxWhiskerGraph.prototype.input = function(){ + return DATADOC.getBoxWhikerData(); +}; + +BoxWhiskerGraph.prototype.test = function(targetId){ + var plot = new BoxWhiskerGraph( + { + targetId : targetId, + height : 350, + width : 450, + maxBoxWidth : 25 + } + ); + plot.refresh(this.input()); +}; + + + + + -GraphCanvas.prototype.getVertexOpacity = function(vertexId) { - return this.getFormatter().getVertexById(vertexId).getDefault().getOpacity(); -}; + +function DataSet(){ + this.json = null; + +}; + + +DataSet.prototype.loadFromJSON = function(json){ + if(json != null) { + if(this.validate(json)) { + this.json = json; + } + } +}; + + +DataSet.prototype.toJSON = function(json){ + return this.json; +}; + + +/** Abstract method to be override on childs classes **/ +DataSet.prototype.validate = function(json){ + if (true){ + return true; + } + /*else{ + throw "Data validation failed"; + }*/ +}; + + -GraphCanvas.prototype.setVertexFill = function(vertexId, color) { - this.getFormatter().getVertexById(vertexId).getDefault().setFill(color); -}; + +Edge.prototype.getName = GraphItem.prototype.getName; +Edge.prototype.setName = GraphItem.prototype.setName; +Edge.prototype.getId = GraphItem.prototype.getId; + +function Edge(id, name, nodeSource, nodeTarget, args){ + GraphItem.prototype.constructor.call(this, id, name, args); + + this.sourceNode = nodeSource; + this.targetNode = nodeTarget; + +}; + +Edge.prototype.toJSON = function(){ + return {"index": this.id,"sourceIndex":this.sourceNode.getId(),"targetIndex":this.targetNode.getId(),"args":this.args}; +}; + +Edge.prototype.getNodeSource = function(){ + return this.sourceNode; +}; + +Edge.prototype.getNodeTarget = function(){ + return this.targetNode; +}; + +Edge.prototype.remove = function(){ + //Remove edge object in the nodes + this.getNodeSource().removeEdge(this); + this.getNodeTarget().removeEdge(this); + + this.deleted.notify(this); +}; -GraphCanvas.prototype.getVertexFill = function(vertexId) { - return this.getFormatter().getVertexById(vertexId).getDefault().getFill(); -}; + +EdgeGraphFormatter.prototype.setProperties = ItemGraphFormatter.prototype.setProperties; +EdgeGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; +EdgeGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; +EdgeGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; +EdgeGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; +EdgeGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; +EdgeGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; +EdgeGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; +EdgeGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; + +function EdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ + ItemGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); + + this.getDefault().args.type = "EdgeGraphFormatter"; +}; + + + + +LineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; +LineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; +LineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; +LineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; +LineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; +LineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; +LineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; +LineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; +LineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; + +function LineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ + EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); + this.args.type = "LineEdgeGraphFormatter"; +}; + +/** DIRECTED **/ +DirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; +DirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; +DirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; +DirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; +DirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; +DirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; +DirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; +DirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; +DirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; + +function DirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ + EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); + this.args.type = "DirectedLineEdgeGraphFormatter"; + this.args.arrowSize = "3"; +}; +DirectedLineEdgeGraphFormatter.prototype.getArrowSize = function(){ + return this.args.arrowSize; +}; + +OdirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; +OdirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; +OdirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; +OdirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; +OdirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; +OdirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; +OdirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; +OdirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; +OdirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; + +function OdirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ + EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); + this.args.type = "DirectedLineEdgeGraphFormatter"; + this.args.arrowSize = "3"; +}; + +OdirectedLineEdgeGraphFormatter.prototype.getArrowSize = function(){ + return this.args.arrowSize; +}; + + +/** CUT (inhibition) **/ +CutDirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; +CutDirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; +CutDirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; +CutDirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; +CutDirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; +CutDirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; +CutDirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; +CutDirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; +CutDirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; + +function CutDirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ + EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); + this.args.type = "CutDirectedLineEdgeGraphFormatter"; +}; + + + + +BezierEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; +BezierEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; +BezierEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; +BezierEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; +BezierEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; +BezierEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; +BezierEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; +BezierEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; +BezierEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; +BezierEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; + +function BezierEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ + EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); + this.args.type = "BezierEdgeGraphFormatter"; +}; + + + +DotDirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; +DotDirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; +DotDirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; +DotDirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; +DotDirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; +DotDirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; +DotDirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; +DotDirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; +DotDirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; + +function DotDirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ + EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); + this.args.type = "DotDirectedLineEdgeGraphFormatter"; +}; + + +OdotDirectedLineEdgeGraphFormatter.prototype.setProperties = EdgeGraphFormatter.prototype.setProperties; +OdotDirectedLineEdgeGraphFormatter.prototype.getDefault = EdgeGraphFormatter.prototype.getDefault; +OdotDirectedLineEdgeGraphFormatter.prototype.getSelected = EdgeGraphFormatter.prototype.getSelected; +OdotDirectedLineEdgeGraphFormatter.prototype.getOver = EdgeGraphFormatter.prototype.getOver; +OdotDirectedLineEdgeGraphFormatter.prototype.getDragging = EdgeGraphFormatter.prototype.getDragging; +OdotDirectedLineEdgeGraphFormatter.prototype.getId = EdgeGraphFormatter.prototype.getId; +OdotDirectedLineEdgeGraphFormatter.prototype.toJSON = EdgeGraphFormatter.prototype.toJSON; +OdotDirectedLineEdgeGraphFormatter.prototype.loadFromJSON = EdgeGraphFormatter.prototype.loadFromJSON; +OdotDirectedLineEdgeGraphFormatter.prototype._setEvents = EdgeGraphFormatter.prototype._setEvents; + +function OdotDirectedLineEdgeGraphFormatter(id, defaultFormat, selectedFormat, overFormat, dragginFormat){ + EdgeGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, dragginFormat); + this.args.type = "OdotDirectedLineEdgeGraphFormatter"; +}; + + -/** EDGES FORMATTER **/ -GraphCanvas.prototype.setEdgeSize = function(edgeId, value) { - this.getFormatter().getEdgeById(edgeId).getDefault().setSize(value); -}; +function GraphDataset(){ + DataSet.prototype.constructor.call(this); + this.edges = new Object(); + this.vertices = new Object(); + this.verticesIndex = new Object(); + + //Events + this.newVertex = new Event(this); + this.vertexNameChanged = new Event(this); + this.vertexDeleted = new Event(this); + + this.newEdge = new Event(this); + this.edgeNameChanged = new Event(this); + this.edgeDeleted = new Event(this); + + this.json = new Object(); + this.json.vertices = new Array(); + this.json.edges = new Array(); + this.json.relations = new Array(); +}; + +GraphDataset.prototype.loadFromJSON = DataSet.prototype.loadFromJSON; +GraphDataset.prototype.toJSON = DataSet.prototype.toJSON; +GraphDataset.prototype.validate = DataSet.prototype.validate; + +/** Devuelve el numero de edges incidentes sobre el nodo con mas edges **/ +GraphDataset.prototype.getMaxClass = function(){ + var maxClassNode = 0; + for ( var node in this.vertices) { + if (this.vertices[node].getEdgesCount() > maxClassNode){ + maxClassNode = this.vertices[node].getEdgesCount(); + } + } + return maxClassNode; +}; + +/** Devuelve el numero de edges incidentes sobre el nodo con mas edges **/ +GraphDataset.prototype.getMinClass = function(){ + var minClassNode = Math.min(); + for ( var node in this.vertices) { + if (this.vertices[node].getEdgesCount() < minClassNode){ + minClassNode = this.vertices[node].getEdgesCount(); + } + } + return minClassNode; +}; + +GraphDataset.prototype.getVertexByName = function(nodeName){ + var results = new Array(); + + for (var vertexId in this.verticesIndex[nodeName]){ + var vertexByid = this.getVertexById(this.verticesIndex[nodeName][vertexId]); + results.push(vertexByid); + //* añadido nuevo porque fallaba el anterior codigo + return vertexByid + } + + if (results <= 1){ + return this.getVertexById(this.verticesIndex[nodeName]); + } + else{ + return results; + } +}; + +GraphDataset.prototype.getVertexById = function(id){ + return this.vertices[id]; +}; + +GraphDataset.prototype.toSIF = function(){ + var sifDataAdapter = new SifFileDataAdapter(); + return sifDataAdapter.toSIF(this); +}; + +GraphDataset.prototype.toSIFID = function(){ + var sifDataAdapter = new SifFileDataAdapter(); + return sifDataAdapter.toSIFID(this); +}; + +GraphDataset.prototype.toDOT = function(){ + var dotFileDataAdapter = new DotFileDataAdapter(); + return dotFileDataAdapter.toDOT(this); +}; + +GraphDataset.prototype.toDOTID = function(){ + var dotFileDataAdapter = new DotFileDataAdapter(); + return dotFileDataAdapter.toDOTID(this); +}; + +GraphDataset.prototype._addNode = function(nodeName, args){ + return new Vertex(this._getVerticesCount()-1, nodeName, args); +}; + +GraphDataset.prototype.addNode = function(nodeName, args){ + this.json.vertices.push(nodeName); + this._addVerticesIndex(nodeName, this._getVerticesCount() - 1); + var vertex = this._addNode(nodeName, args); + this.vertices[this._getVerticesCount()-1] = vertex; + this._setNodeEvents(vertex); + this.newVertex.notify(vertex); +}; + +GraphDataset.prototype._addVerticesIndex = function(nodeName, id){ + if (this.verticesIndex[nodeName] == null){ + this.verticesIndex[nodeName] = new Array(); + } + this.verticesIndex[nodeName].push(id); +}; + +GraphDataset.prototype.addEdge = function(edgeName, nodeSourceId, nodeTargetId, args){ + this.json.edges.push(edgeName); + var nodeSource = this.getVertexById(nodeSourceId); + var nodeTarget = this.getVertexById(nodeTargetId); + var index = this.getEdgesCount() - 1; + this.edges[index] = new Edge(index, edgeName, nodeSource, nodeTarget, args); + this.json.relations.push({"index": index, "sourceIndex": nodeSourceId, "targetIndex": nodeTargetId, "args": args }); + + nodeSource.addEdge(this.edges[index]); + nodeTarget.addEdge(this.edges[index]); + this._setEdgeEvents(this.edges[index]); + this.newEdge.notify(this.edges[index]); +}; + +GraphDataset.prototype.getVertices = function(){ + return this.vertices; +}; + +GraphDataset.prototype.getEdges = function(){ + return this.edges; +}; + +GraphDataset.prototype.getEdgeById = function(edgeId){ + return this.edges[edgeId]; +}; + +GraphDataset.prototype._getVerticesCount = function(){ + return this.json.vertices.length; +}; + + +GraphDataset.prototype.getVerticesCount = function(){ + var count = 0; + for ( var vertex in this.getVertices()) { + count ++; + } + return count; +}; + + +GraphDataset.prototype.getEdgesCount = function(){ + return this.json.edges.length; +}; + +GraphDataset.prototype.init = function(){ + this.edges = new Object(); + this.vertices = new Object(); +}; + +GraphDataset.prototype._setNodeEvents = function(node){ + var _this = this; + //NODE EVENTS + node.deleted.attach(function (sender, node){ + _this._removeNode(node); + }); + + node.nameChanged.attach(function (sender, args){ + var item = args.item; + var newName = item.name; + var indexes = _this.verticesIndex[args.previousName]; + for(var i = 0; i < indexes.length; i++){ + if(indexes[i] == item.id) + indexes.splice(i,1); + } + if(indexes.length == 0){ + delete _this.verticesIndex[args.previousName]; + } + _this._addVerticesIndex(newName, item.id); + _this.json.vertices[item.id] = newName; + _this.vertexNameChanged.notify(args); + }); +}; + +GraphDataset.prototype._setEdgeEvents = function(edge){ + var _this = this; + //EDGE EVENTS + edge.nameChanged.attach(function (sender, edge){ + _this.edgeNameChanged.notify(edge); + + }); + + edge.deleted.attach(function (sender, edge){ + _this._removeEdge(edge); + }); +}; + +GraphDataset.prototype._connectVerticesByName = function(nodeNameSource, nodeNameTarget){ + var source = this.getVertexByName(nodeNameSource); + var target = this.getVertexByName(nodeNameTarget); + + if ((source != null)&&(target!=null)){ + this.addEdge(source.getName() +"_" + target.getName(), source.getId(), target.getId(), {}); + } + else{ + if (source == null){ + console.log("No encontrado: " + nodeNameSource) + } + if (target == null){ + console.log("No encontrado: " + nodeNameTarget) + } + } +}; + +GraphDataset.prototype.loadFromJSON = function(json){ + var json = json; + this.init(); + this.json = new Object(); + this.json.vertices = new Array(); + this.json.edges = new Array(); + this.json.relations = new Array(); + + for ( var i = 0; i < json.nodes.length; i++) { + if (json.nodes[i] != null){ + var name = json.nodes[i]; + this.addNode(name); + } + else{ + this.json.vertices.push(null); + } + } + + for ( var i = 0; i < json.edges.length; i++) { + if (json.edges[i] != null){ + if (json.relations[i] != null){ + var name = json.edges[i]; + this.addEdge(name, json.relations[i].sourceIndex, json.relations[i].targetIndex, json.relations[i].args); + } + } + else{ + this.json.edges.push(null); + this.json.relations.push(null); + } + } +}; + +GraphDataset.prototype.prettyPrint = function(){ + for ( var node in this.vertices) { + console.log(this.vertices[node].getName() ); + for ( var j = 0; j < this.vertices[node].getEdgesIn().length; j++) { + console.log(" --> " + this.vertices[node].getEdgesIn()[j].getNodeTarget().getName() ); + } + } +}; + +GraphDataset.prototype._removeEdge = function(edge){ + this.json.edges[edge.getId()] = null; + this.json.relations[edge.getId()] = null; + + delete this.edges[edge.getId()]; + this.edgeDeleted.notify(edge); + + +}; + +GraphDataset.prototype._removeNode = function(node){ + this.json.vertices[node.getId()] = null; + delete this.vertices[node.getId()]; + this.vertexDeleted.notify(node); +}; + +GraphDataset.prototype.toJSON = function(){ + var json = new Object(); + var nodes = new Array(); + json.nodes = this.json.vertices; //nodes; + json.edges = this.json.edges; //edges; + json.relations = this.json.relations; + return json; +}; + +GraphDataset.prototype.clone = function(){ + var dsDataset = new GraphDataset(); + dsDataset.loadFromJSON(this.toJSON()); + return dsDataset; +}; +//GraphDataset.prototype.test = function(){ +// this.loadFromJSON(this.toJSON()); +//}; + +function labels(){ + var names = new Array(); + + var dataset = interactomeViewer.graphEditorWidget.dataset; + var layout = interactomeViewer.graphEditorWidget.layout; + + for ( var vertexId in interactomeViewer.graphEditorWidget.dataset.getVertices()) { + names.push(interactomeViewer.graphEditorWidget.dataset.getVertexById(vertexId).getName()); + } + + var sorted = (names.sort()); + console.log(sorted) + var distance = 0.01; + var altura = 0.6; + for ( var i = 0; i < names.length; i++) { + var id =dataset.getVertexByName(names[i]).getId(); + + layout.getNodeById(id).setCoordenates(distance, altura); + + + distance = parseFloat(distance) + parseFloat(0.03); + + altura = parseFloat(altura) + parseFloat(0.02); + + if (parseFloat(altura) == 0.9800000000000003){ + + altura = 0.6; + distance = distance - 0.51; + } + + } + + +}; -GraphCanvas.prototype.getEdgeSize = function(edgeId) { - return this.getFormatter().getEdgeById(edgeId).getDefault().getSize(); -}; +function GraphItem(id, name, args){ + this.id = id; + this.name = name; + this.type = "NONE"; + + this.args = new Object(); + + + if (args!=null){ + this.args = args; + if (args.type !=null){ + this.type = args.type; + } + } + + //Events + this.nameChanged = new Event(this); + this.deleted = new Event(this); +} + +GraphItem.prototype.getName = function(){ + return this.name; +}; + +GraphItem.prototype.getId = function(){ + return this.id; +}; + +GraphItem.prototype.setName = function(name){ + var oldName = this.getName(); + this.name = name; + this.nameChanged.notify({"item": this, "previousName" : oldName}); +}; + + + + -GraphCanvas.prototype.setEdgeStroke = function(edgeId, value) { - this.getFormatter().getEdgeById(edgeId).getDefault().setStroke(value); -}; +function LayoutDataset(){ + this.dataset = null; + this.vertices = new Object(); + this.changed = new Event(this); + + + this.args = new Object(); + + //RANDOM, CIRCLE + this.args.type = "CIRCLE"; +}; + +LayoutDataset.prototype.loadFromJSON = function(dataset, json){ + var _this = this; + this.vertices = new Object(); + this.dataset = dataset; //new GraphDataset(); + for ( var vertex in json) { + this.vertices[vertex] = new NodeLayout(vertex, json[vertex].x, json[vertex].y); + this.vertices[vertex].changed.attach(function (sender, item){ + _this.changed.notify(item); + }); + } + this._attachDatasetEvents(); +}; + + +LayoutDataset.prototype.toJSON = function(){ + var serialize = new Object(); + for ( var vertex in this.vertices) { + serialize[vertex] = new Object(); + serialize[vertex].x = this.vertices[vertex].x; + serialize[vertex].y = this.vertices[vertex].y; + } + serialize.dataset = new Object(); + serialize.dataset =this.dataset.toJSON(); + return serialize; +}; + +LayoutDataset.prototype.dataBind = function(graphDataset){ + this.dataset = graphDataset; + this._attachDatasetEvents(); + this._calculateLayout(); +}; + +LayoutDataset.prototype._removeVertex = function(vertexId){ + delete this.vertices[vertexId]; +}; + +LayoutDataset.prototype._attachDatasetEvents = function(){ + var _this = this; + + this.dataset.vertexDeleted.attach(function (sender, item){ + _this._removeVertex(item.getId()); + }); + + this.dataset.newVertex.attach(function (sender, item){ + _this.vertices[item.getId()] = new NodeLayout(item.getId(), 0.5, 0.5); + _this.vertices[item.getId()].changed.attach(function (sender, item){ + _this.changed.notify(item); + }); + }); +}; + +LayoutDataset.prototype.getType = function(){ + return this.args.type; +}; + +LayoutDataset.prototype._calculateLayoutVertices = function(type, count){ + + if (type == "CIRCLE"){ + var radius = 0.4; + var centerX = 0.5; + var centerY = 0.5; + var verticesCoordinates = new Array(); + for(var i = 0; i < count; i++){ + x = centerX + radius * Math.sin(i * 2 * Math.PI/count); + y = centerY + radius * Math.cos(i * 2 * Math.PI/count); + verticesCoordinates.push({'x':x,'y':y}); + } + return verticesCoordinates; + } +}; + + +LayoutDataset.prototype._calculateLayout = function(){ + var _this = this; + if (this.getType() == "RANDOM"){ + for ( var vertex in this.dataset.getVertices()) { + if (this.vertices[vertex] == null){ + this.vertices[vertex] = new NodeLayout(vertex, 0, 0); + } + this.vertices[vertex].setCoordinates(Math.random(), Math.random()); + this.vertices[vertex].changed.attach(function (sender, item){ + _this.changed.notify(item); + }); + } + } + + if ( this.getType() == "CIRCLE"){ + + var count = this.dataset._getVerticesCount(); + var verticesCoordinates = this._calculateLayoutVertices(this.getType(), count); + + var aux = 0; + for ( var vertex in this.dataset.getVertices()) { + if (this.vertices[vertex] == null){ + this.vertices[vertex] = new NodeLayout(vertex, 0, 0); + } + this.vertices[vertex].setCoordinates(verticesCoordinates[aux].x, verticesCoordinates[aux].y);//{"x":, "y":}; + aux++; + this.vertices[vertex].changed.attach(function (sender, item){ + _this.changed.notify(item); + }); + } + } + + + if (this.getType() == "SQUARE"){ + + var count = this.dataset._getVerticesCount(); + var xMin = 0.1; + var xMax = 0.9; + var yMin = 0.1; + var yMax = 0.9; + + var rows = Math.sqrt(count); + var step = (xMax - xMin) / rows; + + var verticesCoordinates = new Array(); + for(var i = 0; i < rows; i ++){ + for ( var j = 0; j < rows; j++) { + x = i * step + xMin; + y = j * step + yMin; + verticesCoordinates.push({'x':x,'y':y}); + } + } + + var aux = 0; + for ( var vertex in this.dataset.getVertices()) { + if (this.vertices[vertex] == null){ + this.vertices[vertex] = new NodeLayout(vertex, 0, 0); + } + this.vertices[vertex].setCoordinates(verticesCoordinates[aux].x, verticesCoordinates[aux].y);//{"x":, "y":}; + aux++; + this.vertices[vertex].changed.attach(function (sender, item){ + _this.changed.notify(item); + }); + } + } + +}; + +LayoutDataset.prototype.getNodeById = function(id){ + return this.vertices[id]; +}; + +LayoutDataset.prototype.getVerticesByArea = function(x1, y1, x2, y2){ + var vertices = new Array(); + for ( var vertex in this.dataset.getVertices()) { + if ((this.vertices[vertex].x >= x1)&&(this.vertices[vertex].x <= x2)){ + if ((this.vertices[vertex].y >= y1)&&(this.vertices[vertex].y <= y2)){ + vertices.push(this.vertices[vertex]); + } + } + } + return vertices; +}; + + + + +LayoutDataset.prototype.getLayout = function(type){ + + if (type == "CIRCLE"){ + this.args.type = "CIRCLE"; + this._calculateLayout(); + return; + } + + if (type == "SQUARE"){ + this.args.type = "SQUARE"; + this._calculateLayout(); + return; + } + + if (type == "RANDOM"){ + this.args.type = "RANDOM"; + this._calculateLayout(); + return; + } + + + var dotText = this.dataset.toDOTID(); + var url = "http://bioinfo.cipf.es/utils/ws/rest/network/layout/"+type+".coords"; + var _this = this; + + $.ajax({ + async: true, + type: "POST", + url: url, + dataType: "text", + data: { + dot :dotText + }, + cache: false, + success: function(data){ + var response = JSON.parse(data); + for ( var vertexId in response) { + _this.vertices[vertexId].setCoordinates(response[vertexId].x, response[vertexId].y); + } + } + }); + +// $.ajax({ +// async: true, +// type: "POST", +// url: url, +// dataType: "script", +// data: { +// dot :dotText +// }, +// cache: false, +// success: function(data){ +// var response = JSON.parse(data); +// for ( var vertexId in response) { +// _this.vertices[vertexId].setCoordinates(response[vertexId].x, response[vertexId].y); +// } +// } +// }); + +}; + +function NodeLayout(id, x, y, args){ + this.id = id; + this.x = x; + this.y = y; + this.changed = new Event(this); +}; + +NodeLayout.prototype.getId = function(id){ + return this.id; +}; + +NodeLayout.prototype.setCoordinates = function(x, y){ + this.x = x; + this.y = y; + this.changed.notify(this); +}; + -GraphCanvas.prototype.getEdgeStroke = function(edgeId) { - return this.getFormatter().getEdgeById(edgeId).getDefault().getStroke(); -}; + +function NetworkDataSetFormatter(vertexFormatProperties, defaultEdgeProperties, args){ + DataSet.prototype.constructor.call(this); + + this.args = new Object(); + + this.vertices = new Object(); + this.edges = new Object(); + this.dataset = null; + this.maxClass = 0; + this.minClass = 0; + + /** Coordenates with default Setting */ + this.args.width = 1100; + this.args.height = 500; + + /** Optional parameters */ + this.args.backgroundColor = "#FFFFFF"; + this.args.backgroundImage = null; + this.args.backgroundImageHeight = null; + this.args.backgroundImageWidth = null; + this.args.backgroundImageX = null; + this.args.backgroundImageY = null; + + + this.args.balanceNodes = false; + this.args.nodesMaxSize = 3; + this.args.nodesMinSize = 0.5; + + + /** Zoom **/ + this.args.zoomScale = 1; + this.args.zoomScaleStepFactor = 0.4; + + if (args != null){ + if (args.backgroundImage != null){ + this.args.backgroundImage = args.backgroundImage; + } + + if (args.width != null){ + this.args.width = args.width; + } + + if (args.height != null){ + this.args.height = args.height; + this.args.svgHeight = args.height; + } + + if (args.svgHeight != null){ + this.args.svgHeight = args.svgHeight; + } + + if (args.backgroundColor != null){ + this.args.backgroundColor = args.backgroundColor; + } + + if(args.balanceNodes != null){ + this.args.balanceNodes = args.balanceNodes; + } + + if(args.nodesMaxSize != null){ + this.args.nodesMaxSize = args.nodesMaxSize; + } + if(args.nodesMinSize != null){ + this.args.nodesMinSize = args.nodesMinSize; + } + } + + this.args.defaultEdgeProperties = {"fill":"#000000", "radius":"1", "stroke":"#000000", "size":1, "title":{"fontSize":10, "fontColor":"#000000"}}; + this.args.vertexFormatProperties = { "fill":"#000000", "stroke":"#000000", "stroke-opacity":"#000000"}; + + if (vertexFormatProperties!= null){ + this.args.vertexFormatProperties = vertexFormatProperties; + } + if (defaultEdgeProperties!= null){ + this.args.defaultEdgeProperties = defaultEdgeProperties; + } + + /** Events **/ + this.changed = new Event(this); + this.edgeChanged = new Event(this); + this.resized = new Event(this); + this.backgroundImageChanged= new Event(this); + this.backgroundColorChanged= new Event(this); +}; + +NetworkDataSetFormatter.prototype.loadFromJSON = function(dataset, json){ + this.args = new Object(); + this.vertices = new Object(); + this.args = json; + this._setDataset(dataset); + var _this = this; + + for ( var vertex in json.vertices) { + this.addVertex(vertex, json.vertices[vertex]); + } + + for ( var edgeId in json.edges) { + this.addEdge(edgeId, json.edges[edgeId]); + } +}; + + +NetworkDataSetFormatter.prototype.toJSON = function(){ + + +// this.args.vertices = new Object(); +// this.args.edges = new Object(); +// +// for ( var vertex in this.vertices) { +// this.args.vertices[vertex] = this.getVertexById(vertex).toJSON(); +// } +// for ( var edge in this.edges) { +// this.args.edges[edge] = this.getEdgeById(edge).toJSON(); +// } +// +// return (this.args); + + + var serialize = new Object(); + serialize = JSON.parse(JSON.stringify(this.args)); + serialize.vertices = new Object(); + serialize.edges = new Object(); + + for ( var vertex in this.vertices) { + serialize.vertices[vertex] = this.getVertexById(vertex).toJSON(); + } + for ( var edge in this.edges) { + serialize.edges[edge] = this.getEdgeById(edge).toJSON(); + } + + return (serialize); +}; + + + +NetworkDataSetFormatter.prototype._getNodeSize = function(nodeId){ + if (this.isVerticesBalanced()){ + var total = this.maxClass - this.minClass; + if (total == 0){ total = 1;} + var nodeConnection = this.dataset.getVertexById(nodeId).getEdges().length; + return ((nodeConnection*this.args.nodesMaxSize)/total) + this.args.nodesMinSize; + } + return this.getVertexById(nodeId).getDefault().getSize(); +}; + +NetworkDataSetFormatter.prototype._recalculateSize = function(){ + if (this.isVerticesBalanced()){ + this.maxClass = this.dataset.getMaxClass(); + this.minClass = this.dataset.getMinClass(); + for ( var vertexIdAll in this.vertices) { + var size = this._getNodeSize(vertexIdAll); + this.vertices[vertexIdAll].getDefault().setSize(size); + this.vertices[vertexIdAll].getSelected().setSize(size); + this.vertices[vertexIdAll].getOver().setSize(size); + } + } +}; + + +NetworkDataSetFormatter.prototype.addVertex = function(vertexId, json){ + + + if (json == null){ + this.vertices[vertexId] = new CircleVertexGraphFormatter(vertexId, this.args.vertexFormatProperties.defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); + } + else{ + + /** Cargo los attributos desde el json **/ + if (json.type == null){ + this.vertices[vertexId] = new CircleVertexGraphFormatter(vertexId, this.args.vertexFormatProperties.defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); + } + + if ((json.type == "SquareVertexGraphFormatter")||(json.type == "SquareVertexNetworkFormatter")){ + this.vertices[vertexId] = new SquareVertexGraphFormatter(vertexId); + this.vertices[vertexId].loadFromJSON(json); + } + + if ((json.type == "CircleVertexGraphFormatter")||(json.type == "CircleVertexNetworkFormatter")){ + this.vertices[vertexId] = new CircleVertexGraphFormatter(vertexId); + this.vertices[vertexId].loadFromJSON(json); + } + + if ((json.type == "EllipseVertexGraphFormatter")||(json.type == "EllipseVertexNetworkFormatter")){ + this.vertices[vertexId] = new EllipseVertexGraphFormatter(vertexId); + this.vertices[vertexId].loadFromJSON(json); + } + + if ((json.type == "RectangleVertexGraphFormatter")||(json.type == "RectangleVertexNetworkFormatter")){ + this.vertices[vertexId] = new RectangleVertexGraphFormatter(vertexId); + this.vertices[vertexId].loadFromJSON(json); + } + + if ((json.type == "RoundedVertexGraphFormatter")||(json.type == "RoundedVertexNetworkFormatter")){ + this.vertices[vertexId] = new RoundedVertexGraphFormatter(vertexId); + this.vertices[vertexId].loadFromJSON(json); + } + + } + + + var _this = this; + this.vertices[vertexId].stateChanged.attach(function (sender, item){ + _this.changed.notify(item); + }); + + var size = this._getNodeSize(vertexId); + this.vertices[vertexId].defaultFormat.args.size = size; + this.vertices[vertexId].selected.args.size = size; + this.vertices[vertexId].over.args.size = size; + +}; + +NetworkDataSetFormatter.prototype.addEdge = function(edgeId, json){ + + /** Es un edge nuevo que le doy los atributos por defecto **/ + if (json == null){ + if (this.dataset.getEdgeById(edgeId).getNodeSource().getId() == this.dataset.getEdgeById(edgeId).getNodeTarget().getId()){ + this.edges[edgeId] = new BezierEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + }else{ + this.edges[edgeId] = new DirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + } + } + else{ + /** Cargo los attributos desde el json **/ + if (json.type == null){ + this.edges[edgeId] = new LineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + } + + if ((json.type == "LineEdgeGraphFormatter")||(json.type == "LineEdgeNetworkFormatter")){ + this.edges[edgeId] = new LineEdgeGraphFormatter(edgeId); + this.edges[edgeId].loadFromJSON(json); + } + if ((json.type == "DirectedLineEdgeGraphFormatter")||(json.type == "DirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new DirectedLineEdgeGraphFormatter(edgeId); + this.edges[edgeId].loadFromJSON(json); + } + + if ((json.type == "BezierEdgeGraphFormatter")||(json.type == "BezierEdgeNetworkFormatter")){ + this.edges[edgeId] = new BezierEdgeGraphFormatter(edgeId); + this.edges[edgeId].loadFromJSON(json); + } + + + if ((json.type == "CutDirectedLineEdgeGraphFormatter")||(json.type == "CutDirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new CutDirectedLineEdgeGraphFormatter(edgeId); + this.edges[edgeId].loadFromJSON(json); + } + + if ((json.type == "DotDirectedLineEdgeGraphFormatter")||(json.type == "DotDirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new DotDirectedLineEdgeGraphFormatter(edgeId); + this.edges[edgeId].loadFromJSON(json); + } + if ((json.type == "OdotDirectedLineEdgeGraphFormatter")||(json.type == "OdotDirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new OdotDirectedLineEdgeGraphFormatter(edgeId); + this.edges[edgeId].loadFromJSON(json); + } + + if ((json.type == "OdirectedLineEdgeGraphFormatter")||(json.type == "OdirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new OdirectedLineEdgeGraphFormatter(edgeId); + this.edges[edgeId].loadFromJSON(json); + } + } + + var _this = this; + this.edges[edgeId].stateChanged.attach(function (sender, item){ + _this.edgeChanged.notify(item); + }); + + this._recalculateSize(); +}; + +NetworkDataSetFormatter.prototype._setDataset = function(dataset){ + this.dataset = dataset; + this.maxClass = dataset.getMaxClass(); + this.minClass = dataset.getMinClass(); + this._attachDatasetEvents(); +}; + +NetworkDataSetFormatter.prototype.changeEdgeType = function(edgeId, type){ + if ((type == "LineEdgeGraphFormatter")||(type == "LineEdgeNetworkFormatter")){ + this.edges[edgeId] = new LineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + + } + if ((type == "DirectedLineEdgeGraphFormatter")||(type == "DirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new DirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + } + + if ((type == "CutDirectedLineEdgeGraphFormatter")||(type == "CutDirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new CutDirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + } + + if ((type == "DotDirectedLineEdgeGraphFormatter")||(type == "DotDirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new DotDirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + } + + if ((type == "OdotDirectedLineEdgeGraphFormatter")||(type == "OdotDirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new OdotDirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + } + + if ((type == "OdirectedLineEdgeGraphFormatter")||(type == "OdirectedLineEdgeNetworkFormatter")){ + this.edges[edgeId] = new OdirectedLineEdgeGraphFormatter(edgeId, this.args.defaultEdgeProperties.defaultFormat, this.args.defaultEdgeProperties.selected, this.args.defaultEdgeProperties.over, this.args.defaultEdgeProperties.dragging); + } + + + + var _this = this; + this.edges[edgeId].stateChanged.attach(function (sender, item){ + _this.edgeChanged.notify(item); + }); + _this.edgeChanged.notify(this.edges[edgeId]); +}; +/* +classe = "SquareNetworkNodeFormatter"; +} +if (value == "circle"){ + classe = "CircleNetworkNodeFormatter"; + **/ +NetworkDataSetFormatter.prototype.changeNodeType = function(vertexId, type){ + var defaultFormat = JSON.parse(JSON.stringify(this.vertices[vertexId].getDefault())); + var selectedFormat = JSON.parse(JSON.stringify(this.vertices[vertexId].getSelected())); + var defaultFormat = JSON.parse(JSON.stringify(this.vertices[vertexId].getDefault())); + var defaultFormat = JSON.parse(JSON.stringify(this.vertices[vertexId].getDefault())); + + if ((type == "SquareVertexGraphFormatter")||(type == "SquareVertexNetworkFormatter")){ + this.vertices[vertexId] = new SquareVertexGraphFormatter(vertexId,defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); + } + + if ((type == "CircleVertexGraphFormatter")||(type == "CircleVertexNetworkFormatter")){ + this.vertices[vertexId] = new CircleVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); + } + + if ((type == "EllipseVertexGraphFormatter")||(type == "EllipseVertexNetworkFormatter")){ + this.vertices[vertexId] = new EllipseVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); + } + + if ((type == "RectangleVertexGraphFormatter")||(type == "RectangleVertexNetworkFormatter")){ + this.vertices[vertexId] = new RectangleVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); + } + + if ((type == "RoundedVertexGraphFormatter")||(type == "RoundedVertexNetworkFormatter")){ + this.vertices[vertexId] = new RoundedVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); + } + + if ((type == "OctagonVertexGraphFormatter")||(type == "OctagonVertexNetworkhFormatter")){ + this.vertices[vertexId] = new OctagonVertexGraphFormatter(vertexId, defaultFormat, this.args.vertexFormatProperties.selected, this.args.vertexFormatProperties.over, this.args.vertexFormatProperties.dragging); + } + + + var _this = this; + this.vertices[vertexId].stateChanged.attach(function (sender, item){ + _this.changed.notify(item); + }); + _this.changed.notify(this.vertices[vertexId]); +}; + + + +NetworkDataSetFormatter.prototype.dataBind = function(networkDataSet){ + var _this = this; + this._setDataset(networkDataSet); + + for ( var vertex in this.dataset.getVertices()) { + this.addVertex(vertex); + } + + for ( var edge in this.dataset.getEdges()) { + this.addEdge(edge); + } +}; + +NetworkDataSetFormatter.prototype._removeEdge = function(edgeId){ + delete this.edges[edgeId]; +}; + +NetworkDataSetFormatter.prototype._removeVertex = function(vertexId){ + delete this.vertices[vertexId]; +}; + +NetworkDataSetFormatter.prototype._attachDatasetEvents = function(id){ + var _this = this; + this.dataset.vertexDeleted.attach(function (sender, item){ + _this._removeVertex(item.getId()); + }); + + this.dataset.edgeDeleted.attach(function (sender, item){ + _this._removeEdge(item.getId()); + }); + + this.dataset.newVertex.attach(function (sender, item){ + _this.addVertex(item.getId()); + }); + + this.dataset.newEdge.attach(function (sender, item){ + _this.addEdge(item.getId()); + }); +}; + + +NetworkDataSetFormatter.prototype.getVertexById = function(id){ + return this.vertices[id]; +}; + +NetworkDataSetFormatter.prototype.getEdgeById = function(id){ + return this.edges[id]; +}; + +NetworkDataSetFormatter.prototype.makeLabelsBigger = function(){ +for ( var vertexId in this.vertices) { + var fontSize = this.vertices[vertexId].getDefault().getFontSize() + 2; + this.vertices[vertexId].getDefault().setFontSize(fontSize); + } +}; + +NetworkDataSetFormatter.prototype.makeLabelsSmaller = function(){ + for ( var vertexId in this.vertices) { + var fontSize = this.vertices[vertexId].getDefault().getFontSize() - 2; + this.vertices[vertexId].getDefault().setFontSize(fontSize); + } +}; + + +NetworkDataSetFormatter.prototype.resize = function(width, height){ + this.args.width = width; + this.args.height = height; + this.resized.notify(); +}; + +/** ZOOM GETTERS **/ +NetworkDataSetFormatter.prototype.getZoomScaleStepFactor = function(){return this.args.zoomScaleStepFactor;}; +NetworkDataSetFormatter.prototype.setZoomScaleStepFactor = function(scaleFactor){this.args.zoomScaleStepFactor = scaleFactor;}; +NetworkDataSetFormatter.prototype.getZoomScale = function(){return this.args.zoomScale;}; +NetworkDataSetFormatter.prototype.setZoomScale = function(scale){this.args.zoomScale = scale;}; + +NetworkDataSetFormatter.prototype.getNodesMaxSize = function(){return this.args.nodesMaxSize;}; +NetworkDataSetFormatter.prototype.getNodesMinSize = function(){return this.args.nodesMinSize;}; + +/** SIZE SETTERS AND GETTERS **/ +NetworkDataSetFormatter.prototype.isVerticesBalanced = function(){return this.args.balanceNodes;}; +NetworkDataSetFormatter.prototype.getWidth = function(){return this.args.width;}; +NetworkDataSetFormatter.prototype.getHeight = function(){return this.args.height;}; + +/** OPTIONAL PARAMETERS GETTERS AND SETTERS **/ +NetworkDataSetFormatter.prototype.getBackgroundImage = function(){return this.args.backgroundImage;}; +NetworkDataSetFormatter.prototype.setBackgroundImage = function(value){this.args.backgroundImage = value; this.backgroundImageChanged.notify(this);}; + + +NetworkDataSetFormatter.prototype.getBackgroundImageWidth = function(){return this.args.backgroundImageWidth;}; +NetworkDataSetFormatter.prototype.setBackgroundImageWidth = function(value){this.args.backgroundImageWidth = value; this.backgroundImageChanged.notify(this);}; + +NetworkDataSetFormatter.prototype.getBackgroundImageHeight = function(){return this.args.backgroundImageHeight;}; +NetworkDataSetFormatter.prototype.setBackgroundImageHeight = function(value){this.args.backgroundImageHeight = value; this.backgroundImageChanged.notify(this);}; + +NetworkDataSetFormatter.prototype.getBackgroundImageX = function(){return this.args.backgroundImageX;}; +NetworkDataSetFormatter.prototype.setBackgroundImageX = function(value){this.args.backgroundImageX = value; this.backgroundImageChanged.notify(this);}; + +NetworkDataSetFormatter.prototype.getBackgroundImageY = function(){return this.args.backgroundImageX;}; +NetworkDataSetFormatter.prototype.setBackgroundImageY = function(value){this.args.backgroundImageY = value; this.backgroundImageChanged.notify(this);}; + + + +NetworkDataSetFormatter.prototype.getBackgroundColor = function(){return this.args.backgroundColor;}; +NetworkDataSetFormatter.prototype.setBackgroundColor = function(value){this.args.backgroundColor = value; this.backgroundColorChanged.notify(this);}; + +NetworkDataSetFormatter.prototype.getWidth = function(){return this.args.width;}; +NetworkDataSetFormatter.prototype.setWidth = function(value){this.args.width = value;}; + +NetworkDataSetFormatter.prototype.getHeight = function(){return this.args.height;}; +NetworkDataSetFormatter.prototype.setHeight = function(value){this.args.height = value;}; + + -GraphCanvas.prototype.setEdgeStrokeOpacity = function(edgeId, value) { - this.getFormatter().getEdgeById(edgeId).getDefault().setStrokeOpacity(value); -}; + +Vertex.prototype.getName = GraphItem.prototype.getName; +Vertex.prototype.setName = GraphItem.prototype.setName; +Vertex.prototype.getId = GraphItem.prototype.getId; + +function Vertex(id, name, args){ + GraphItem.prototype.constructor.call(this, id, name, args); + this.edgesIn= new Array(); + this.edgesOut= new Array(); +}; + +Vertex.prototype.getEdges = function(){ + return this.edgesIn.concat(this.edgesOut); +}; + +Vertex.prototype.getEdgesCount = function(){ + return this.getEdges().length; +}; + +Vertex.prototype.getEdgesIn = function(){ + return this.edgesIn; +}; + +Vertex.prototype.getEdgesOut = function(){ + return this.edgesOut; +}; + +Vertex.prototype.addEdge = function(edge){ + if (edge.getNodeSource().getId() == this.id){ + this.edgesIn.push(edge); + } + else{ + this.edgesOut.push(edge); + } +}; + +Vertex.prototype.removeEdge = function(edge){ + for ( var i = 0; i < this.getEdgesIn().length; i++) { + var edgeIn = this.edgesIn[i]; + if (edgeIn.getId() == edge.getId()){ + this.edgesIn.splice(i, 1); + } + } + for ( var i = 0; i < this.getEdgesOut().length; i++) { + var edgeIn = this.edgesOut[i]; + if (edgeIn.getId() == edge.getId()){ + this.edgesOut.splice(i, 1); + } + } +}; + +Vertex.prototype.remove = function(){ + var edges = this.getEdges(); + for ( var i = 0; i < edges.length; i++) { + var edge = edges[i]; + edge.remove(); + } + this.deleted.notify(this); +}; + + + + -GraphCanvas.prototype.getEdgeStrokeOpacity = function(edgeId) { - return this.getFormatter().getEdgeById(edgeId).getDefault().getStrokeOpacity(); -}; +VertexGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; +VertexGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; +VertexGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; +VertexGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; +VertexGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; +VertexGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; +VertexGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; +VertexGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; + + +function VertexGraphFormatter(defaultFormat, selectedFormat, overFormat, draggingFormat){ + ItemGraphFormatter.prototype.constructor.call(this, defaultFormat, selectedFormat, overFormat, draggingFormat); +}; + + +CircleVertexGraphFormatter.prototype.getDefault = VertexGraphFormatter.prototype.getDefault; +CircleVertexGraphFormatter.prototype.getSelected = VertexGraphFormatter.prototype.getSelected; +CircleVertexGraphFormatter.prototype.getOver = VertexGraphFormatter.prototype.getOver; +CircleVertexGraphFormatter.prototype.getDragging = VertexGraphFormatter.prototype.getDragging; +CircleVertexGraphFormatter.prototype.getId = VertexGraphFormatter.prototype.getId; +CircleVertexGraphFormatter.prototype.toJSON = VertexGraphFormatter.prototype.toJSON; +CircleVertexGraphFormatter.prototype.loadFromJSON = VertexGraphFormatter.prototype.loadFromJSON; +CircleVertexGraphFormatter.prototype._setEvents = VertexGraphFormatter.prototype._setEvents; + +function CircleVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ + VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); + this.args.type = "CircleVertexGraphFormatter"; + if (defaultFormat != null){ + if (defaultFormat.radius != null){ + this.defaultFormat.args.radius = defaultFormat.radius; + } + } + + if (selectedFormat != null){ + if (selectedFormat.radius != null){ + this.selected.args.radius = selectedFormat.radius; + } + } + + if (overFormat != null){ + if (overFormat.radius != null){ + this.over.args.radius = overFormat.radius; + } + } + + if (draggingFormat != null){ + if (draggingFormat.radius != null){ + this.dragging.args.draggingFormat = draggingFormat.radius; + } + } +}; + + + +SquareVertexGraphFormatter.prototype.getDefault = VertexGraphFormatter.prototype.getDefault; +SquareVertexGraphFormatter.prototype.getSelected = VertexGraphFormatter.prototype.getSelected; +SquareVertexGraphFormatter.prototype.getOver = VertexGraphFormatter.prototype.getOver; +SquareVertexGraphFormatter.prototype.getDragging = VertexGraphFormatter.prototype.getDragging; +SquareVertexGraphFormatter.prototype.getId = VertexGraphFormatter.prototype.getId; +SquareVertexGraphFormatter.prototype.toJSON = VertexGraphFormatter.prototype.toJSON; +SquareVertexGraphFormatter.prototype.loadFromJSON = VertexGraphFormatter.prototype.loadFromJSON; +SquareVertexGraphFormatter.prototype._setEvents = VertexGraphFormatter.prototype._setEvents; + +function SquareVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ + VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); + this.args.type = "SquareVertexGraphFormatter"; + if (defaultFormat != null){ + if (defaultFormat.radius != null){ + this.defaultFormat.args.radius = defaultFormat.radius; + } + } + + if (selectedFormat != null){ + if (selectedFormat.radius != null){ + this.selected.args.radius = selectedFormat.radius; + } + } + + if (overFormat != null){ + if (overFormat.radius != null){ + this.over.args.radius = overFormat.radius; + } + } + + if (draggingFormat != null){ + if (draggingFormat.radius != null){ + this.dragging.args.draggingFormat = draggingFormat.radius; + } + } +}; + + +EllipseVertexGraphFormatter.prototype.getDefault = VertexGraphFormatter.prototype.getDefault; +EllipseVertexGraphFormatter.prototype.getSelected = VertexGraphFormatter.prototype.getSelected; +EllipseVertexGraphFormatter.prototype.getOver = VertexGraphFormatter.prototype.getOver; +EllipseVertexGraphFormatter.prototype.getDragging = VertexGraphFormatter.prototype.getDragging; +EllipseVertexGraphFormatter.prototype.getId = VertexGraphFormatter.prototype.getId; +EllipseVertexGraphFormatter.prototype.toJSON = VertexGraphFormatter.prototype.toJSON; +EllipseVertexGraphFormatter.prototype.loadFromJSON = VertexGraphFormatter.prototype.loadFromJSON; +EllipseVertexGraphFormatter.prototype._setEvents = VertexGraphFormatter.prototype._setEvents; + +function EllipseVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ + VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); + this.args.type = "EllipseVertexGraphFormatter"; + if (defaultFormat != null){ + if (defaultFormat.radius != null){ + this.defaultFormat.args.radius = defaultFormat.radius; + } + } + + if (selectedFormat != null){ + if (selectedFormat.radius != null){ + this.selected.args.radius = selectedFormat.radius; + } + } + + if (overFormat != null){ + if (overFormat.radius != null){ + this.over.args.radius = overFormat.radius; + } + } + + if (draggingFormat != null){ + if (draggingFormat.radius != null){ + this.dragging.args.draggingFormat = draggingFormat.radius; + } + } +}; + + + +RectangleVertexGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; +RectangleVertexGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; +RectangleVertexGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; +RectangleVertexGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; +RectangleVertexGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; +RectangleVertexGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; +RectangleVertexGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; +RectangleVertexGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; + +function RectangleVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ + VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); + this.args.type = "RectangleVertexGraphFormatter"; + if (defaultFormat != null){ + if (defaultFormat.radius != null){ + this.defaultFormat.args.radius = defaultFormat.radius; + } + } + + if (selectedFormat != null){ + if (selectedFormat.radius != null){ + this.selected.args.radius = selectedFormat.radius; + } + } + + if (overFormat != null){ + if (overFormat.radius != null){ + this.over.args.radius = overFormat.radius; + } + } + + if (draggingFormat != null){ + if (draggingFormat.radius != null){ + this.dragging.args.draggingFormat = draggingFormat.radius; + } + } +}; + + + +RoundedVertexGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; +RoundedVertexGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; +RoundedVertexGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; +RoundedVertexGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; +RoundedVertexGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; +RoundedVertexGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; +RoundedVertexGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; +RoundedVertexGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; + +function RoundedVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ + VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); + this.args.type = "RoundedVertexGraphFormatter"; + if (defaultFormat != null){ + if (defaultFormat.radius != null){ + this.defaultFormat.args.radius = defaultFormat.radius; + } + } + + if (selectedFormat != null){ + if (selectedFormat.radius != null){ + this.selected.args.radius = selectedFormat.radius; + } + } + + if (overFormat != null){ + if (overFormat.radius != null){ + this.over.args.radius = overFormat.radius; + } + } + + if (draggingFormat != null){ + if (draggingFormat.radius != null){ + this.dragging.args.draggingFormat = draggingFormat.radius; + } + } +}; + + + +OctagonVertexGraphFormatter.prototype.getDefault = ItemGraphFormatter.prototype.getDefault; +OctagonVertexGraphFormatter.prototype.getSelected = ItemGraphFormatter.prototype.getSelected; +OctagonVertexGraphFormatter.prototype.getOver = ItemGraphFormatter.prototype.getOver; +OctagonVertexGraphFormatter.prototype.getDragging = ItemGraphFormatter.prototype.getDragging; +OctagonVertexGraphFormatter.prototype.getId = ItemGraphFormatter.prototype.getId; +OctagonVertexGraphFormatter.prototype.toJSON = ItemGraphFormatter.prototype.toJSON; +OctagonVertexGraphFormatter.prototype.loadFromJSON = ItemGraphFormatter.prototype.loadFromJSON; +OctagonVertexGraphFormatter.prototype._setEvents = ItemGraphFormatter.prototype._setEvents; + +function OctagonVertexGraphFormatter(id, defaultFormat, selectedFormat, overFormat, draggingFormat){ + VertexGraphFormatter.prototype.constructor.call(this, id, defaultFormat, selectedFormat, overFormat, draggingFormat); + this.args.type = "OctagonVertexGraphFormatter"; + if (defaultFormat != null){ + if (defaultFormat.radius != null){ + this.defaultFormat.args.radius = defaultFormat.radius; + } + } + + if (selectedFormat != null){ + if (selectedFormat.radius != null){ + this.selected.args.radius = selectedFormat.radius; + } + } + + if (overFormat != null){ + if (overFormat.radius != null){ + this.over.args.radius = overFormat.radius; + } + } + + if (draggingFormat != null){ + if (draggingFormat.radius != null){ + this.dragging.args.draggingFormat = draggingFormat.radius; + } + } +}; + -GraphCanvas.prototype.setEdgeFill = function(edgeId, color) { - this.getFormatter().getEdgeById(edgeId).getDefault().setFill(color); + +var Colors = new function() +{ + this.hashColor = []; + this.getColorByScoreArrayValue = function (arrayScore) + { + var array = new Array(); + + for (var i = 0; i< arrayScore.length; i++) + { + + var color = this.getColorByScoreValue(arrayScore[i]) + array.push( color); + + } + return array; + }; + + this.getHexStringByScoreArrayValue = function (arrayScore) + { + var arrayColor = this.getColorByScoreArrayValue(arrayScore); + var arrayHex = new Array(); + for (var i = 0; i< arrayColor.length; i++) + { + arrayHex.push( arrayColor[i].HexString()); + } + return arrayHex; + }; + + this.getColorByScoreValue = function (score) + { + + var truncate = score.toString().substr(0,4); + if (this.hashColor[truncate]!=null) + { + return this.hashColor[truncate]; + } + + + if(isNaN(score)) { + return Colors.ColorFromRGB(0,0,0); + } + var value; + + var from, to; + if(score < 0.5) { + from = Colors.ColorFromRGB(0,0,255); + to = Colors.ColorFromRGB(255,255,255); + value = (score * 2); + } else { + from = Colors.ColorFromRGB(255,255,255); + to = Colors.ColorFromRGB(255,0,0); + value = (score * 2) - 1; + } + + var x = value; + var y = 1.0 - value; + var color = Colors.ColorFromRGB(y * from.Red() + x * to.Red(), y * from.Green() + x * to.Green(), y * from.Blue() + x * to.Blue()); + + this.hashColor[truncate] = color; + + return color; + }; + + this.ColorFromHSV = function(hue, sat, val) + { + var color = new Color(); + color.SetHSV(hue,sat,val); + return color; + }; + + this.ColorFromRGB = function(r, g, b) + { + var color = new Color(); + color.SetRGB(r,g,b); + return color; + }; + + this.ColorFromHex = function(hexStr) + { + var color = new Color(); + color.SetHexString(hexStr); + return color; + }; + + function Color() { + //Stored as values between 0 and 1 + var red = 0; + var green = 0; + var blue = 0; + + //Stored as values between 0 and 360 + var hue = 0; + + //Strored as values between 0 and 1 + var saturation = 0; + var value = 0; + + this.SetRGB = function(r, g, b) + { + red = r/255.0; + green = g/255.0; + blue = b/255.0; + calculateHSV(); + }; + + this.Red = function() { return Math.round(red*255); }; + + this.Green = function() { return Math.round(green*255); }; + + this.Blue = function() { return Math.round(blue*255); }; + + this.SetHSV = function(h, s, v) + { + hue = h; + saturation = s; + value = v; + calculateRGB(); + }; + + this.Hue = function() + { return hue; }; + + this.Saturation = function() + { return saturation; }; + + this.Value = function() + { return value; }; + + this.SetHexString = function(hexString) + { + if(hexString == null || typeof(hexString) != "string") + { + this.SetRGB(0,0,0); + return; + } + + if (hexString.substr(0, 1) == '#') + hexString = hexString.substr(1); + + if(hexString.length != 6) + { + this.SetRGB(0,0,0); + return; + } + + var r = parseInt(hexString.substr(0, 2), 16); + var g = parseInt(hexString.substr(2, 2), 16); + var b = parseInt(hexString.substr(4, 2), 16); + if (isNaN(r) || isNaN(g) || isNaN(b)) + { + this.SetRGB(0,0,0); + return; + } + + this.SetRGB(r,g,b); + }; + + this.HexString = function() + { + + var rStr = this.Red().toString(16); + if (rStr.length == 1) + rStr = '0' + rStr; + var gStr = this.Green().toString(16); + if (gStr.length == 1) + gStr = '0' + gStr; + var bStr = this.Blue().toString(16); + if (bStr.length == 1) + bStr = '0' + bStr; + return ('#' + rStr + gStr + bStr).toUpperCase(); + }; + + this.Complement = function() + { + var newHue = (hue >= 180) ? hue - 180 : hue + 180; + var newVal = (value * (saturation - 1) + 1); + var newSat = (value*saturation) / newVal; + var newColor = new Color(); + newColor.SetHSV(newHue, newSat, newVal); + return newColor; + } ; + + function calculateHSV() + { + var max = Math.max(Math.max(red, green), blue); + var min = Math.min(Math.min(red, green), blue); + + value = max; + + saturation = 0; + if(max != 0) + saturation = 1 - min/max; + + hue = 0; + if(min == max) + return; + + var delta = (max - min); + if (red == max) + hue = (green - blue) / delta; + else if (green == max) + hue = 2 + ((blue - red) / delta); + else + hue = 4 + ((red - green) / delta); + hue = hue * 60; + if(hue < 0) + hue += 360; + } + + function calculateRGB() + { + red = value; + green = value; + blue = value; + + if(value == 0 || saturation == 0) + return; + + var tHue = (hue / 60); + var i = Math.floor(tHue); + var f = tHue - i; + var p = value * (1 - saturation); + var q = value * (1 - saturation * f); + var t = value * (1 - saturation * (1 - f)); + switch(i) + { + case 0: + red = value; green = t; blue = p; + break; + case 1: + red = q; green = value; blue = p; + break; + case 2: + red = p; green = value; blue = t; + break; + case 3: + red = p; green = q; blue = value; + break; + case 4: + red = t; green = p; blue = value; + break; + default: + red = value; green = p; blue = q; + break; + } + } + } +} +(); +/* + * Clase gestiona la insercción, eliminación de los elementos en el DOM + * + * Vital hacerla SIEMPRE compatible hacia atrás + * + * Last update: 28-10-2010 + * + */ + + +var DOM = {}; + +DOM.createNewElement = function(type, nodeParent, attributes) +{ + + var node = document.createElement(type); + for (var i=0; i0) + { + parent.removeChild(parent.childNodes[0]); + + } +}; + +DOM.select = function(targetID) +{ + return document.getElementById(targetID); +// return $("#"+targetID); }; +var Geometry = +{ + + /** From tow points obtains the angles formed with the cartesian side **/ + getAngleBetweenTwoPoints : function(x1, y1, x2, y2){ + //var m = (y1 - y2)/ (x1 - x2); + return Math.atan2(y2-y1, x2-x1); + }, + + getAdjacentSideOfRectangleRight : function(angle, hypotenuse){ + return Math.abs(Math.cos(angle)*hypotenuse); + }, + + getOppositeSideOfRectangleRight : function(angle, hypotenuse){ + return Math.abs(Math.sin(angle)*hypotenuse); + }, + + toDegree: function(radian){ + return radian*180/Math.PI; + + } + + +}; -GraphCanvas.prototype.getEdgeFill = function(edgeId) { - return this.getFormatter().getEdgeById(edgeId).getDefault().getFill(); -}; +var SVG = +{ + svgns : 'http://www.w3.org/2000/svg', + xlinkns : "http://www.w3.org/1999/xlink", + + createSVGCanvas: function(parentNode, attributes) + { + + attributes.push( ['xmlns', SVG.svgns], ['xmlns:xlink', 'http://www.w3.org/1999/xlink']); + var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + this._setProperties(svg, attributes); + parentNode.appendChild( svg); + return svg; + + }, + + createRectangle : function (x, y, width, height, attributes){ + var rect = document.createElementNS(this.svgns, "rect"); + rect.setAttribute("x",x); + rect.setAttribute("y",y); + rect.setAttribute("width",width); + rect.setAttribute("height",height); + SVG._setProperties(rect, attributes); + return rect; + }, + + drawImage64 : function (x, y, width, height, base64, svgNode, attributes) { + var node = SVG.createImage64(x, y, width, height, base64, attributes); + svgNode.appendChild(node); + return node; + }, + + createImage64 : function (x, y, width, height, base64, attributes) { + var img = document.createElementNS(this.svgns, "image"); + img.setAttribute("x",x); + img.setAttribute("y",y); + img.setAttribute("width",width); + img.setAttribute("height",height); + img.setAttribute("xlink:href",base64); + SVG._setProperties(img, attributes); + return img; + }, + + createLine: function (x1, y1, x2, y2, attributes){ + var line = document.createElementNS(this.svgns,"line"); + line.setAttribute("x1",x1); + line.setAttribute("y1",y1); + line.setAttribute("x2", x2); + line.setAttribute("y2", y2); + SVG._setProperties(line, attributes); + return line; + }, + + createClip: function (id, nodeToClip, attributes){ + var clip = document.createElementNS(this.svgns,"clipPath"); + clip.setAttribute("id",id); + clip.appendChild(nodeToClip); + return clip; + }, + + drawClip : function (id, nodeToClip, svgNode) { + var node = SVG.createClip(id, nodeToClip); + svgNode.appendChild(node); + return node; + }, + + drawRectangle : function (cx, cy, width, height, svgNode, attributes) { + try{ + var node = SVG.createRectangle(cx, cy, width, height, attributes); + svgNode.appendChild(node); + } + catch(e){ + + console.log("-------------------- "); + console.log("Error on drawRectangle " + e); + console.log(attributes); + console.log("-------------------- "); + } + return node; + }, + + createEllipse : function (x, y, rx, ry, attributes){ + var rect = document.createElementNS(this.svgns, "ellipse"); + rect.setAttribute("cx",x); + rect.setAttribute("cy",y); + rect.setAttribute("rx",rx); + rect.setAttribute("ry",ry); + SVG._setProperties(rect, attributes); + return rect; + }, + + drawEllipse : function (cx, cy, rx, ry, svgNode, attributes) { + var node = SVG.createEllipse(cx, cy, rx, ry, attributes); + svgNode.appendChild(node); + return node; + }, + + drawImage : function (x, y, canvasSVG, attributes) { + var image = document.createElementNS(this.svgns, "image"); + image.setAttribute("x",x); + image.setAttribute("y",y); + canvasSVG.appendChild(image); + SVG._setProperties(image, attributes); + }, + + drawLine : function (x1, y1, x2, y2, nodeSVG, attributes) { + try{ + var line = SVG.createLine(x1, y1, x2, y2, attributes); + nodeSVG.appendChild(line); + }catch(e){ + } + return line; + }, + + + drawPath: function (d, nodeSVG, attributes) { + var path = SVG.createPath(d, attributes); + nodeSVG.appendChild(path); + return path; + }, + + createPoligon : function (points, attributes){ + var poligon = document.createElementNS(this.svgns, "polygon"); + poligon.setAttribute("points",points); + SVG._setProperties(poligon, attributes); + return poligon; + }, + + drawPoligon : function (points, canvasSVG, attributes){ + var poligon = SVG.createPoligon(points, attributes); + canvasSVG.appendChild(poligon); + return poligon; + }, + // + + createPath : function (d, attributes){ + var path = document.createElementNS(this.svgns, "path"); + path.setAttribute("d",d); + SVG._setProperties(path, attributes); + return path; + }, + + drawCircle : function (x, y, radio, canvasSVG, attributes) { + + var newText = document.createElementNS(this.svgns,"circle"); + newText.setAttribute("cx",x); + newText.setAttribute("cy",y); + newText.setAttribute("r",radio); + + canvasSVG.appendChild(newText); + attributes["cursor"] = "pointer"; + this._setProperties(newText, attributes); + return newText; + }, + + + _setProperties: function(node, attributes) + { + if (attributes instanceof Array){ + for (var i=0; i< attributes.length; i++) + { + node.setAttribute(attributes[i][0], attributes[i][1]); + } + } + else{ + for ( var key in attributes){ + node.setAttribute(key, attributes[key]); + } + } + }, + +/* drawPath: function(pointsArray, canvasSVG, attributes){ + var path = document.createElementNS(this.svgns,"polyline"); + path.setAttribute ('id', id); + + var d= pointsArray[0].x+ " "+ pointsArray[0].y; + for (var i=1; i< pointsArray.length; i++) + { + d=d+" "+pointsArray[i].x+" "+pointsArray[i].y; + } + path.setAttribute ('points', d); + canvasSVG.appendChild(path); + },*/ + + createText : function (x, y, text, attributes) { + var node = document.createElementNS(this.svgns,"text"); + node.setAttributeNS(null , "x",x); + node.setAttributeNS(null, "y",y); + + var textNode = document.createTextNode(text); + node.appendChild(textNode); + + this._setProperties(node, attributes); + return node; + }, + + drawText : function (x, y, text, canvasSVG, attributes) { + var text = SVG.createText(x, y, text, attributes); + canvasSVG.appendChild(text); + return text; + }, + + + + drawGroup: function(svgNode, attributes) + { + var group = SVG.createGroup(attributes); + svgNode.appendChild(group); + return group; + }, + + createGroup: function(attributes){ + var group = document.createElementNS(this.svgns,"g"); + this._setProperties(group, attributes); + return group; + } + +}; + + + +var CanvasToSVG = { + + convert: function(sourceCanvas, targetSVG, x, y, id, attributes) { + + var img = this._convert(sourceCanvas, targetSVG, x, y, id); + + for (var i=0; i< attributes.length; i++) + { + img.setAttribute(attributes[i][0], attributes[i][1]); + } + }, + + _convert: function(sourceCanvas, targetSVG, x, y, id) { + var svgNS = "http://www.w3.org/2000/svg"; + var xlinkNS = "http://www.w3.org/1999/xlink"; + // get base64 encoded png from Canvas + var image = sourceCanvas.toDataURL(); + + // must be careful with the namespaces + var svgimg = document.createElementNS(svgNS, "image"); + + svgimg.setAttribute('id', id); + + //svgimg.setAttribute('class', class); + //svgimg.setAttribute('xlink:href', image); + svgimg.setAttributeNS(xlinkNS, 'xlink:href', image); + + + + + svgimg.setAttribute('x', x ? x : 0); + svgimg.setAttribute('y', y ? y : 0); + svgimg.setAttribute('width', sourceCanvas.width); + svgimg.setAttribute('height', sourceCanvas.height); + //svgimg.setAttribute('cursor', 'pointer'); + svgimg.imageData = image; + + targetSVG.appendChild(svgimg); + return svgimg; + }, + + importSVG: function(sourceSVG, targetCanvas) { + svg_xml = sourceSVG;//(new XMLSerializer()).serializeToString(sourceSVG); + var ctx = targetCanvas.getContext('2d'); + + var img = new Image(); + img.src = "data:image/svg+xml;base64," + btoa(svg_xml); +// img.onload = function() { + ctx.drawImage(img, 0, 0); +// }; + } + +}; +/* +Graph.prototype.importSVG = function(sourceSVG, targetCanvas) { + sourceSVG = this._svg; + targetCanvas = document.createElementNS('canvas'); + // https://developer.mozilla.org/en/XMLSerializer + svg_xml = (new XMLSerializer()).serializeToString(sourceSVG); + var ctx = targetCanvas.getContext('2d'); + // this is just a JavaScript (HTML) image + var img = new Image(); + // http://en.wikipedia.org/wiki/SVG#Native_support + // https://developer.mozilla.org/en/DOM/window.btoa + img.src = "data:image/svg+xml;base64," + btoa(svg_xml); + img.onload = function() { + // after this, Canvas’ origin-clean is DIRTY + ctx.drawImage(img, 0, 0); + } +}; +*/ -/** API LAYOUT **/ -GraphCanvas.prototype.setCoordinates = function(vertexId, x, y) { - return this.getLayout().getEdgeById(vertexId).setCoordinates(x, y); -}; +/* + +Normalizacion de datos para dibujar colores +Issues: + No sé como debería llamarse esta libreria + No sé si ya existe una funciçon en javascript que lo haga + + +*/ + + +var Normalizer = new function() +{ + this.normalizeArray = function (arrayData) + { + + return this.standardizeArray(this.normal(arrayData)); + +// var result = this._getMaxAndMin(arrayData); +// var min =result[0]; +// var max = result[1]; +// +// +// //los hacemos todos positivos +// for (var i = 0; i< arrayData.length; i++) +// { +// arrayData[i]= Math.abs(min) + parseFloat(arrayData[i]); +// } +// +// var result = this._getMaxAndMin(arrayData); +// var min =result[0]; +// var max = result[1]; +// +// +// var resultArray = new Array(); +// for (var i = 0; i< arrayData.length; i++) +// { +// resultArray.push(arrayData[i]*1/max); +// } +// return resultArray; + }; + + this.normal = function(arrayData){ + var mean = this._getMean(arrayData); + var deviation = this._getStdDeviation(arrayData); + var result = this._getMaxAndMin(arrayData); + var min = result[0]; + var max = result[1]; + + var resultArray = new Array(); + for (var i = 0; i< arrayData.length; i++) { + if (deviation!=0){ + resultArray.push((arrayData[i]-mean)/deviation); + }else{ + resultArray.push(arrayData[i]); + } + } + return resultArray; + }; + + this.standardizeArray = function(arrayData) + { + var result = this._getMaxAndMin(arrayData); + var min = result[0]; + var max = result[1]; + + var offset = ( min <= 0 ) ? Math.abs(min) : (-1 * min); + var resultArray = new Array(); + for (var i = 0; i< arrayData.length; i++) { + if(max + offset!=0){ + resultArray.push((arrayData[i] + offset) / (max + offset)); + }else{ + resultArray.push(arrayData[i]+offset); + } + } + return resultArray; + }; + + + this._getMean = function(arrayData) { + var sum = 0; + for (var i = 0; i< arrayData.length; i++) { + sum = sum + parseFloat(arrayData[i]); + } + return sum/arrayData.length; + }; + + this._getStdDeviation = function(arrayData) { + var mean = this._getMean(arrayData); + var acum = 0.0; + for(var i=0; i max) max = parseFloat(arrayData[i]); + } + + return [min, max]; + }; +}; +function GraphCanvas(componentID, targetNode, args) { + this.args = {}; + /** target */ + this.targetID = targetNode.id; + + /** id manage */ + this.id = componentID; + this.args.idGraph = this.id + "main"; + this.args.idBackgroundNode = this.id + "background"; + + this.args.idEdgesGraph = this.id + "edges"; + this.args.idNodesGraph = this.id + "vertices"; + this.args.idLabelGraph = this.id + "label"; + this.args.idBackground = this.id + "background"; + + /** Objects Graph **/ + this.dataset = null; + this.formatter = null; + this.layout = null; + + /** Drawing **/ + this.circleDefaultRadius = 2; + this.squareDefaultSide = this.circleDefaultRadius * 1.5; + + /** Directed Arrow **/ + this.arrowDefaultSize = this.circleDefaultRadius; + + /** Groups **/ + this.GraphGroup = null; + this.GraphNodeGroup = null; + this.GraphLabelGroup = null; + this.GraphBackground = null; + + /** SETTINGS FLAGS **/ + this.args.draggingCanvasEnabled = false; //Flag to set if the canvas can be dragged + this.args.multipleSelectionEnabled = false; + this.args.interactive = false; + this.args.labeled = false; + this.args.linkEnabled = false; + + /** If numberEdge > maxNumberEdgesMoving then only it will move edges when mouse up **/ + this.args.maxNumberEdgesMoving = 3; + this.args.maxNumberEdgesFiringEvents = 50; + + /** Linking edges **/ + this.args.linking = false; + this.linkStartX = 0; + this.linkStartY = 0; + this.linkSVGNode = null; + this.linkNodeSource = null; + this.linkNodeTarget = null; + + /** Dragging Control **/ + this.draggingElement = null; + this.dragging = false; + this.nMouseOffsetX = 0; + this.nMouseOffsetY = 0; + this.dragStartX = 0; + this.dragStartY = 0; + this.desplazamientoX = 0; + this.desplazamientoY = 0; + + /** Selection Control **/ + this.selecting = false; + this.selectorX = null; + this.selectorY = null; + this.selectorSVGNode = null; + + /** Node status **/ + this.args.isVertexSelected = {}; + this.args.selectedVertices = []; + + /** Edges status **/ + this.args.isEdgeSelected = {}; + //this.args.selectedEdges = []; + + if (args != null) { + if (args.multipleSelectionEnabled != null) { + this.args.multipleSelectionEnabled = args.multipleSelectionEnabled; + this.args.draggingCanvasEnabled = !(this.args.multipleSelectionEnabled); + } + if (args.draggingCanvasEnabled != null) { + this.args.draggingCanvasEnabled = args.draggingCanvasEnabled; + this.args.multipleSelectionEnabled = !(this.args.draggingCanvasEnabled); + } + if (args.interactive != null) { + this.args.interactive = args.interactive; + } + if (args.labeled != null) { + this.args.labeled = args.labeled; + } + + } + + /** Hashmap with the svg node labels **/ + this.svgLabels = {}; + + /** EVENTS **/ + this.onVertexOut = new Event(this); + this.onVertexOver = new Event(this); + this.onVertexSelect = new Event(this); + this.onEdgeSelect = new Event(this); + this.onCanvasClicked = new Event(this); + this.onVertexUp = new Event(this); +} + +GraphCanvas.prototype.showLabels = function(value) { + this.args.labeled = value; + this.removeLabels(); + if (value) { + this.renderLabels(); + } +}; + +GraphCanvas.prototype.getSelectedVertices = function() { + return this.args.selectedVertices; +}; + +GraphCanvas.prototype.getSelectedEdges = function() { + var selected = []; + for ( var selectedEdge in this.args.isEdgeSelected) { + selected.push(selectedEdge); + } + return selected; +}; + +GraphCanvas.prototype.createSVGDom = function(targetID, id, width, height, backgroundColor) { + var container = document.getElementById(targetID); + this._svg = SVG.createSVGCanvas(container, [ + [ "style", "background-color:" + backgroundColor + ";" ], [ "id", id ], [ "dragx", 0 ], [ "dragy", 0 ], + [ "height", this.getFormatter().getHeight() ], [ "width", this.getFormatter().getWidth() ] ]); + return this._svg; +}; + +/** MULTIPLE SELECTION **/ +GraphCanvas.prototype.isMultipleSelectionEnabled = function() { + return this.args.multipleSelectionEnabled; +}; + +GraphCanvas.prototype.setMultipleSelection = function(value) { + this.args.multipleSelectionEnabled = value; + this.args.draggingCanvasEnabled = (!value); +}; + +GraphCanvas.prototype.setSelecting = function(value) { + this.selecting = value; +}; + +/** linking **/ +GraphCanvas.prototype.setLinking = function(value) { + this.args.linkEnabled = value; + this.selecting = !value; + this.dragging = !value; +}; + +/** CANVAS MOVING **/ +GraphCanvas.prototype.setDraggingCanvas = function(value) { + this.args.draggingCanvasEnabled = value; + this.args.multipleSelectionEnabled = !value; +}; + +GraphCanvas.prototype.isDraggingCanvasEnabled = function() { + return this.args.draggingCanvasEnabled; +}; +/** ZOOM **/ +GraphCanvas.prototype.getScale = function() { + return this.getFormatter().getZoomScale(); +}; + +GraphCanvas.prototype.setScale = function(scale) { + var graphNode = document.getElementById(this.args.idGraph); + graphNode.setAttribute("transform", graphNode.getAttribute("transform").replace("scale(" + this.getScale() + ")", "scale(" + scale + ")")); + this.getFormatter().setZoomScale(scale); +}; + +GraphCanvas.prototype.zoomIn = function() { + this.setScale(this.getScale() + this.getFormatter().getZoomScaleStepFactor()); +}; + +GraphCanvas.prototype.zoomOut = function() { + this.setScale(this.getScale() - this.getFormatter().getZoomScaleStepFactor()); + +}; + +/** SVG COORDENATES **/ +GraphCanvas.prototype.getSVGCoordenates = function(evt) { + var p = this._svg.createSVGPoint(); + p.x = evt.clientX; + p.y = evt.clientY; + + var m = this._svg.getScreenCTM(document.documentElement); + p = p.matrixTransform(m.inverse()); + return p; +}; + +/** SVG EVENTS **/ +GraphCanvas.prototype.mouseClick = function(event) { + if (event.button == 0) { + if (!this.args.interactive) { + return; + } + + if (this.isVertex(event.target)) { + this.clickNode(this.getVertexIdFromSVGId(event.target.id)); + } + /** Como el evento mouseClick viene despues del mouse up es aqui donde manejo el tema de deseccionar los elementos que estoy dragging **/ + if (this.dragging) { + this.dragging = false; + } + } +}; + +GraphCanvas.prototype.mouseMove = function(evt) { + if (this.selecting) { + this.clearLabels(); + + var width = (this.getSVGCoordenates(evt).x - this.selectorX); + var height = (this.getSVGCoordenates(evt).y - this.selectorY); + if ((width > 0) && (height > 0)) { + this.displaySelection(this.selectorX, this.selectorY, width, height); + } + if ((width > 0) && (height < 0)) { + this.displaySelection(this.selectorX, this.getSVGCoordenates(evt).y, width, Math.abs(height)); + } + if ((width < 0) && (height < 0)) { + this.displaySelection(this.getSVGCoordenates(evt).x, this.getSVGCoordenates(evt).y, Math.abs(width), Math.abs(height)); + } + if ((width < 0) && (height > 0)) { + this.displaySelection(this.selectorX + width, this.selectorY, Math.abs(width), Math.abs(height)); + } + + var x1 = (parseFloat(this.selectorSVGNode.getAttribute("x")) - DOM.select(this.id).getAttribute("dragx")) / this.getFormatter().getWidth(); + var y1 = (parseFloat(this.selectorSVGNode.getAttribute("y")) - DOM.select(this.id).getAttribute("dragy")) / this.getFormatter().getHeight(); + var x2 = (x1 + parseFloat(this.selectorSVGNode.getAttribute("width") / this.getFormatter().getWidth())); + var y2 = (y1 + parseFloat(this.selectorSVGNode.getAttribute("height") / this.getFormatter().getHeight())); + + this.deselectNodes(this.getLayout()); + var verticesSelected = this.getLayout().getVerticesByArea(x1 / this.getFormatter().getZoomScale(), y1 / this.getFormatter().getZoomScale(), + x2 / this.getFormatter().getZoomScale(), y2 / this.getFormatter().getZoomScale()); + for ( var i = 0; i < verticesSelected.length; i++) { + this.selectNode(verticesSelected[i].getId()); + this.renderLabel(verticesSelected[i].getId()); + } + + } + var p = null; + if (this.args.linking) { + p = this.getSVGCoordenates(evt); + if (this.linkSVGNode != null) { + this.linkSVGNode.setAttribute("x2", p.x - 2); + this.linkSVGNode.setAttribute("y2", p.y - 2); + } + } + + if (this.dragging) { + p = this.getSVGCoordenates(evt); + p.x -= this.nMouseOffsetX; + p.y -= this.nMouseOffsetY; + this.desplazamientoX = (this.getSVGCoordenates(evt).x - this.dragStartX);// + parseFloat(DOM.select(this.id).getAttribute("dragx")); + this.desplazamientoY = (this.getSVGCoordenates(evt).y - this.dragStartY);// + parseFloat(DOM.select(this.id).getAttribute("dragy")); + + if (this.draggingElement != null) { + /** Click sobre el recct del banground que provoca que mueva todo el canvas **/ + if (this.isNodeCanvas(this.draggingElement)) { + + p = this.getSVGCoordenates(evt); + p.x = this.desplazamientoX; + p.y = this.desplazamientoY; + + this.draggingElement.setAttribute("dragx", p.x); + this.draggingElement.setAttribute("dragy", p.y); + this.draggingElement = document.getElementById(this.args.idGraph); + this.draggingElement.setAttribute("transform", "translate(" + p.x + "," + p.y + "), scale(" + this.getScale() + ")"); + + DOM.select(this.id).setAttribute("dragx", p.x); + DOM.select(this.id).setAttribute("dragy", p.y); + + if (this.NodeSVGbackgroundImage != null) { + this.NodeSVGbackgroundImage.setAttribute("dragx", p.x); + this.NodeSVGbackgroundImage.setAttribute("dragy", p.y); + } + } else { + if (this.isVertex(this.draggingElement)) { + this.selectNode(this.getVertexIdFromSVGId(this.draggingElement.id)); + this.desplazamientoX = this.desplazamientoX / this.getFormatter().getZoomScale(); + this.desplazamientoY = this.desplazamientoY / this.getFormatter().getZoomScale(); + this.moveSelectedNodes(this.desplazamientoX, this.desplazamientoY); + + this.dragStartX = this.getSVGCoordenates(evt).x; + this.dragStartY = this.getSVGCoordenates(evt).y; + } else { + if (this.isNodeBackground(this.draggingElement)) { + + this.draggingElement.setAttribute("dragx", p.x); + this.draggingElement.setAttribute("dragy", p.y); + this.draggingElement = document.getElementById(this.args.idGraph); + this.draggingElement.setAttribute("transform", "translate(" + p.x + "," + p.y + "), scale(" + this.getScale() + ")"); + } else { + this.draggingElement.setAttribute("transform", "translate(" + p.x + "," + p.y + ")"); + } + } + } + } + } +}; + +GraphCanvas.prototype.moveSelectedNodes = function(offsetX, offsetY) { + for ( var i = 0; i < this.getSelectedVertices().length; i++) { + + var nodeId = this.getSelectedVertices()[i]; + var svgNodeId = this.getSVGNodeId(nodeId); + + var x = parseFloat(DOM.select(svgNodeId).getAttribute("dragx")) + parseFloat(offsetX);// - parseFloat(DOM.select(this.id).getAttribute("dragx")); + var y = parseFloat(DOM.select(svgNodeId).getAttribute("dragy")) + parseFloat(offsetY);// + parseFloat(DOM.select(this.id).getAttribute("dragy")); + + this._movingNode(DOM.select(svgNodeId), x, y); + } +}; + +GraphCanvas.prototype.mouseDown = function(evt) { + if (event.button == 0) { + + /** if !no interactive mouse events do anything **/ + if (!this.args.interactive) { + return; + } + + var p = this.getSVGCoordenates(evt); + + /** When click on canvas or background deselect all **/ + if (this.isNodeCanvas(evt.target) || this.isNodeBackground(evt.target)) { + this.deselectNodes(); + this.deselectEdges(); + this.onCanvasClicked.notify(); + } + + /** if I am linking vertices **/ + if (this.args.linkEnabled) { + + if (!this.args.linking) { + this.args.linking = true; + if (this.isVertex(evt.target)) { + this.linkStartX = p.x; + this.linkStartY = p.y; + this.linkSVGNode = SVG.drawLine(p.x, p.y, p.x, p.y, this._svg, { + "stroke" : "#FF0000" + }); + this.linkNodeSource = this.getVertexIdFromSVGId(evt.target.id); + } + } else { + this.linkNodeTarget = this.getVertexIdFromSVGId(evt.target.id); + this.args.linking = false; + this.args.linkEnabled = false; + if (this.isVertex(evt.target)) { + this.getDataset().addEdge(this.linkNodeSource + "_" + this.linkNodeTarget, this.linkNodeSource, this.linkNodeTarget, {}); + } + this.linkSVGNode.parentNode.removeChild(this.linkSVGNode); + } + return; + } + + /** Id is a vertex or the canvas **/ + if (this.isVertex(evt.target) || this.isNodeCanvas(evt.target) || this.isNodeBackground(evt.target)) { + this._startDragging(evt); + } + /** if i is edge **/ + if (this.isEdge(evt.target)) { + this.selectEdge(this.getEdgeIdFromSVGId(evt.target.getAttribute("id"))); + } + + if (this.args.multipleSelectionEnabled) { + if (!this.dragging) { + this.setSelecting(true); + this.selectorX = p.x; + this.selectorY = p.y; + this.displaySelection(p.x, p.y, 1, 1); + } + } + + } + if (event.button == 1) { + this.setLinking(false); + this.setMultipleSelection(false); + this.selecting = false; + + /** Id is a vertex or the canvas **/ + if (this.isVertex(evt.target) || this.isNodeCanvas(evt.target) || this.isNodeBackground(evt.target)) { + this._startDragging(evt); + } + } +}; + +GraphCanvas.prototype.mouseUp = function(event) { + if (!this.args.interactive) { + return; + } + + if (this.dragging) { + this._stopDragging(event); + if (this.isVertex(event.target)) { + var vertexId = this.getVertexIdFromSVGId(event.target.id); + if (this.getDataset().getVertexById(vertexId).getEdges().length >= this.args.maxNumberEdgesMoving) { + this.moveEdge(vertexId); + } + } + } + + if (this.selecting) { + this.setSelecting(false); + + var x1 = (parseFloat(this.selectorSVGNode.getAttribute("x")) - DOM.select(this.id).getAttribute("dragx")) / this.getFormatter().getWidth(); + var y1 = (parseFloat(this.selectorSVGNode.getAttribute("y")) - DOM.select(this.id).getAttribute("dragy")) / this.getFormatter().getHeight(); + var x2 = (x1 + parseFloat(this.selectorSVGNode.getAttribute("width") / this.formatter.getWidth())); + var y2 = (y1 + parseFloat(this.selectorSVGNode.getAttribute("height") / this.formatter.getHeight())); + + var verticesSelected = this.getLayout().getVerticesByArea(x1 / this.getFormatter().getZoomScale, y1 / this.getFormatter().getZoomScale, + x2 / this.getFormatter().getZoomScale, y2 / this.getFormatter().getZoomScale); + + for ( var i = 0; i < verticesSelected.length; i++) { + this.selectNode(verticesSelected[i].getId()); + } + + if (this.selectorSVGNode != null) { + this._svg.removeChild(this.selectorSVGNode); + } + + if (this.args.labeled) { + this.clearLabels(); + this.renderLabels(); + } + + this.selectorSVGNode = null; + // this.renderLabels(); + } +}; + +/** SELECTION **/ +GraphCanvas.prototype.displaySelection = function(x, y, width, height) { + if (this.selectorSVGNode != null) { + this.selectorSVGNode.setAttribute("x", x); + this.selectorSVGNode.setAttribute("y", y); + this.selectorSVGNode.setAttribute("width", width); + this.selectorSVGNode.setAttribute("height", height); + } else { + this.selectorSVGNode = SVG.drawRectangle(x, y, width, height, this._svg, { + "fill" : "red", + "stroke" : "black", + "opacity" : "0.2", + "stroke-opacity" : "1" + }); + } +}; + +/** DRAGGING **/ +GraphCanvas.prototype._startDragging = function(evt) { + if (!this.isDraggingCanvasEnabled()) { + if (this.isNodeCanvas(evt.target)) { + this.draggingElement = null; + } + } + + if (this.isVertex(evt.target) || (this.isNodeBackground(evt.target) && (this.isDraggingCanvasEnabled()))|| (this.isNodeCanvas(evt.target) && (this.isDraggingCanvasEnabled()))) { + this.clearLabels(); + this.draggingElement = evt.target; + this.dragging = true; + var p = this.getSVGCoordenates(evt); + + this.nMouseOffsetX = p.x - parseInt(evt.target.getAttribute("dragx")); + this.nMouseOffsetY = p.y - parseInt(evt.target.getAttribute("dragy")); + + if (this.isVertex(evt.target)) { + this.dragStartX = parseInt(this.draggingElement.getAttribute("dragx")) * this.getFormatter().getZoomScale() + + parseFloat(DOM.select(this.id).getAttribute("dragx")); + this.dragStartY = parseInt(this.draggingElement.getAttribute("dragy")) * this.getFormatter().getZoomScale() + + parseFloat(DOM.select(this.id).getAttribute("dragy")); + } else { + this.dragStartX = p.x - parseInt(this.draggingElement.getAttribute("dragx"));// + parseFloat(DOM.select(this.id).getAttribute("dragx")); + this.dragStartY = p.y - parseInt(this.draggingElement.getAttribute("dragy"));// + parseFloat(DOM.select(this.id).getAttribute("dragy")); + } + } +}; + +GraphCanvas.prototype._stopDragging = function(event) { + this.nMouseOffsetX = 0; + this.nMouseOffsetX = 0; + /** despues del evento up viene el evento click entonces acabo el dragging en el mouseclick **/ + this.dragging = false; + this.draggingElement = null; + this.renderLabels(); + + this.setLinking(false); + this.setMultipleSelection(true); + this.selecting = false; + +}; + +/** Move the edges of the vertex with the vertexId indicado **/ +GraphCanvas.prototype.moveEdge = function(vertexId) { + var x = this.getLayout().getNodeById(vertexId).x * this.getFormatter().getWidth(); + var y = this.getLayout().getNodeById(vertexId).y * this.getFormatter().getHeight(); + + /** Moving edges out **/ + for ( var i = 0; i < this.getDataset().getVertexById(vertexId).getEdgesOut().length; i++) { + var edgeId = this.getDataset().getVertexById(vertexId).getEdgesOut()[i].getId(); + var svgEdgeId = this.getSVGEdgeId(edgeId); + var edgeFormatter = this.getFormatter().getEdgeById(edgeId); + if (edgeFormatter instanceof LineEdgeGraphFormatter) { + DOM.select(svgEdgeId + "_shadow").setAttribute("x2", x); + DOM.select(svgEdgeId + "_shadow").setAttribute("y2", y); + DOM.select(svgEdgeId).setAttribute("x2", x); + DOM.select(svgEdgeId).setAttribute("y2", y); + } + + if ((edgeFormatter instanceof DirectedLineEdgeGraphFormatter) || (edgeFormatter instanceof OdirectedLineEdgeGraphFormatter) + || (edgeFormatter instanceof OdotDirectedLineEdgeGraphFormatter) || (edgeFormatter instanceof DotDirectedLineEdgeGraphFormatter) + || (edgeFormatter instanceof CutDirectedLineEdgeGraphFormatter)) { + this.removeEdge(edgeId); + this.renderEdge(edgeId); + } + } + + /** Moving edges in **/ + for ( var i = 0; i < this.getDataset().getVertexById(vertexId).getEdgesIn().length; i++) { + var edgeId = this.getDataset().getVertexById(vertexId).getEdgesIn()[i].getId(); + var svgEdgeId = this.getSVGEdgeId(edgeId); + var edgeFormatter = this.getFormatter().getEdgeById(edgeId); + if (edgeFormatter instanceof LineEdgeGraphFormatter) { + DOM.select(svgEdgeId).setAttribute("x1", x); + DOM.select(svgEdgeId).setAttribute("y1", y); + DOM.select(svgEdgeId + "_shadow").setAttribute("x1", x); + DOM.select(svgEdgeId + "_shadow").setAttribute("y1", y); + } + + if ((edgeFormatter instanceof DirectedLineEdgeGraphFormatter) || (edgeFormatter instanceof OdirectedLineEdgeGraphFormatter) + || (edgeFormatter instanceof OdotDirectedLineEdgeGraphFormatter) || (edgeFormatter instanceof DotDirectedLineEdgeGraphFormatter) + || (edgeFormatter instanceof CutDirectedLineEdgeGraphFormatter)) { + this.removeEdge(edgeId); + this.renderEdge(edgeId); + } + + if (edgeFormatter instanceof BezierEdgeGraphFormatter) { + var radius = this.getFormatter().getVertexById(vertexId).getDefault().getSize() * this.getFormatter().getNodesMaxSize(); + var d = this.calculateCoordenatesBezier(radius, x, y); + DOM.select(svgEdgeId).setAttribute("d", d); + } + } +}; + +GraphCanvas.prototype.moveNode = function(vertexId) { + var x = this.getLayout().getNodeById(vertexId).x * this.getFormatter().getWidth(); + var y = this.getLayout().getNodeById(vertexId).y * this.getFormatter().getHeight(); + var svgNodeElement = DOM.select(this.getSVGNodeId(vertexId)); + + svgNodeElement.setAttribute("dragx", x); + svgNodeElement.setAttribute("dragy", y); + svgNodeElement.setAttribute("transform", "translate(" + x + "," + y + ")"); + + if (this.getDataset().getVertexById(vertexId).getEdges().length < this.args.maxNumberEdgesMoving) { + this.moveEdge(vertexId); + } +}; + +GraphCanvas.prototype._movingNode = function(svgNodeElement, x, y) { + var vertexId = this.getVertexIdFromSVGId(svgNodeElement.getAttribute("id")); + this.getLayout().getNodeById(vertexId).setCoordinates(x / this.getFormatter().getWidth(), y / this.getFormatter().getHeight()); + this.desplazamientoX = 0; + this.desplazamientoY = 0; + this.removeLabel(vertexId); + this.renderLabel(vertexId); +}; + +/** INIT **/ +GraphCanvas.prototype.init = function() { + + this._svg = this.createSVGDom(this.targetID, this.id, this.getFormatter().getWidth(), this.getFormatter().getHeight(), this.getFormatter() + .getBackgroundColor()); + this.GraphGroup = SVG.drawGroup(this._svg, [ [ "id", this.args.idGraph ], [ "transform", "translate(0,0), scale(1)" ] ]); + this.GraphBackground = SVG.drawGroup(this.GraphGroup, [ [ "id", this.args.idBackground ] ]); + this.GraphEdgeGroup = SVG.drawGroup(this.GraphGroup, [ [ "id", this.args.idEdgesGraph ] ]); + this.GraphNodeGroup = SVG.drawGroup(this.GraphGroup, [ [ "id", this.args.idNodesGraph ] ]); + this.GraphLabelGroup = SVG.drawGroup(this.GraphGroup, [ [ "id", this.args.idLabelGraph ] ]); + + if ((this.getFormatter().getBackgroundImage() != null) && (this.getFormatter().getBackgroundImage() != "")) { + this.setBackgroundImage(this.getFormatter().getBackgroundImage()); + } + /** SVG Events listener */ + var _this = this; + this._svg.addEventListener("click", function(event) { + _this.mouseClick(event); + }, false); + this._svg.addEventListener("mousemove", function(event) { + _this.mouseMove(event, _this); + }, false); + this._svg.addEventListener("mousedown", function(event) { + _this.mouseDown(event, _this); + }, false); + this._svg.addEventListener("mouseup", function(event) { + _this.mouseUp(event, _this); + }, false); +}; + +/* + GraphCanvas.prototype.backgroungToSVG = function(){ + var _this = this; + var canvas = document.createElement('canvas'); + canvas.setAttribute("id", "canvas"); + canvas.width = this.formatter.getWidth(); + canvas.height = this.formatter.getHeight(); + + this._svg.parentNode.parentNode.appendChild(canvas); + var ctx = document.getElementById('canvas').getContext('2d'); + var img = new Image(); + + img.src = this.formatter.getBackgroundImage(); + ctx.drawImage(img,0,0 ,_this.formatter.getWidth(), _this.formatter.getHeight()); + + + img.onload = function() { + canvas.parentNode.removeChild(canvas); + } + + this.NodeSVGbackgroundImage.setAttribute("xlink:href", document.getElementById("canvas").toDataURL()); + this.NodeSVGbackgroundImage.removeAttribute("href"); + + // + + };*/ + +GraphCanvas.prototype.setBackgroundImage = function() { + if (this.NodeSVGbackgroundImage != null) { + this.NodeSVGbackgroundImage.parentNode.removeChild(this.NodeSVGbackgroundImage); + } + $('#' + this.targetID).svg(); + $('#' + this.targetID).svg("get"); + + $('#' + this.targetID).svg("get")._svg = document.getElementById(this.id); + + var svg = $('#' + this.targetID).svg("get"); + this.NodeSVGbackgroundImage = svg.image(0, 0, this.getFormatter().getWidth(), this.getFormatter().getHeight(), this.getFormatter() + .getBackgroundImage()); + this.NodeSVGbackgroundImage.setAttribute("id", this.args.idBackgroundNode); + + this.NodeSVGbackgroundImage.setAttribute("x", 0); + this.NodeSVGbackgroundImage.setAttribute("y", 0); + + this.NodeSVGbackgroundImage.setAttribute("dragx", 0); + this.NodeSVGbackgroundImage.setAttribute("dragy", 0); + + if (this.getFormatter().args.backgroundImageHeight != null) { + this.NodeSVGbackgroundImage.setAttribute("height", this.getFormatter().args.backgroundImageHeight); + } + if (this.getFormatter().args.backgroundImageWidth != null) { + this.NodeSVGbackgroundImage.setAttribute("width", this.getFormatter().args.backgroundImageWidth); + } + + if (this.getFormatter().args.backgroundImageX != null) { + this.NodeSVGbackgroundImage.setAttribute("x", this.getFormatter().args.backgroundImageX); + } + if (this.getFormatter().args.backgroundImageY != null) { + this.NodeSVGbackgroundImage.setAttribute("y", this.getFormatter().args.backgroundImageY); + } + + this.GraphBackground.appendChild(this.NodeSVGbackgroundImage); + this.NodeSVGbackgroundImage.removeAttribute("href"); + this.NodeSVGbackgroundImage.setAttribute("xlink:href", this.getFormatter().getBackgroundImage()); +}; + +GraphCanvas.prototype.removeBackgroundImage = function() { + if (this.NodeSVGbackgroundImage != null) { + this.NodeSVGbackgroundImage.parentNode.removeChild(this.NodeSVGbackgroundImage); + } +}; + +GraphCanvas.prototype._setBackgroundColor = function(color) { + var attributes = [ [ "fill", color ] ]; + SVG.drawRectangle(0, 0, this.getFormatter().getWidth(), this.getFormatter().getHeight(), this.GraphBackground, attributes); +}; + +/** Serialize **/ +GraphCanvas.prototype.toJSON = function() { + var json = {}; + json.dataset = {}; + json.formatter = {}; + json.layout = {}; + json.dataset = this.getDataset().toJSON(); + json.formatter = this.getFormatter().toJSON(); + json.layout = this.getLayout().toJSON(); + return json; +}; + +GraphCanvas.prototype.toHTML = function() { + //this.backgroungToSVG(); + var html = this._svg.parentElement.innerHTML; + + var start = html.indexOf("") + 6; + + return html.substr(start, end); +}; + +/** DRAW **/ +GraphCanvas.prototype.draw = function(graphdataset, graphformatter, graphlayout) { + this.setDataset(graphdataset); + this.setFormatter(graphformatter); + this.setLayout(graphlayout); + + var _this = this; + this.getFormatter().changed.attach(function(sender, item) { + _this.removeNode(item.getId()); + _this.renderNode(item.getId()); + if (_this.args.labeled) { + _this.removeLabel(item.getId()); + _this.renderLabel(item.getId()); + } + + }); + //TODO + this.getFormatter().edgeChanged.attach(function(sender, item) { + _this.removeEdge(item.getId()); + _this.renderEdge(item.getId()); + }); + + this.getFormatter().resized.attach(function(sender, item) { + _this.resize(_this.getFormatter().getWidth(), _this.getFormatter().getHeight()); + }); + + this.getFormatter().backgroundImageChanged.attach(function(sender, item) { + _this.setBackgroundImage(_this.getFormatter().getBackgroundImage()); + }); + + this.getFormatter().backgroundColorChanged.attach(function(sender, item) { + _this._setBackgroundColor(_this.getFormatter().getBackgroundColor()); + }); + + this.getLayout().changed.attach(function(sender, item) { + _this.moveNode(item.getId()); + _this.moveEdge(item.getId()); + if (_this.args.labeled) { + _this.removeLabel(item.getId()); + _this.renderLabel(item.getId()); + } + }); + + this.getDataset().newVertex.attach(function(sender, item) { + + _this.renderNode(item.getId()); + if (_this.args.labeled) { + _this.renderLabel(item.getId()); + } + }); + + this.getDataset().newEdge.attach(function(sender, item) { + _this.renderEdge(item.getId()); + }); + + this.getDataset().vertexDeleted.attach(function(sender, item) { + _this.removeNode(item.getId()); + if (_this.args.labeled) { + _this.removeLabel(item.getId()); + } + }); + + this.getDataset().edgeDeleted.attach(function(sender, item) { + _this.removeEdge(item.getId()); + }); + + this.getDataset().vertexNameChanged.attach(function(sender, args) { + if (_this.args.labeled) { + _this.removeLabel(args.item.getId()); + _this.removeLabel(args.item.getId()); + _this.renderLabel(args.item.getId()); + } + }); + this.init(); + this.render(); +}; + +GraphCanvas.prototype.render = function() { + for ( var id in this.getDataset().getVertices()) { + this.renderNode(id); + } + this.renderLabels(); + this.renderEdges(); +}; + +GraphCanvas.prototype.renderLabels = function() { + if (this.args.labeled) { + for ( var id in this.getDataset().getVertices()) { + this.renderLabel(id); + } + } +}; + +GraphCanvas.prototype.removeLabels = function() { + for ( var id in this.getDataset().getVertices()) { + this.removeLabel(id); + } +}; + +/** Utilities method for nodes **/ +GraphCanvas.prototype.isNodeCanvas = function(node) { + return ((node.id == this.args.idGraph) || (node.id == this.id)); +}; + +GraphCanvas.prototype.isNodeBackground = function(node) { + return ((node.id == this.args.idBackgroundNode)); +}; + +GraphCanvas.prototype.isVertex = function(node) { + if (node.getAttribute("id") != null) { + if (node.getAttribute("id").indexOf("_v_") != -1) { + return true; + } + } + return false; +}; + +GraphCanvas.prototype.isLabel = function(node) { + if (node.getAttribute("id") != null) { + if (node.getAttribute("id").indexOf("_l_") != -1) { + return true; + } + } + return false; +}; + +GraphCanvas.prototype.isEdge = function(node) { + if (node.getAttribute("id") != null) { + if (node.getAttribute("id").indexOf("_e_") != -1) { + return true; + } + } + return false; +}; + +/** Resize **/ +GraphCanvas.prototype.resize = function(width, height) { + // this._svg.setAttribute("width", width); + // this._svg.setAttribute("height", height); + if (this.NodeSVGbackgroundImage != null) { + this.NodeSVGbackgroundImage.setAttribute("width", width); + this.NodeSVGbackgroundImage.setAttribute("height", height); + } + + this._svg.setAttribute("width", width); + this._svg.setAttribute("height", height); + + this.clearCanvas(); + this.render(); +}; + +GraphCanvas.prototype.clearCanvas = function() { + DOM.removeChilds(this.GraphEdgeGroup.getAttribute("id")); + DOM.removeChilds(this.GraphNodeGroup.getAttribute("id")); + this.clearLabels(); +}; + +GraphCanvas.prototype.clearLabels = function() { + DOM.removeChilds(this.GraphLabelGroup.getAttribute("id")); +}; + +/** ID'S converter **/ +GraphCanvas.prototype.getSVGNodeId = function(nodeId) { + return this.id + "_v_" + nodeId; +}; + +GraphCanvas.prototype.getSVGEdgeId = function(edgeId) { + return this.id + "_e_" + edgeId; +}; + +GraphCanvas.prototype.getSVGArrowEdgeId = function(edgeId) { + return this.id + "_arrow_" + edgeId; +}; + +GraphCanvas.prototype.getSVGLabelId = function(edgeId) { + return this.id + "_l_" + edgeId; +}; + +GraphCanvas.prototype.blinkVertexById = function(vertexId) { + $("#" + this.getSVGNodeId(vertexId)).fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut(); +}; + +GraphCanvas.prototype.getVertexIdFromSVGId = function(svgVertexId) { + return svgVertexId.replace(this.id, "").replace("_v_", ""); +}; + +GraphCanvas.prototype.getEdgeIdFromSVGId = function(svgEdgeId) { + return svgEdgeId.replace(this.id, "").replace("_e_", ""); +}; + +/** VERTEX **/ +GraphCanvas.prototype.getVertexById = function(id) { + return document.getElementById(this.getSVGNodeId(id)); +}; + +GraphCanvas.prototype.renderNodes = function() { + for ( var id in this.getDataset().getVertices()) { + this.renderNode(id); + } +}; + +GraphCanvas.prototype.overNode = function(nodeId) { + if (!this.args.interactive) { + return; + } + /** If selected we don't change the format **/ + if (this.args.isVertexSelected[nodeId] == null) { + var args = this.getFormatter().getVertexById(nodeId).getOver(); + args.args["cursor"] = 'pointer'; + this.changeVertexFormat(nodeId, args); + } +}; + +GraphCanvas.prototype.outNode = function(nodeId) { + if (!this.args.interactive) { + return; + } + + /** If selected we don't change the format **/ + if (this.args.isVertexSelected[nodeId] == null) { + this.changeVertexFormat(nodeId, this.getFormatter().getVertexById(nodeId).getDefault()); + } +}; + +GraphCanvas.prototype.overLabel = function(nodeId) { + this.overNode(nodeId); + // this.svgLabels[nodeId].setAttribute("cursor", "pointer"); +}; + +GraphCanvas.prototype.outLabel = function(nodeId) { + this.outNode(nodeId); + // this.svgLabels[nodeId].setAttribute("cursor", ""); +}; + +GraphCanvas.prototype.clickNode = function(nodeId) { + if (!this.args.interactive) { + return; + } + + /** si el evento se dispara oprque estaba dragging entonces no activo nada **/ + if (this.args.isVertexSelected[nodeId] == null) { + this.selectNode(nodeId); + } else { + this.deselectNode(nodeId); + } +}; + +GraphCanvas.prototype.selectNode = function(nodeId) { + for ( var i = 0; i < this.args.selectedVertices.length; i++) { + var format = this.getFormatter().getVertexById(nodeId).getSelected(); + format.opacity = 0.2; + this.changeVertexFormat(nodeId, this.getFormatter().getVertexById(nodeId).getSelected()); + } + + if (this.args.isVertexSelected[nodeId] == null) { + var format = this.getFormatter().getVertexById(nodeId).getSelected(); + format.opacity = 1; + this.changeVertexFormat(nodeId, this.getFormatter().getVertexById(nodeId).getSelected()); + this.args.selectedVertices.push(nodeId); + this.args.isVertexSelected[nodeId] = this.args.selectedVertices.length - 1; + this.onVertexSelect.notify(nodeId); + } +}; + +GraphCanvas.prototype.selectAllEdges = function() { + this.deselectNodes(); + this.deselectEdges(); + + for ( var edgesId in this.getDataset().edges) { + this.selectEdge(edgesId); + } +}; + +GraphCanvas.prototype.selectAllNodes = function() { + this.deselectNodes(); + this.deselectEdges(); + + for ( var vertexId in this.getDataset().vertices) { + this.selectNode(vertexId); + } +}; + +GraphCanvas.prototype.selectAll = function() { + this.deselectNodes(); + this.deselectEdges(); + + for ( var vertexId in this.getDataset().vertices) { + this.selectNode(vertexId); + } + + for ( var edgesId in this.getDataset().edges) { + this.selectEdge(edgesId); + } +}; + +GraphCanvas.prototype.selectEdge = function(edgeId) { + if (this.args.isEdgeSelected[edgeId] == null) { + this.changeEdgeFormat(edgeId, this.getFormatter().getEdgeById(edgeId).getSelected()); + //this.args.selectedEdges.push(edgeId); + this.args.isEdgeSelected[edgeId] = true; //this.args.selectedEdges.length - 1; + this.onEdgeSelect.notify(edgeId); + } +}; + +GraphCanvas.prototype.selectEdges = function(edges) { + + for ( var i = 0; i < edges.length; i++) { + this.selectEdge(edges[i]); + } +}; + +GraphCanvas.prototype.deselectNode = function(nodeId) { + if (this.args.isVertexSelected[nodeId] != null) { + this.changeVertexFormat(nodeId, this.getFormatter().getVertexById(nodeId).getDefault()); + this.args.selectedVertices.splice(this.args.isVertexSelected[nodeId], 1); + var index = this.args.isVertexSelected[nodeId]; + delete this.args.isVertexSelected[nodeId]; + + for ( var vertex in this.args.isVertexSelected) { + if (this.args.isVertexSelected[vertex] > index) { + this.args.isVertexSelected[vertex] = this.args.isVertexSelected[vertex] - 1; + } + } + } +}; + +GraphCanvas.prototype.deselectNodes = function() { + var selected = JSON.parse(JSON.stringify(this.getSelectedVertices())); + for ( var i = 0; i < selected.length; i++) { + this.deselectNode(selected[i]); + } +}; +GraphCanvas.prototype.selectNodes = function(idNodes) { + + for ( var i = 0; i < idNodes.length; i++) { + this.selectNode(idNodes[i]); + } + + // for ( var vertex in this.args.isVertexSelected) { + // if (this.args.isVertexSelected[vertex] > index){ + // this.args.isVertexSelected[vertex] = this.args.isVertexSelected[vertex] - 1; + // } + // } + +}; + +GraphCanvas.prototype.changeVertexFormat = function(nodeId, format) { + var svgNode = DOM.select(this.getSVGNodeId(nodeId)); + if (svgNode != null) { + var properties = format.toJSON(); + for ( var item in properties) { + svgNode.setAttribute(item, properties[item]); + } + + if (this.getFormatter().getVertexById(nodeId) instanceof CircleVertexGraphFormatter) { + var transform = "translate(" + svgNode.getAttribute("dragx") + "," + svgNode.getAttribute("dragy") + "), scale(" + format.getSize() + ")"; + svgNode.setAttribute("transform", transform); + } + } +}; + +GraphCanvas.prototype.renderLabel = function(nodeId) { + var x = Math.ceil(this.getLayout().getNodeById(nodeId).x * this.getFormatter().getWidth()); + var y = Math.ceil(this.getLayout().getNodeById(nodeId).y * this.getFormatter().getHeight()); + + var svgAttributesNode = JSON.parse(JSON.stringify(this.getFormatter().getVertexById(nodeId).getDefault().toJSON().title)); + svgAttributesNode.id = this.getSVGLabelId(this.getDataset().getVertexById(nodeId).getId()); + svgAttributesNode.dx = (-1) * (this.getDataset().getVertexById(nodeId).getName().length * svgAttributesNode["font-size"]) / 4 - 4; + + svgAttributesNode.dy = parseFloat((this.getFormatter().getVertexById(nodeId).getDefault().getSize())) + + parseFloat(svgAttributesNode["font-size"]) + parseFloat(this.getFormatter().getVertexById(nodeId).getDefault().getStrokeWidth()) - 4; + svgAttributesNode.dragx = Math.ceil(this.getLayout().getNodeById(nodeId).x * this.getFormatter().getWidth()); + + var gragy = parseFloat(this.getFormatter().getVertexById(nodeId).getDefault().getSize()) + + Math.ceil(this.getLayout().getNodeById(nodeId).y * this.getFormatter().getHeight()); + svgAttributesNode.dragy = gragy; + svgAttributesNode.transform = "translate(" + svgAttributesNode.dragx + "," + svgAttributesNode.dragy + ")";//, scale("+this.formatter.getVertexById(nodeId).getDefault().getSize()+")"; + + var nodeSVG = SVG.drawText(0, 0, this.getDataset().getVertexById(nodeId).getName(), this.GraphLabelGroup, svgAttributesNode); + + this.svgLabels[nodeId] = nodeSVG; + + /** Events for the SVG node **/ + var _this = this; + if (nodeSVG != null) { + nodeSVG.addEventListener("mouseover", function() { + _this.overLabel(nodeId); + }, false); + nodeSVG.addEventListener("mouseout", function() { + _this.outLabel(nodeId); + }, false); + } + +}; + +GraphCanvas.prototype.removeLabel = function(labelId) { + if (DOM.select(this.getSVGLabelId(labelId)) != null) { + DOM.select(this.getSVGLabelId(labelId)).parentNode.removeChild(DOM.select(this.getSVGLabelId(labelId))); + } +}; + +GraphCanvas.prototype.renderNode = function(nodeId) { + var svgAttributesNode = JSON.parse(JSON.stringify(this.getFormatter().getVertexById(nodeId).getDefault().toJSON())); + svgAttributesNode.dragx = Math.ceil(this.getLayout().getNodeById(nodeId).x * this.getFormatter().getWidth()); + svgAttributesNode.dragy = Math.ceil(this.getLayout().getNodeById(nodeId).y * this.getFormatter().getHeight()); + svgAttributesNode.transform = "translate(" + svgAttributesNode.dragx + "," + svgAttributesNode.dragy + ")"; + svgAttributesNode.id = this.getSVGNodeId(nodeId); + /*svgAttributesNode["stroke-width"] = 3 ; + svgAttributesNode["stroke-opacity"] = 1 ; + svgAttributesNode["fill-opacity"] = svgAttributesNode["opacity"] ; + svgAttributesNode["opacity"] = 1 ;*/ + this.circleDefaultRadius = this.getFormatter().getVertexById(nodeId).getDefault().getSize(); + var nodeSVG; + + if (this.getFormatter().getVertexById(nodeId) instanceof CircleVertexGraphFormatter) { + nodeSVG = SVG.drawCircle(0, 0, this.circleDefaultRadius, this.GraphNodeGroup, svgAttributesNode); + } + + if (this.getFormatter().getVertexById(nodeId) instanceof SquareVertexGraphFormatter) { + //nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius) ,0 - (this.formatter.getVertexById(nodeId).getDefault().getSize()) , (this.getFormatter().getVertexById(nodeId).getDefault().getSize()*2), (this.getFormatter().getVertexById(nodeId).getDefault().getSize()*2), this.GraphNodeGroup, svgAttributesNode); + nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius), 0 - (this.circleDefaultRadius), (this.circleDefaultRadius * 2), + (this.circleDefaultRadius * 2), this.GraphNodeGroup, svgAttributesNode); + } + + if (this.getFormatter().getVertexById(nodeId) instanceof EllipseVertexGraphFormatter) { + nodeSVG = SVG.drawEllipse(0, 0, this.circleDefaultRadius * 1.5, this.circleDefaultRadius, this.GraphNodeGroup, svgAttributesNode); + } + + if (this.getFormatter().getVertexById(nodeId) instanceof RectangleVertexGraphFormatter) { + //nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius) ,0 - ((this.circleDefaultRadius*2)/2) , (this.circleDefaultRadius*2), (this.circleDefaultRadius), this.GraphNodeGroup, svgAttributesNode); + nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius * 1.5), 0 - (this.circleDefaultRadius), (this.circleDefaultRadius * 2 * 1.5), + (this.circleDefaultRadius * 2), this.GraphNodeGroup, svgAttributesNode); + + } + + if (this.getFormatter().getVertexById(nodeId) instanceof RoundedVertexGraphFormatter) { + svgAttributesNode.ry = 2;// this.formatter.getVertexById(nodeId).getDefault().getSize()/4; + svgAttributesNode.rx = 2;// this.formatter.getVertexById(nodeId).getDefault().getSize()/4; + nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius * 1.5), 0 - (this.circleDefaultRadius), (this.circleDefaultRadius * 2 * 1.5), + (this.circleDefaultRadius * 2), this.GraphNodeGroup, svgAttributesNode); + } + + // + + if (this.getFormatter().getVertexById(nodeId) instanceof OctagonVertexGraphFormatter) { + svgAttributesNode.ry = 2; + svgAttributesNode.rx = 2; + nodeSVG = SVG.drawRectangle(0 - (this.circleDefaultRadius * 1.5), 0 - (this.circleDefaultRadius), (this.circleDefaultRadius * 2 * 1.5), + (this.circleDefaultRadius * 2), this.GraphNodeGroup, svgAttributesNode); + } + + nodeSVG.internalId = nodeId; + // + var _this = this; + + /** Events for the SVG node **/ + if (nodeSVG != null) { + nodeSVG.addEventListener("mouseover", function() { + _this.onVertexOver.notify(nodeId); + _this.overNode(nodeId); + }, false); + nodeSVG.addEventListener("mouseout", function() { + _this.onVertexOut.notify(nodeId); + _this.outNode(nodeId); + }, false); + //nodeSVG.addEventListener("click", function(){_this.clickNode(nodeId);}, false); + // + nodeSVG.addEventListener("mouseup", function() { + _this.onVertexUp.notify(nodeId); + }, false); + } +}; + +GraphCanvas.prototype.removeNode = function(nodeId) { + DOM.select(this.getSVGNodeId(nodeId)).parentNode.removeChild(DOM.select(this.getSVGNodeId(nodeId))); + if (this.args.labeled) { + this.removeLabel(nodeId); + } +}; + +/** REMOVING **/ +GraphCanvas.prototype.removeSelected = function() { + /** El orden importa **/ + this.removeSelectedEdges(); + this.removeSelectedNode(); + +}; + +GraphCanvas.prototype.removeSelectedNode = function() { + var selected = JSON.parse(JSON.stringify(this.getSelectedVertices())); + this.deselectNodes(); + var sorted = selected.sort(function(a, b) { + return a - b + }); + for ( var i = 0; i < sorted.length; i++) { + if (this.getDataset().getVertexById(sorted[i]) != null) { + this.getDataset().getVertexById(sorted[i]).remove(); + } + } +}; + +/** EDGES **/ +GraphCanvas.prototype.removeEdge = function(edgeId) { + if (DOM.select(this.getSVGEdgeId(edgeId)) != null) { + DOM.select(this.getSVGEdgeId(edgeId)).parentNode.removeChild(DOM.select(this.getSVGEdgeId(edgeId))); + } + + if (DOM.select(this.getSVGEdgeId(edgeId) + "_shadow") != null) { + DOM.select(this.getSVGEdgeId(edgeId) + "_shadow").parentNode.removeChild(DOM.select(this.getSVGEdgeId(edgeId) + "_shadow")); + } + + if (DOM.select(this.getSVGArrowEdgeId(edgeId)) != null) { + DOM.select(this.getSVGArrowEdgeId(edgeId)).parentNode.removeChild(DOM.select(this.getSVGArrowEdgeId(edgeId))); + } +}; + +GraphCanvas.prototype.overEdge = function(edgeId) { + if ((!this.args.interactive) || this.dragging || this.selecting) { + return; + } + + /** If selected we don't change the format **/ + if (this.args.isEdgeSelected[edgeId] == null) { + var format = this.getFormatter().getEdgeById(edgeId).getOver(); + format.args["cursor"] = "pointer"; + this.changeEdgeFormat(edgeId, format); + } +}; + +GraphCanvas.prototype.outEdge = function(edgeId) { + if (!this.args.interactive) { + return; + } + + /** If selected we don't change the format **/ + if (this.args.isEdgeSelected[edgeId] == null) { + this.changeEdgeFormat(edgeId, this.getFormatter().getEdgeById(edgeId).getDefault()); + } +}; + +GraphCanvas.prototype.changeEdgeFormat = function(edgeId, format) { + var svgEdge = DOM.select(this.getSVGEdgeId(edgeId) + "_shadow"); + if (svgEdge != null) { + var properties = format.toJSON(); + for ( var item in properties) { + svgEdge.setAttribute(item, properties[item]); + } + } +}; + +GraphCanvas.prototype.deselectEdge = function(edgeID) { + if (this.args.isEdgeSelected[edgeID] != null) { + this.changeEdgeFormat(edgeID, this.getFormatter().getEdgeById(edgeID).getDefault()); + var index = this.args.isEdgeSelected[edgeID]; + delete this.args.isEdgeSelected[edgeID]; + } +}; + +GraphCanvas.prototype.deselectEdges = function() { + var selected = JSON.parse(JSON.stringify(this.getSelectedEdges())); + for ( var i = 0; i < selected.length; i++) { + this.deselectEdge(selected[i]); + } +}; + +GraphCanvas.prototype.removeSelectedEdges = function() { + var selected = JSON.parse(JSON.stringify(this.getSelectedEdges())); + this.deselectEdges(); + for ( var i = 0; i < selected.length; i++) { + if (this.getDataset().getEdgeById(selected[i]) != null) { + this.getDataset().getEdgeById(selected[i]).remove(); + } + } +}; + +GraphCanvas.prototype.renderEdge = function(edgeId) { + var svgAttributesEdge = this.getFormatter().getEdgeById(edgeId).getDefault().toJSON(); + var edge = this.getDataset().getEdgeById(edgeId); + + var svgNodeTarget = this.getVertexById(edge.getNodeTarget().getId()); + var svgNodeSource = this.getVertexById(edge.getNodeSource().getId()); + svgAttributesEdge.id = this.getSVGEdgeId(edge.getId()) + "_shadow"; + + var svgEdge = null; + + if (this.getFormatter().getEdgeById(edgeId) instanceof LineEdgeGraphFormatter) { + var coordenateSourceX = svgNodeSource.getAttribute("dragx"); + var coordenateSourceY = svgNodeSource.getAttribute("dragy"); + var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); + var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); + + SVG.drawLine(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, this.GraphEdgeGroup, svgAttributesEdge); + var attributesShadow = {}; + attributesShadow.id = this.getSVGEdgeId(edge.getId()); + attributesShadow["stroke-opacity"] = 0; + attributesShadow["stroke-width"] = 4; + attributesShadow["stroke"] = "black"; + svgEdge = SVG.drawLine(svgNodeSource.getAttribute("dragx"), svgNodeSource.getAttribute("dragy"), svgNodeTarget.getAttribute("dragx"), + svgNodeTarget.getAttribute("dragy"), this.GraphEdgeGroup, attributesShadow); + } + + if (this.getFormatter().getEdgeById(edgeId) instanceof BezierEdgeGraphFormatter) { + var nodeId = edge.getNodeTarget().getId(); + var nodeSize = this.formatter.getVertexById(nodeId).getDefault().getSize() * this.getFormatter().getNodesMaxSize(); + svgAttributesEdge.fill = "none"; + svgAttributesEdge.id = this.getSVGEdgeId(edgeId); + var d = this.calculateCoordenatesBezier(nodeSize, svgNodeSource.getAttribute("dragx"), svgNodeSource.getAttribute("dragy")); + svgEdge = SVG.drawPath(d, this.GraphEdgeGroup, svgAttributesEdge); + } + ; + + if ((this.getFormatter().getEdgeById(edgeId) instanceof DirectedLineEdgeGraphFormatter) + || (this.getFormatter().getEdgeById(edgeId) instanceof CutDirectedLineEdgeGraphFormatter) + || (this.getFormatter().getEdgeById(edgeId) instanceof DotDirectedLineEdgeGraphFormatter) + || (this.getFormatter().getEdgeById(edgeId) instanceof OdotDirectedLineEdgeGraphFormatter) + || (this.getFormatter().getEdgeById(edgeId) instanceof OdirectedLineEdgeGraphFormatter)) { + var coordenateSourceX = svgNodeSource.getAttribute("dragx"); + var coordenateSourceY = svgNodeSource.getAttribute("dragy"); + var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); + var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); + + var offset = parseFloat(this.getFormatter().getVertexById(this.getDataset().getEdgeById(edgeId).getNodeTarget().getId()).getDefault() + .getSize() + * this.circleDefaultRadius); + var point = this._calculateEdgePointerPosition(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, offset); + coordenateTargetX = point.x; + coordenateTargetY = point.y; + SVG.drawLine(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, this.GraphEdgeGroup, svgAttributesEdge); + + var attributesShadow = {}; + attributesShadow.id = this.getSVGEdgeId(edge.getId()); + attributesShadow["stroke-opacity"] = 0; + attributesShadow["stroke-width"] = 4; + attributesShadow["stroke"] = "black"; + svgEdge = SVG.drawLine(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, this.GraphEdgeGroup, attributesShadow); + } + + if (this.getFormatter().getEdgeById(edgeId) instanceof DirectedLineEdgeGraphFormatter + || (this.getFormatter().getEdgeById(edgeId) instanceof OdirectedLineEdgeGraphFormatter)) { + var coordenateSourceX = svgNodeSource.getAttribute("dragx"); + var coordenateSourceY = svgNodeSource.getAttribute("dragy"); + var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); + var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); + + var point = this._calculateEdgePointerPosition(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, offset); + coordenateTargetX = point.x; + coordenateTargetY = point.y; + + var angle = Geometry.toDegree(point.angle) + 90; + this.arrowDefaultSize = this.getFormatter().getEdgeById(edgeId).getArrowSize(); //getDefault().getArrowSize(); + var d = "-" + this.arrowDefaultSize + ",0 0,-" + parseFloat(this.arrowDefaultSize) * 2 + " " + this.arrowDefaultSize + ",0"; + + var attributes; + + if (this.getFormatter().getEdgeById(edgeId) instanceof DirectedLineEdgeGraphFormatter) { + attributes = [ + [ "fill", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], + [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], [ "id", this.getSVGArrowEdgeId(edgeId) ] ]; + } else { + attributes = [ + [ "fill", "#FFFFFF" ], [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], + [ "id", this.getSVGArrowEdgeId(edgeId) ] ]; + } + + var flechaSVGNode = SVG.drawPoligon(d, this.GraphEdgeGroup, attributes);//, ["transform", "rotate("+angle+"), translate(0,0)"]]); + flechaSVGNode.setAttribute("transform", " translate(" + coordenateTargetX + ", " + coordenateTargetY + "), rotate(" + angle + ")"); + } + ; + + if (this.getFormatter().getEdgeById(edgeId) instanceof CutDirectedLineEdgeGraphFormatter) { + var coordenateSourceX = svgNodeSource.getAttribute("dragx"); + var coordenateSourceY = svgNodeSource.getAttribute("dragy"); + var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); + var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); + + var point = this._calculateEdgePointerPosition(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, offset); + coordenateTargetX = point.x; + coordenateTargetY = point.y; + + var angle = Geometry.toDegree(point.angle) + 90; + + //this.arrowDefaultSize = 2; //getDefault().getArrowSize(); + var d = "-4,0 4,0 4,-2 -4,-2"; + + var flechaSVGNode = SVG.drawPoligon(d, this.GraphEdgeGroup, [ + [ "fill", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], + [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], [ "id", this.getSVGArrowEdgeId(edgeId) ] ]);//, ["transform", "rotate("+angle+"), translate(0,0)"]]); + flechaSVGNode.setAttribute("transform", " translate(" + coordenateTargetX + ", " + coordenateTargetY + "), rotate(" + angle + ")"); + } + ; + + if ((this.getFormatter().getEdgeById(edgeId) instanceof DotDirectedLineEdgeGraphFormatter) + || (this.getFormatter().getEdgeById(edgeId) instanceof OdotDirectedLineEdgeGraphFormatter)) { + var coordenateSourceX = svgNodeSource.getAttribute("dragx"); + var coordenateSourceY = svgNodeSource.getAttribute("dragy"); + var coordenateTargetX = svgNodeTarget.getAttribute("dragx"); + var coordenateTargetY = svgNodeTarget.getAttribute("dragy"); + var point = this._calculateEdgePointerPosition(coordenateSourceX, coordenateSourceY, coordenateTargetX, coordenateTargetY, offset); + coordenateTargetX = point.x; + coordenateTargetY = point.y; + var angle = Geometry.toDegree(point.angle) + 90; + // this.arrowDefaultSize = this.formatter.getEdgeById(edgeId).getArrowSize(); //getDefault().getArrowSize(); + var attributes = []; + if (this.getFormatter().getEdgeById(edgeId) instanceof OdotDirectedLineEdgeGraphFormatter) { + attributes = [ + [ "fill", "#FFFFFF" ], [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], + [ "id", this.getSVGArrowEdgeId(edgeId) ] ]; + } else { + attributes = [ + [ "fill", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], + [ "stroke", this.getFormatter().getEdgeById(edgeId).getDefault().getStroke() ], [ "id", this.getSVGArrowEdgeId(edgeId) ] ]; + } + var flechaSVGNode = SVG.drawCircle(0, 0, 4, this.GraphEdgeGroup, attributes); + flechaSVGNode.setAttribute("transform", " translate(" + coordenateTargetX + ", " + coordenateTargetY + "), rotate(" + angle + ")"); + } + ; + + var _this = this; + /** Events for the SVG edge **/ + if (svgEdge != null) { + if (this.getDataset().getEdgesCount() < this.args.maxNumberEdgesFiringEvents) { + svgEdge.addEventListener("mouseover", function() { + _this.overEdge(edgeId); + }, false); + svgEdge.addEventListener("mouseout", function() { + _this.outEdge(edgeId); + }, false); + } + } +}; + +GraphCanvas.prototype._calculateEdgePointerPosition = function(sourceX, sourceY, targetX, targetY, radius) { + var angle = Geometry.getAngleBetweenTwoPoints(sourceX, sourceY, targetX, targetY); + + /** Suponiendo el node source que este a la derecha **/ + if ((targetX - sourceX) < 0) { + var b = Geometry.getAdjacentSideOfRectangleRight(angle, radius); + targetX = parseFloat(targetX) + parseFloat(b); + arrowX = parseFloat(targetX) + parseFloat(b) + this.arrowDefaultSize / 2; + } else { + var b = Geometry.getAdjacentSideOfRectangleRight(angle, radius); + targetX = parseFloat(targetX) - parseFloat(b); + arrowX = parseFloat(targetX) - parseFloat(b) - this.arrowDefaultSize / 2; + } + + /** Suponiendo el node source que este a la arriba **/ + if ((targetY - sourceY) > 0) { + var a = Geometry.getOppositeSideOfRectangleRight(angle, radius); + targetY = parseFloat(targetY) - parseFloat(a); + arrowY = parseFloat(targetY) - parseFloat(a) - this.arrowDefaultSize / 2; + } else { + var a = Geometry.getOppositeSideOfRectangleRight(angle, radius); + targetY = parseFloat(targetY) + parseFloat(a); + arrowY = parseFloat(targetY) + parseFloat(a) - this.arrowDefaultSize / 2; + + } + + return { + "x" : arrowX, + "y" : arrowY, + "angle" : angle + }; +}; + +GraphCanvas.prototype.calculateCoordenatesBezier = function(nodeSize, x1, y1) { + var x11 = x1 - (nodeSize / 2); + var y11 = y1 - (nodeSize / 2); + + var x12 = parseFloat(x1) + parseFloat(nodeSize / 2); + var y12 = y1 - (nodeSize / 2); + + var curvePointX = (x12 - x11) / 2 + x11; + var curvePointY = y1 - (nodeSize * 2); + var d = "M" + x11 + "," + y11 + " T" + curvePointX + "," + curvePointY + " " + x12 + "," + y12; + return d; + +}; + +GraphCanvas.prototype.renderEdges = function() { + for ( var edge in this.getDataset().getEdges()) { + this.renderEdge(this.getDataset().getEdgeById(edge).getId()); + + } +}; + +GraphCanvas.prototype.getLastSelectedNode = function() { + var node = null; + if (this.getSelectedVertices().length > 0) { + var nodeId = this.getSelectedVertices()[this.getSelectedVertices().length - 1]; + node = this.getDataset().getVertexById(nodeId); + } + return node; +}; +/* + GraphCanvas.prototype.getNodeByNameAndIndex = function(node, index){ + var nodeId = this.getDataset().verticesIndex[node][index]; + var nodeItem = this.getDataset().getVertexById(nodeId); + return nodeItem; + }; + */ + +GraphCanvas.prototype.setDataset = function(dataset) { + this.dataset = dataset; +}; + +GraphCanvas.prototype.setFormatter = function(formatter) { + this.formatter = formatter; +}; + +GraphCanvas.prototype.setLayout = function(layout) { + this.layout = layout; +}; + +/** API **/ +GraphCanvas.prototype.getDataset = function() { + return this.dataset; +}; + +GraphCanvas.prototype.getFormatter = function() { + return this.formatter; +}; + +GraphCanvas.prototype.getLayout = function() { + return this.layout; +}; + +/** API DATASET **/ +GraphCanvas.prototype.addVertex = function(name, args) { + this.getDataset().addNode(name, args); +}; + +GraphCanvas.prototype.removeVertex = function(vertexId) { + this.getDataset().getVertexById(vertexId).remove(); +}; + +GraphCanvas.prototype.addEdge = function(edgeName, nodeSourceId, nodeTargetId, args) { + this.getDataset().addEdge(edgeName, nodeSourceId, nodeTargetId, args); +}; +/* + GraphCanvas.prototype.removeEdge = function(edgeId){ + this.getDataset().getEdgeById(edgeId).remove(); + }; + */ + +/** API FORMATTER **/ +GraphCanvas.prototype.getWidth = function() { + return this.getFormatter().getWidth(); +}; + +GraphCanvas.prototype.getHeight = function() { + return this.getFormatter().getHeight(); +}; + +GraphCanvas.prototype.getBackgroundImage = function() { + return this.getFormatter().getBackgroundImage(); +}; + +//GraphCanvas.prototype.setBackgroundImage = function(value){ +// this.getFormatter().setBackgroundImage(value); +//}; + +GraphCanvas.prototype.getBackgroundColor = function() { + return this.getFormatter().getBackgroundColor(); +}; + +GraphCanvas.prototype.setBackgroundColor = function() { + this.getFormatter().setBackgroundColor(value); +}; + +//GraphCanvas.prototype.setEdgeFill = function(edgeId, value){ +// this.getFormatter().getEdgeById(edgeId).getDefault().setFill(value); +//}; +// +//GraphCanvas.prototype.getEdgeFill = function(edgeId){ +// return this.getFormatter().getEdgeById(edgeId).getDefault().getFill(); +//}; + +/** VERTICES FORMATTER **/ +GraphCanvas.prototype.setVertexSize = function(vertexId, value) { + this.getFormatter().getVertexById(vertexId).getDefault().setSize(value); +}; + +GraphCanvas.prototype.getVertexSize = function(vertexId) { + return this.getFormatter().getVertexById(vertexId).getDefault().getSize(); +}; + +GraphCanvas.prototype.setVertexStroke = function(vertexId, value) { + this.getFormatter().getVertexById(vertexId).getDefault().setStroke(value); +}; + +GraphCanvas.prototype.getVertexStroke = function(vertexId) { + return this.getFormatter().getVertexById(vertexId).getDefault().getStroke(); +}; + +GraphCanvas.prototype.setVertexStrokeOpacity = function(vertexId, value) { + this.getFormatter().getVertexById(vertexId).getDefault().setStrokeOpacity(value); +}; + +GraphCanvas.prototype.getVertexStrokeOpacity = function(vertexId) { + return this.getFormatter().getVertexById(vertexId).getDefault().getStrokeOpacity(); +}; + +GraphCanvas.prototype.setVertexOpacity = function(vertexId, value) { + this.getFormatter().getVertexById(vertexId).getDefault().setOpacity(value); +}; + +GraphCanvas.prototype.getVertexOpacity = function(vertexId) { + return this.getFormatter().getVertexById(vertexId).getDefault().getOpacity(); +}; + +GraphCanvas.prototype.setVertexFill = function(vertexId, color) { + this.getFormatter().getVertexById(vertexId).getDefault().setFill(color); +}; + +GraphCanvas.prototype.getVertexFill = function(vertexId) { + return this.getFormatter().getVertexById(vertexId).getDefault().getFill(); +}; + +/** EDGES FORMATTER **/ +GraphCanvas.prototype.setEdgeSize = function(edgeId, value) { + this.getFormatter().getEdgeById(edgeId).getDefault().setSize(value); +}; + +GraphCanvas.prototype.getEdgeSize = function(edgeId) { + return this.getFormatter().getEdgeById(edgeId).getDefault().getSize(); +}; + +GraphCanvas.prototype.setEdgeStroke = function(edgeId, value) { + this.getFormatter().getEdgeById(edgeId).getDefault().setStroke(value); +}; + +GraphCanvas.prototype.getEdgeStroke = function(edgeId) { + return this.getFormatter().getEdgeById(edgeId).getDefault().getStroke(); +}; + +GraphCanvas.prototype.setEdgeStrokeOpacity = function(edgeId, value) { + this.getFormatter().getEdgeById(edgeId).getDefault().setStrokeOpacity(value); +}; + +GraphCanvas.prototype.getEdgeStrokeOpacity = function(edgeId) { + return this.getFormatter().getEdgeById(edgeId).getDefault().getStrokeOpacity(); +}; + +GraphCanvas.prototype.setEdgeFill = function(edgeId, color) { + this.getFormatter().getEdgeById(edgeId).getDefault().setFill(color); +}; + +GraphCanvas.prototype.getEdgeFill = function(edgeId) { + return this.getFormatter().getEdgeById(edgeId).getDefault().getFill(); +}; + +/** API LAYOUT **/ +GraphCanvas.prototype.setCoordinates = function(vertexId, x, y) { + return this.getLayout().getEdgeById(vertexId).setCoordinates(x, y); +}; @@ -14339,283 +14339,283 @@ MergesHPLCGraph.prototype.getMenu = function () { } }); - return actions; + return actions; +}; + + +MergesHPLCGraph.prototype.input = function () { + return DATADOC.getScatteringHPLCFrameData(); +}; + +MergesHPLCGraph.prototype.test = function (targetId) { + var mainPlotPanel = new MergesHPLCGraph({ + title : 'Scattering', + width : this.plotWidth, + height : 500, + showRangeSelector : false, + xParam : 0, + xlabel : "scattering_I", + plots : { + "scattering_I" : true, + "subtracted_I" : true, + "buffer_I" : true + } + }); + mainPlotPanel.getPanel().render(targetId); + mainPlotPanel.loadData(mainPlotPanel.input()); +}; + + +function NetworkWidget(args) { + this.id = "NetworkViewer_" + Math.random().toString().replace(".", "_"); + + this.label = true; + if (args != null) { + if (args.targetId != null) { + this.targetId = args.targetId; + } + if (args.label != null) { + this.label = args.label; + } + } + + this.onVertexOver = new Event(this); + this.onVertexOut = new Event(this); +} + +NetworkWidget.prototype.draw = function(dataset, formatter, layout) { + + this.graphCanvas = new GraphCanvas(this.id, document.getElementById(this.targetId), { + "labeled" : this.label, + "multipleSelectionEnabled" : false, + "draggingCanvasEnabled" : false + }); + this.graphCanvas.draw(dataset, formatter, layout); + + var _this = this; + this.graphCanvas.onVertexOver.attach(function(sender, nodeId) { + _this.onVertexOver.notify(nodeId); + }); + + this.graphCanvas.onVertexOut.attach(function(sender, nodeId) { + _this.onVertexOut.notify(nodeId); + }); +}; + +/** SELECT VERTICES BY NAME * */ +NetworkWidget.prototype.selectVertexByName = function(vertexName) { + var vertices = this.getDataset().getVertexByName(vertexName); + if (vertices != null) { + for ( var nodeId in vertices) { + if (vertices.hasOwnProperty(nodeId)) { + var vertexId = vertices[nodeId].getId(); + this.selectVertexById(vertexId); + } + } + } +}; + +NetworkWidget.prototype.selectVerticesByName = function(verticesName) { + for ( var i = 0; i < verticesName.length; i++) { + this.selectVertexByName(verticesName[i]); + } +}; + +/** SELECT VERTICES BY ID * */ +NetworkWidget.prototype.selectVertexById = function(vertexId) { + this.graphCanvas.selectNode(vertexId); + this.blinkVertexById(vertexId); +}; + +NetworkWidget.prototype.selectVerticesById = function(verticesId) { + for ( var i = 0; i < verticesId.length; i++) { + this.selectVertexById(verticesId[i]); + } +}; + +/** VECINDARIO * */ +NetworkWidget.prototype.selectNeighbourhood = function() { + this.selectEdgesFromVertices(); + this.selectAdjacent(); +}; + +/** DESELECT * */ +NetworkWidget.prototype.deselectNodes = function() { + this.graphCanvas.deselectNodes(); +}; + +/** SELECT ALL NODES * */ +NetworkWidget.prototype.selectAllNodes = function() { + this.getGraphCanvas().selectAllNodes(); +}; + +/** SELECT EVERYTHING * */ +NetworkWidget.prototype.selectAll = function() { + this.getGraphCanvas().selectAll(); +}; + +/** SELECT ALL EDGES * */ +NetworkWidget.prototype.selectAllEdges = function() { + this.getGraphCanvas().selectAllEdges(); +}; + +/** ZOOM * */ +NetworkWidget.prototype.setScale = function(value) { + this.graphCanvas.setScale(value); +}; + +NetworkWidget.prototype.getScale = function() { + return this.graphCanvas.getScale(value); +}; + +/** SELECT ADJACENT VERTICES FROM SELECTED VERTICES * */ +NetworkWidget.prototype.selectAdjacent = function() { + var selectedVertices = this.getGraphCanvas().getSelectedVertices(); + var edges = []; + for ( var i = 0; i < selectedVertices.length; i++) { + edges = edges.concat(this.getGraphCanvas().getDataset().getVertexById(selectedVertices[i]).getEdges()); + } + var vertices = []; + for ( i = 0; i < edges.length; i++) { + vertices.push(edges[i].getNodeSource().getId()); + vertices.push(edges[i].getNodeTarget().getId()); + } + + this.selectVerticesById(vertices); +}; + +/** SELECT EDGES FROM SELECTED VERTICES * */ +NetworkWidget.prototype.selectEdgesFromVertices = function() { + var selectedVertices = this.getGraphCanvas().getSelectedVertices(); + var edges = []; + for ( var i = 0; i < selectedVertices.length; i++) { + edges = edges.concat(this.getGraphCanvas().getDataset().getVertexById(selectedVertices[i]).getEdges()); + } + var edgesId = []; + for ( i = 0; i < edges.length; i++) { + edgesId.push(edges[i].getId()); + } + this.getGraphCanvas().selectEdges(edgesId); +}; + +/** BLINKING * */ +NetworkWidget.prototype.blinkVertexById = function(vertexId) { + this.graphCanvas.blinkVertexById(vertexId); +}; + +/** COMPONENTE CONEXA DE LOS NODOS SELECCIONADOS * */ +NetworkWidget.prototype.selectConnectedComponent = function() { + var elements = this.getConnectedComponent(); + this.selectVerticesById(elements.nodes); + this.graphCanvas.selectEdges(elements.edges); +}; + +NetworkWidget.prototype.getConnectedComponent = function() { + var nodosVisitados = {}; + var aristasVisitadas = {}; + var arrNodos = []; + var arrAristas = []; + var selectedGraphNodesId = this.getGraphCanvas().getSelectedVertices(); + for ( var i = 0; i < selectedGraphNodesId.length; i++) { + this.visitNode(selectedGraphNodesId[i], nodosVisitados, aristasVisitadas, arrNodos, arrAristas); + } + return { + nodes : arrNodos, + edges : arrAristas + }; +}; + +NetworkWidget.prototype.visitNode = function(nodeId, nodosVisitados, aristasVisitadas, arrNodos, arrAristas) { + nodosVisitados[nodeId] = true; + arrNodos.push(nodeId); + var nodeEdges = this.getDataset().getVertexById(nodeId).getEdges(); + for ( var j = 0; j < nodeEdges.length; j++) { + var edge = nodeEdges[j]; + var edgeId = edge.getId(); + if (aristasVisitadas[edgeId] == null) { + aristasVisitadas[edgeId] = true; + arrAristas.push(edgeId); + var nodeTargetId = edge.getNodeTarget().getId(); + if (nodosVisitados[nodeTargetId] == null) { + this.visitNode(nodeTargetId, nodosVisitados, aristasVisitadas, arrNodos, arrAristas); + } + var nodeSourceId = edge.getNodeSource().getId(); + if (nodosVisitados[nodeSourceId] == null) { + this.visitNode(nodeSourceId, nodosVisitados, aristasVisitadas, arrNodos, arrAristas); + } + } + } +}; + +/** COLLAPSE SELECTED VERTICES * */ +NetworkWidget.prototype.collapse = function() { + var selectedVertices = this.getGraphCanvas().getSelectedVertices(); + var xMin = -Infinity; + var xMax = Infinity; + var yMin = -Infinity; + var yMax = Infinity; + + for ( var i = 0; i < selectedVertices.length; i++) { + var vertex = this.getGraphCanvas().getLayout().getNodeById(selectedVertices[i]); + if (xMin < vertex.x) { + xMin = vertex.x; + } + if (xMax > vertex.x) { + xMax = vertex.x; + } + if (yMin < vertex.y) { + yMin = vertex.y; + } + if (yMax > vertex.y) { + yMax = vertex.y; + } + } + + var centerX = xMin - xMax; + var centerY = yMin - yMax; + var radius = (xMax - xMin) / 4; + + var count = selectedVertices.length; + var verticesCoordinates = []; + + for ( i = 0; i < selectedVertices.length; i++) { + x = centerX + radius * Math.sin(i * 2 * Math.PI / count); + y = centerY + radius * Math.cos(i * 2 * Math.PI / count); + verticesCoordinates.push({ + 'x' : x, + 'y' : y + }); + } + + for ( i = 0; i < selectedVertices.length; i++) { + this.getGraphCanvas().getLayout().getNodeById(selectedVertices[i]).setCoordinates(verticesCoordinates[i].x, verticesCoordinates[i].y); + } }; +/** SETTER FONT SIZE * */ +NetworkWidget.prototype.setVerticesFontSize = function(value) { + for ( var nodeId in this.getDataset().getVertices()) { + if (this.getDataset().getVertices().hasOwnProperty(nodeId)) { + this.getFormatter().getVertexById(nodeId).getDefault().setFontSize(value); + } + } +}; -MergesHPLCGraph.prototype.input = function () { - return DATADOC.getScatteringHPLCFrameData(); +/** GETTERS * */ +NetworkWidget.prototype.getFormatter = function() { + return this.getGraphCanvas().getFormatter(); +}; +NetworkWidget.prototype.getLayout = function() { + return this.getGraphCanvas().getLayout(); }; -MergesHPLCGraph.prototype.test = function (targetId) { - var mainPlotPanel = new MergesHPLCGraph({ - title : 'Scattering', - width : this.plotWidth, - height : 500, - showRangeSelector : false, - xParam : 0, - xlabel : "scattering_I", - plots : { - "scattering_I" : true, - "subtracted_I" : true, - "buffer_I" : true - } - }); - mainPlotPanel.getPanel().render(targetId); - mainPlotPanel.loadData(mainPlotPanel.input()); +NetworkWidget.prototype.getDataset = function() { + return this.getGraphCanvas().getDataset(); }; - -function NetworkWidget(args) { - this.id = "NetworkViewer_" + Math.random().toString().replace(".", "_"); - - this.label = true; - if (args != null) { - if (args.targetId != null) { - this.targetId = args.targetId; - } - if (args.label != null) { - this.label = args.label; - } - } - - this.onVertexOver = new Event(this); - this.onVertexOut = new Event(this); -} - -NetworkWidget.prototype.draw = function(dataset, formatter, layout) { - - this.graphCanvas = new GraphCanvas(this.id, document.getElementById(this.targetId), { - "labeled" : this.label, - "multipleSelectionEnabled" : false, - "draggingCanvasEnabled" : false - }); - this.graphCanvas.draw(dataset, formatter, layout); - - var _this = this; - this.graphCanvas.onVertexOver.attach(function(sender, nodeId) { - _this.onVertexOver.notify(nodeId); - }); - - this.graphCanvas.onVertexOut.attach(function(sender, nodeId) { - _this.onVertexOut.notify(nodeId); - }); -}; - -/** SELECT VERTICES BY NAME * */ -NetworkWidget.prototype.selectVertexByName = function(vertexName) { - var vertices = this.getDataset().getVertexByName(vertexName); - if (vertices != null) { - for ( var nodeId in vertices) { - if (vertices.hasOwnProperty(nodeId)) { - var vertexId = vertices[nodeId].getId(); - this.selectVertexById(vertexId); - } - } - } -}; - -NetworkWidget.prototype.selectVerticesByName = function(verticesName) { - for ( var i = 0; i < verticesName.length; i++) { - this.selectVertexByName(verticesName[i]); - } -}; - -/** SELECT VERTICES BY ID * */ -NetworkWidget.prototype.selectVertexById = function(vertexId) { - this.graphCanvas.selectNode(vertexId); - this.blinkVertexById(vertexId); -}; - -NetworkWidget.prototype.selectVerticesById = function(verticesId) { - for ( var i = 0; i < verticesId.length; i++) { - this.selectVertexById(verticesId[i]); - } -}; - -/** VECINDARIO * */ -NetworkWidget.prototype.selectNeighbourhood = function() { - this.selectEdgesFromVertices(); - this.selectAdjacent(); -}; - -/** DESELECT * */ -NetworkWidget.prototype.deselectNodes = function() { - this.graphCanvas.deselectNodes(); -}; - -/** SELECT ALL NODES * */ -NetworkWidget.prototype.selectAllNodes = function() { - this.getGraphCanvas().selectAllNodes(); -}; - -/** SELECT EVERYTHING * */ -NetworkWidget.prototype.selectAll = function() { - this.getGraphCanvas().selectAll(); -}; - -/** SELECT ALL EDGES * */ -NetworkWidget.prototype.selectAllEdges = function() { - this.getGraphCanvas().selectAllEdges(); -}; - -/** ZOOM * */ -NetworkWidget.prototype.setScale = function(value) { - this.graphCanvas.setScale(value); -}; - -NetworkWidget.prototype.getScale = function() { - return this.graphCanvas.getScale(value); -}; - -/** SELECT ADJACENT VERTICES FROM SELECTED VERTICES * */ -NetworkWidget.prototype.selectAdjacent = function() { - var selectedVertices = this.getGraphCanvas().getSelectedVertices(); - var edges = []; - for ( var i = 0; i < selectedVertices.length; i++) { - edges = edges.concat(this.getGraphCanvas().getDataset().getVertexById(selectedVertices[i]).getEdges()); - } - var vertices = []; - for ( i = 0; i < edges.length; i++) { - vertices.push(edges[i].getNodeSource().getId()); - vertices.push(edges[i].getNodeTarget().getId()); - } - - this.selectVerticesById(vertices); -}; - -/** SELECT EDGES FROM SELECTED VERTICES * */ -NetworkWidget.prototype.selectEdgesFromVertices = function() { - var selectedVertices = this.getGraphCanvas().getSelectedVertices(); - var edges = []; - for ( var i = 0; i < selectedVertices.length; i++) { - edges = edges.concat(this.getGraphCanvas().getDataset().getVertexById(selectedVertices[i]).getEdges()); - } - var edgesId = []; - for ( i = 0; i < edges.length; i++) { - edgesId.push(edges[i].getId()); - } - this.getGraphCanvas().selectEdges(edgesId); -}; - -/** BLINKING * */ -NetworkWidget.prototype.blinkVertexById = function(vertexId) { - this.graphCanvas.blinkVertexById(vertexId); -}; - -/** COMPONENTE CONEXA DE LOS NODOS SELECCIONADOS * */ -NetworkWidget.prototype.selectConnectedComponent = function() { - var elements = this.getConnectedComponent(); - this.selectVerticesById(elements.nodes); - this.graphCanvas.selectEdges(elements.edges); -}; - -NetworkWidget.prototype.getConnectedComponent = function() { - var nodosVisitados = {}; - var aristasVisitadas = {}; - var arrNodos = []; - var arrAristas = []; - var selectedGraphNodesId = this.getGraphCanvas().getSelectedVertices(); - for ( var i = 0; i < selectedGraphNodesId.length; i++) { - this.visitNode(selectedGraphNodesId[i], nodosVisitados, aristasVisitadas, arrNodos, arrAristas); - } - return { - nodes : arrNodos, - edges : arrAristas - }; -}; - -NetworkWidget.prototype.visitNode = function(nodeId, nodosVisitados, aristasVisitadas, arrNodos, arrAristas) { - nodosVisitados[nodeId] = true; - arrNodos.push(nodeId); - var nodeEdges = this.getDataset().getVertexById(nodeId).getEdges(); - for ( var j = 0; j < nodeEdges.length; j++) { - var edge = nodeEdges[j]; - var edgeId = edge.getId(); - if (aristasVisitadas[edgeId] == null) { - aristasVisitadas[edgeId] = true; - arrAristas.push(edgeId); - var nodeTargetId = edge.getNodeTarget().getId(); - if (nodosVisitados[nodeTargetId] == null) { - this.visitNode(nodeTargetId, nodosVisitados, aristasVisitadas, arrNodos, arrAristas); - } - var nodeSourceId = edge.getNodeSource().getId(); - if (nodosVisitados[nodeSourceId] == null) { - this.visitNode(nodeSourceId, nodosVisitados, aristasVisitadas, arrNodos, arrAristas); - } - } - } -}; - -/** COLLAPSE SELECTED VERTICES * */ -NetworkWidget.prototype.collapse = function() { - var selectedVertices = this.getGraphCanvas().getSelectedVertices(); - var xMin = -Infinity; - var xMax = Infinity; - var yMin = -Infinity; - var yMax = Infinity; - - for ( var i = 0; i < selectedVertices.length; i++) { - var vertex = this.getGraphCanvas().getLayout().getNodeById(selectedVertices[i]); - if (xMin < vertex.x) { - xMin = vertex.x; - } - if (xMax > vertex.x) { - xMax = vertex.x; - } - if (yMin < vertex.y) { - yMin = vertex.y; - } - if (yMax > vertex.y) { - yMax = vertex.y; - } - } - - var centerX = xMin - xMax; - var centerY = yMin - yMax; - var radius = (xMax - xMin) / 4; - - var count = selectedVertices.length; - var verticesCoordinates = []; - - for ( i = 0; i < selectedVertices.length; i++) { - x = centerX + radius * Math.sin(i * 2 * Math.PI / count); - y = centerY + radius * Math.cos(i * 2 * Math.PI / count); - verticesCoordinates.push({ - 'x' : x, - 'y' : y - }); - } - - for ( i = 0; i < selectedVertices.length; i++) { - this.getGraphCanvas().getLayout().getNodeById(selectedVertices[i]).setCoordinates(verticesCoordinates[i].x, verticesCoordinates[i].y); - } -}; - -/** SETTER FONT SIZE * */ -NetworkWidget.prototype.setVerticesFontSize = function(value) { - for ( var nodeId in this.getDataset().getVertices()) { - if (this.getDataset().getVertices().hasOwnProperty(nodeId)) { - this.getFormatter().getVertexById(nodeId).getDefault().setFontSize(value); - } - } -}; - -/** GETTERS * */ -NetworkWidget.prototype.getFormatter = function() { - return this.getGraphCanvas().getFormatter(); -}; -NetworkWidget.prototype.getLayout = function() { - return this.getGraphCanvas().getLayout(); -}; - -NetworkWidget.prototype.getDataset = function() { - return this.getGraphCanvas().getDataset(); -}; - -NetworkWidget.prototype.getGraphCanvas = function() { - return this.graphCanvas; -}; +NetworkWidget.prototype.getGraphCanvas = function() { + return this.graphCanvas; +}; RangeWhiskerGraph.prototype.cleanArray = GenericGraph.prototype.cleanArray; RangeWhiskerGraph.prototype.plotAxes = GenericGraph.prototype.plotAxes; @@ -14883,280 +14883,280 @@ RangeWhiskerGraph.prototype.plotWhisters = function(data, properties) { } } } - } - -}; - -RangeWhiskerGraph.prototype.draw = function(targetId, data) { - //this.calculate(data); - this.targetId = targetId; - var properties = (this.getDimensions(data)); - this.svg = SVG.createSVGCanvas(document.getElementById(this.targetId), [ [ "width", this.width ], [ "height", this.height ] ]); - this.plotAxes(properties); - this.plotWhisters(data, properties); -}; - -RangeWhiskerGraph.prototype.input = function() { - return DATADOC.getBoxWhikerData(); -}; - -RangeWhiskerGraph.prototype.test = function(targetId) { - var plot = new RangeWhiskerGraph({ - targetId : targetId, - height : 350, - width : 450, - maxBoxWidth : 25 - }); - plot.refresh(this.input()); -}; - -StdDevDyGraph.prototype.dblclick = DygraphWidget.prototype.dblclick; -StdDevDyGraph.prototype._createHTLMWrapper = DygraphWidget.prototype._createHTLMWrapper; -StdDevDyGraph.prototype.draw = DygraphWidget.prototype.draw; - -function StdDevDyGraph(targetId, args) { - this.scaled = false; - if (args == null) { - args = {}; - } - args.customBars = true; - DygraphWidget.prototype.constructor.call(this, targetId, args); -} - -StdDevDyGraph.prototype.input = function () { - return { - data : [ [ 1, [ 2, 3, 3.5 ], [ 4, 4.2, 5 ] ], [ 2, [ 5, 5.5, 5.7 ], [ 4, 4.2, 5 ] ] ], - colors : [ "blue", "red" ], - labels : [ "", 'data1', 'data2' ] - }; -}; - -StdDevDyGraph.prototype.test = function (targetId) { - var dygraphObject = new StdDevDyGraph(targetId, { - width : 500, - height : 400, - xlabel : "xLabel", - showRangeSelector : false + } + +}; + +RangeWhiskerGraph.prototype.draw = function(targetId, data) { + //this.calculate(data); + this.targetId = targetId; + var properties = (this.getDimensions(data)); + this.svg = SVG.createSVGCanvas(document.getElementById(this.targetId), [ [ "width", this.width ], [ "height", this.height ] ]); + this.plotAxes(properties); + this.plotWhisters(data, properties); +}; + +RangeWhiskerGraph.prototype.input = function() { + return DATADOC.getBoxWhikerData(); +}; + +RangeWhiskerGraph.prototype.test = function(targetId) { + var plot = new RangeWhiskerGraph({ + targetId : targetId, + height : 350, + width : 450, + maxBoxWidth : 25 + }); + plot.refresh(this.input()); +}; + +StdDevDyGraph.prototype.dblclick = DygraphWidget.prototype.dblclick; +StdDevDyGraph.prototype._createHTLMWrapper = DygraphWidget.prototype._createHTLMWrapper; +StdDevDyGraph.prototype.draw = DygraphWidget.prototype.draw; + +function StdDevDyGraph(targetId, args) { + this.scaled = false; + if (args == null) { + args = {}; + } + args.customBars = true; + DygraphWidget.prototype.constructor.call(this, targetId, args); +} + +StdDevDyGraph.prototype.input = function () { + return { + data : [ [ 1, [ 2, 3, 3.5 ], [ 4, 4.2, 5 ] ], [ 2, [ 5, 5.5, 5.7 ], [ 4, 4.2, 5 ] ] ], + colors : [ "blue", "red" ], + labels : [ "", 'data1', 'data2' ] + }; +}; + +StdDevDyGraph.prototype.test = function (targetId) { + var dygraphObject = new StdDevDyGraph(targetId, { + width : 500, + height : 400, + xlabel : "xLabel", + showRangeSelector : false + }); + + dygraphObject.draw(dygraphObject.input().data, dygraphObject.input().colors, dygraphObject.input().labels); +}; + + + +function AbinitioGrid(args) { + this.height = null; + this.width = null; + this.id = BUI.id(); + + if (args != null) { + if (args.height != null) { + this.height = args.height; + + if (args.width != null) { + this.width = args.width; + } + } + } + + this.onSelected = new Event(this); +}; + + +AbinitioGrid.prototype.refresh = function(subtractions){ + this.store.loadData(this._prepareData(subtractions)); +}; + +AbinitioGrid.prototype._prepareData = function(subtractions){ + /** Parsing data * */ + var models = []; + for (var l = 0; l < subtractions.length; l++) { + var subtraction = subtractions[l]; + for (var k = 0; k < subtraction.substractionToAbInitioModel3VOs.length; k++) { + var data = subtraction.substractionToAbInitioModel3VOs[k].abinitiomodel3VO; + if (data.averagedModel != null) { + models.push(data.averagedModel); + models[models.length - 1].type = "Reference"; + } + + if (data.shapeDeterminationModel != null) { + models.push(data.shapeDeterminationModel); + models[models.length - 1].type = "Refined"; + } + + if (data.modelList3VO != null) { + if (data.modelList3VO.modeltolist3VOs != null) { + for (var i = 0; i < data.modelList3VO.modeltolist3VOs.length; i++) { + models.push(data.modelList3VO.modeltolist3VOs[i].model3VO); + models[models.length - 1].type = "Model"; + } + } + } + } + } + return models; +}; + +AbinitioGrid.prototype.getPanel = function(){ + var _this = this; + + + var modelFields = [ "modelId", "type", "chiSqrt", "dmax", "firFile", "logFile", "fitFile", "pdbFile", "rfactor", "rg", "volume" ]; + Ext.define('AbinitioModel', { + extend : 'Ext.data.Model', + fields : modelFields + + }); + + /** + * Store in Memory + */ + this.store = Ext.create('Ext.data.Store', { + model : 'AbinitioModel', + autoload : true, + groupField : 'type' + }); + + + var groupingFeature = Ext.create('Ext.grid.feature.Grouping',{ + groupHeaderTpl: '{name} ({rows.length} model{[values.rows.length > 1 ? "s" : ""]})', + startCollapsed: true, + collapsible : true + }); + + this.grid = Ext.create('Ext.grid.Panel', { + collapsible : false, + resizable : true, + features: [groupingFeature], + autoscroll : true, + multiSelect : true, + store : this.store, + height : this.height, + width : this.width, + margin : 10, + columns : [ { + text : "Type", + dataindex : "type", + hidden : true, + renderer : function(a, b, record) { + return record.data.type; + }, + flex : 1 + }, + { + text : "ModelId", + dataindex : "modelId", + hidden : true, + renderer : function(a, b, record) { + return record.data.modelId; + + }, + flex : 1 + }, + + { + text : "chiSqrt", + dataindex : "chiSqrt", + renderer : function(a, b, record) { + if (record.data.dmax != null) { + return BUI.formatValuesUnits(record.data.chiSqrt, "", 12, this.decimals); + } + + }, + flex : 1 + }, + { + text : "Dmax", + dataindex : "dmax", + renderer : function(a, b, record) { + if (record.data.dmax != null) { + return BUI.formatValuesUnits(record.data.dmax, "nm", 12, this.decimals); + } + + }, + flex : 1 + }, { + text : "rFactor", + dataindex : "rfactor", + hidden : true, + renderer : function(a, b, record) { + if (record.data.rfactor != null) { + return record.data.rfactor; + } + }, + flex : 1 + }, { + text : "Rg", + dataindex : "rg", + renderer : function(a, b, record) { + if (record.data.rg != null) { + return BUI.formatValuesUnits(record.data.rg, "nm", 12, this.decimals); + } + + }, + flex : 1 + }, + { + text : "Volume", + dataindex : "volume", + renderer : function(a, b, record) { + if (record.raw.volume != null){ + return BUI.formatValuesUnits(record.raw.volume, '') + " nm3"; + } + }, + flex : 1 + }, + { + text : "PDB", + dataindex : "pdbFile", + renderer : function(a, b, record) { + if (record.data.pdbFile != null){ + return record.data.pdbFile.split("/")[record.data.pdbFile.split("/").length - 1]; + } + }, + flex : 1 + }, { + text : "Fir", + dataindex : "firFile", + renderer : function(a, b, record) { + if (record.data.firFile != null){ + return record.data.firFile.split("/")[record.data.firFile.split("/").length - 1]; + } + }, + flex : 1 + }, { + text : "LOG", + dataindex : "logFile", + hidden : true, + renderer : function(a, b, record) { + if (record.data.logFile != null){ + return record.data.logFile.split("/")[record.data.logFile.split("/").length - 1]; + } + }, + flex : 1 + } + ], + viewConfig : { + enableTextSelection : true, + preserveScrollOnRefresh : true, + stripeRows : true, + listeners : { + 'celldblclick' : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + }, + 'cellclick' : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + var models = []; + for (var i = 0; i < grid.getSelectionModel().selected.items.length; i++) { + models.push(grid.getSelectionModel().selected.items[i].raw); + } + _this.onSelected.notify(models); + } + } + } }); - - dygraphObject.draw(dygraphObject.input().data, dygraphObject.input().colors, dygraphObject.input().labels); + return this.grid; + }; - - -function AbinitioGrid(args) { - this.height = null; - this.width = null; - this.id = BUI.id(); - - if (args != null) { - if (args.height != null) { - this.height = args.height; - - if (args.width != null) { - this.width = args.width; - } - } - } - - this.onSelected = new Event(this); -}; - - -AbinitioGrid.prototype.refresh = function(subtractions){ - this.store.loadData(this._prepareData(subtractions)); -}; - -AbinitioGrid.prototype._prepareData = function(subtractions){ - /** Parsing data * */ - var models = []; - for (var l = 0; l < subtractions.length; l++) { - var subtraction = subtractions[l]; - for (var k = 0; k < subtraction.substractionToAbInitioModel3VOs.length; k++) { - var data = subtraction.substractionToAbInitioModel3VOs[k].abinitiomodel3VO; - if (data.averagedModel != null) { - models.push(data.averagedModel); - models[models.length - 1].type = "Reference"; - } - - if (data.shapeDeterminationModel != null) { - models.push(data.shapeDeterminationModel); - models[models.length - 1].type = "Refined"; - } - - if (data.modelList3VO != null) { - if (data.modelList3VO.modeltolist3VOs != null) { - for (var i = 0; i < data.modelList3VO.modeltolist3VOs.length; i++) { - models.push(data.modelList3VO.modeltolist3VOs[i].model3VO); - models[models.length - 1].type = "Model"; - } - } - } - } - } - return models; -}; - -AbinitioGrid.prototype.getPanel = function(){ - var _this = this; - - - var modelFields = [ "modelId", "type", "chiSqrt", "dmax", "firFile", "logFile", "fitFile", "pdbFile", "rfactor", "rg", "volume" ]; - Ext.define('AbinitioModel', { - extend : 'Ext.data.Model', - fields : modelFields - - }); - - /** - * Store in Memory - */ - this.store = Ext.create('Ext.data.Store', { - model : 'AbinitioModel', - autoload : true, - groupField : 'type' - }); - - - var groupingFeature = Ext.create('Ext.grid.feature.Grouping',{ - groupHeaderTpl: '{name} ({rows.length} model{[values.rows.length > 1 ? "s" : ""]})', - startCollapsed: true, - collapsible : true - }); - - this.grid = Ext.create('Ext.grid.Panel', { - collapsible : false, - resizable : true, - features: [groupingFeature], - autoscroll : true, - multiSelect : true, - store : this.store, - height : this.height, - width : this.width, - margin : 10, - columns : [ { - text : "Type", - dataindex : "type", - hidden : true, - renderer : function(a, b, record) { - return record.data.type; - }, - flex : 1 - }, - { - text : "ModelId", - dataindex : "modelId", - hidden : true, - renderer : function(a, b, record) { - return record.data.modelId; - - }, - flex : 1 - }, - - { - text : "chiSqrt", - dataindex : "chiSqrt", - renderer : function(a, b, record) { - if (record.data.dmax != null) { - return BUI.formatValuesUnits(record.data.chiSqrt, "", 12, this.decimals); - } - - }, - flex : 1 - }, - { - text : "Dmax", - dataindex : "dmax", - renderer : function(a, b, record) { - if (record.data.dmax != null) { - return BUI.formatValuesUnits(record.data.dmax, "nm", 12, this.decimals); - } - - }, - flex : 1 - }, { - text : "rFactor", - dataindex : "rfactor", - hidden : true, - renderer : function(a, b, record) { - if (record.data.rfactor != null) { - return record.data.rfactor; - } - }, - flex : 1 - }, { - text : "Rg", - dataindex : "rg", - renderer : function(a, b, record) { - if (record.data.rg != null) { - return BUI.formatValuesUnits(record.data.rg, "nm", 12, this.decimals); - } - - }, - flex : 1 - }, - { - text : "Volume", - dataindex : "volume", - renderer : function(a, b, record) { - if (record.raw.volume != null){ - return BUI.formatValuesUnits(record.raw.volume, '') + " nm3"; - } - }, - flex : 1 - }, - { - text : "PDB", - dataindex : "pdbFile", - renderer : function(a, b, record) { - if (record.data.pdbFile != null){ - return record.data.pdbFile.split("/")[record.data.pdbFile.split("/").length - 1]; - } - }, - flex : 1 - }, { - text : "Fir", - dataindex : "firFile", - renderer : function(a, b, record) { - if (record.data.firFile != null){ - return record.data.firFile.split("/")[record.data.firFile.split("/").length - 1]; - } - }, - flex : 1 - }, { - text : "LOG", - dataindex : "logFile", - hidden : true, - renderer : function(a, b, record) { - if (record.data.logFile != null){ - return record.data.logFile.split("/")[record.data.logFile.split("/").length - 1]; - } - }, - flex : 1 - } - ], - viewConfig : { - enableTextSelection : true, - preserveScrollOnRefresh : true, - stripeRows : true, - listeners : { - 'celldblclick' : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - }, - 'cellclick' : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - var models = []; - for (var i = 0; i < grid.getSelectionModel().selected.items.length; i++) { - models.push(grid.getSelectionModel().selected.items[i].raw); - } - _this.onSelected.notify(models); - } - } - } - }); - return this.grid; - -}; - function AdditiveGrid(args) { this.onRemoveButtonClicked = new Event(this); @@ -16236,255 +16236,255 @@ HPLCAnalysisGrid.prototype._getFramesColumn = function() { }; - - -/** - * Rigid body grid to show PDB, symmetry and multiplicity - * - * - * #onUploadFile click on upload file - */ -function AprioriRigidBodyGrid(args) { - - this.height = 250; - this.btnEditVisible = true; - this.btnRemoveVisible = true; - - if (args != null) { - if (args.height != null) { - this.height = args.height; - } - if (args.btnEditVisible != null) { - this.btnEditVisible = args.btnEditVisible; - } - if (args.btnRemoveVisible != null) { - this.btnRemoveVisible = args.btnRemoveVisible; - } - } - - /** Events **/ - this.onUploadFile = new Event(this); - this.onRemove = new Event(this); -} - -AprioriRigidBodyGrid.prototype._getColumns = function() { -}; - -AprioriRigidBodyGrid.prototype._getTopButtons = function() { - var _this = this; - /** Actions buttons **/ - var actions = []; - - /** ADD BUTTON **/ - actions.push(Ext.create('Ext.Action', { - icon : '../images/add.png', - text : 'Add', - disabled : false, - handler : function(widget, event) { - _this.onAddButtonClicked.notify(); - } - })); - - return actions; -}; - -AprioriRigidBodyGrid.prototype.refresh = function(macromolecule) { - this.macromolecule = macromolecule; - if (macromolecule != null){ - this.pdbStore.loadData(macromolecule.structure3VOs); - } -}; - -AprioriRigidBodyGrid.prototype._prepareData = function() { - var data = []; - for ( var i = 0; i < this.features.length; i++) { - data.push(this.features[i]); - } - return data; -}; - -AprioriRigidBodyGrid.prototype._getPlugins = function() { - var _this = this; - var plugins = []; - plugins.push(Ext.create('Ext.grid.plugin.RowEditing', { - clicksToEdit : 1, - listeners : { - validateedit : function(grid, e) { - /** Comments are always updatable* */ - e.record.raw.symmetry = e.newValues.symmetry; - e.record.raw.multiplicity = e.newValues.multiplicity; - - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, proposal) { - BIOSAXS.proposal.setItems(proposal); - _this.refresh(BIOSAXS.proposal.getMacromoleculeById(_this.macromolecule.macromoleculeId)); - _this.panel.setLoading(false); - }); - adapter.onError.attach(function() { - alert("Error"); - }); - - _this.panel.setLoading(); - adapter.saveStructure(e.record.raw); - } - } - })); - return plugins; -}; - -AprioriRigidBodyGrid.prototype.getPanel = function() { - var _this = this; - - this.pdbStore = Ext.create('Ext.data.Store', { - fields : [ 'filePath', 'structureId', 'structureType', 'symmetry', 'structureId', 'name', 'multiplicity' ], - groupField : 'structureType', - sorters : { - property : 'structureId', - direction : 'DESC' - } - }); - - var groupingFeature = Ext.create('Ext.grid.feature.Grouping', { - groupHeaderTpl : Ext.create('Ext.XTemplate', - "
{name:this.formatName}
", { - formatName : function(name) { - return name; - } - }), - hideGroupedHeader : true, - startCollapsed : false - }); - - this.panel = Ext.create('Ext.grid.Panel', { - margin : "15 10 0 10", - height : this.height, - store : this.pdbStore, - plugins : _this._getPlugins(), - tbar : [ { - text : 'Add Modeling Option (PDB)', - icon : '../images/add.png', - handler : function() { - _this.onUploadFile.notify('PDB', 'Upload PDB File'); - } - } - - ], - columns : [ - { - text : "structureId", - flex : 0.2, - hidden : true, - dataIndex : 'structureId', - sortable : true - }, - { - text : "File", - flex : 0.5, - dataIndex : 'filePath', - sortable : true, - hidden : true - }, - { - text : "PDB", - flex : 0.4, - dataIndex : 'name', - sortable : true - }, - { - text : "Symmetry", - flex : 0.2, - dataIndex : 'symmetry', - sortable : true, - editor : { - xtype : 'combobox', - typeAhead : true, - triggerAction : 'all', - selectOnTab : true, - store : [ [ "P1", "P1" ], [ "P2", "P2" ], [ "P3", "P3" ], [ "P4", "P4" ], [ "P5", "P5" ], [ "P6", "P6" ], [ "P32", "P32" ], [ "P42", "P42" ], - [ "P52", "P52" ], [ "P62", "P62" ], [ "P222", "P222" ] ], - } - }, { - text : "Multiplicity", - flex : 0.2, - dataIndex : 'multiplicity', - sortable : true, - editor : { - xtype : 'textfield' - } - - }, { - text : "Subunit", - flex : 0.2, - dataIndex : 'isSubunit', - sortable : true, - hidden : true - }, { - text : "Type", - flex : 0.2, - dataIndex : 'structureType', - sortable : true, - hidden : true - }, - - { - id : this.id + 'REMOVE', - flex : 0.2, - sortable : false, - renderer : function(value, metaData, record, rowIndex, colIndex, store) { - return BUI.getRedButton('REMOVE'); - } - }, ], - - listeners : { - itemdblclick : function(dataview, record, item, e) { - _this._editExperiment(record.raw.experimentId); - }, - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - - if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'REMOVE') { - var dataAdapter = new BiosaxsDataAdapter(); - dataAdapter.onSuccess.attach(function() { - _this.panel.setLoading(false); - _this.onRemove.notify(); - }); - _this.panel.setLoading("Removing PDB file"); - dataAdapter.removeStructure(record.data.structureId); - } - - } - }, - viewConfig : { - getRowClass : function(record, rowIdx, params, store) { - if (record.raw.isSubunit != null) { - return "blue-row"; - } - } - } - }); - - return this.panel; -}; - - - - -AprioriRigidBodyGrid.prototype.input = function() { - return { - proposal : DATADOC.getProposal_10(), - dewars : DATADOC.getDewars_10() - - }; -}; - -AprioriRigidBodyGrid.prototype.test = function(targetId) { - var AprioriRigidBodyGrid = new AprioriRigidBodyGrid({ - height : 150 - }); - BIOSAXS.proposal = new Proposal(AprioriRigidBodyGrid.input().proposal); - var panel = AprioriRigidBodyGrid.getPanel(AprioriRigidBodyGrid.input().dewars); - panel.render(targetId); - -}; + + +/** + * Rigid body grid to show PDB, symmetry and multiplicity + * + * + * #onUploadFile click on upload file + */ +function AprioriRigidBodyGrid(args) { + + this.height = 250; + this.btnEditVisible = true; + this.btnRemoveVisible = true; + + if (args != null) { + if (args.height != null) { + this.height = args.height; + } + if (args.btnEditVisible != null) { + this.btnEditVisible = args.btnEditVisible; + } + if (args.btnRemoveVisible != null) { + this.btnRemoveVisible = args.btnRemoveVisible; + } + } + + /** Events **/ + this.onUploadFile = new Event(this); + this.onRemove = new Event(this); +} + +AprioriRigidBodyGrid.prototype._getColumns = function() { +}; + +AprioriRigidBodyGrid.prototype._getTopButtons = function() { + var _this = this; + /** Actions buttons **/ + var actions = []; + + /** ADD BUTTON **/ + actions.push(Ext.create('Ext.Action', { + icon : '../images/add.png', + text : 'Add', + disabled : false, + handler : function(widget, event) { + _this.onAddButtonClicked.notify(); + } + })); + + return actions; +}; + +AprioriRigidBodyGrid.prototype.refresh = function(macromolecule) { + this.macromolecule = macromolecule; + if (macromolecule != null){ + this.pdbStore.loadData(macromolecule.structure3VOs); + } +}; + +AprioriRigidBodyGrid.prototype._prepareData = function() { + var data = []; + for ( var i = 0; i < this.features.length; i++) { + data.push(this.features[i]); + } + return data; +}; + +AprioriRigidBodyGrid.prototype._getPlugins = function() { + var _this = this; + var plugins = []; + plugins.push(Ext.create('Ext.grid.plugin.RowEditing', { + clicksToEdit : 1, + listeners : { + validateedit : function(grid, e) { + /** Comments are always updatable* */ + e.record.raw.symmetry = e.newValues.symmetry; + e.record.raw.multiplicity = e.newValues.multiplicity; + + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, proposal) { + BIOSAXS.proposal.setItems(proposal); + _this.refresh(BIOSAXS.proposal.getMacromoleculeById(_this.macromolecule.macromoleculeId)); + _this.panel.setLoading(false); + }); + adapter.onError.attach(function() { + alert("Error"); + }); + + _this.panel.setLoading(); + adapter.saveStructure(e.record.raw); + } + } + })); + return plugins; +}; + +AprioriRigidBodyGrid.prototype.getPanel = function() { + var _this = this; + + this.pdbStore = Ext.create('Ext.data.Store', { + fields : [ 'filePath', 'structureId', 'structureType', 'symmetry', 'structureId', 'name', 'multiplicity' ], + groupField : 'structureType', + sorters : { + property : 'structureId', + direction : 'DESC' + } + }); + + var groupingFeature = Ext.create('Ext.grid.feature.Grouping', { + groupHeaderTpl : Ext.create('Ext.XTemplate', + "
{name:this.formatName}
", { + formatName : function(name) { + return name; + } + }), + hideGroupedHeader : true, + startCollapsed : false + }); + + this.panel = Ext.create('Ext.grid.Panel', { + margin : "15 10 0 10", + height : this.height, + store : this.pdbStore, + plugins : _this._getPlugins(), + tbar : [ { + text : 'Add Modeling Option (PDB)', + icon : '../images/add.png', + handler : function() { + _this.onUploadFile.notify('PDB', 'Upload PDB File'); + } + } + + ], + columns : [ + { + text : "structureId", + flex : 0.2, + hidden : true, + dataIndex : 'structureId', + sortable : true + }, + { + text : "File", + flex : 0.5, + dataIndex : 'filePath', + sortable : true, + hidden : true + }, + { + text : "PDB", + flex : 0.4, + dataIndex : 'name', + sortable : true + }, + { + text : "Symmetry", + flex : 0.2, + dataIndex : 'symmetry', + sortable : true, + editor : { + xtype : 'combobox', + typeAhead : true, + triggerAction : 'all', + selectOnTab : true, + store : [ [ "P1", "P1" ], [ "P2", "P2" ], [ "P3", "P3" ], [ "P4", "P4" ], [ "P5", "P5" ], [ "P6", "P6" ], [ "P32", "P32" ], [ "P42", "P42" ], + [ "P52", "P52" ], [ "P62", "P62" ], [ "P222", "P222" ] ], + } + }, { + text : "Multiplicity", + flex : 0.2, + dataIndex : 'multiplicity', + sortable : true, + editor : { + xtype : 'textfield' + } + + }, { + text : "Subunit", + flex : 0.2, + dataIndex : 'isSubunit', + sortable : true, + hidden : true + }, { + text : "Type", + flex : 0.2, + dataIndex : 'structureType', + sortable : true, + hidden : true + }, + + { + id : this.id + 'REMOVE', + flex : 0.2, + sortable : false, + renderer : function(value, metaData, record, rowIndex, colIndex, store) { + return BUI.getRedButton('REMOVE'); + } + }, ], + + listeners : { + itemdblclick : function(dataview, record, item, e) { + _this._editExperiment(record.raw.experimentId); + }, + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + + if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'REMOVE') { + var dataAdapter = new BiosaxsDataAdapter(); + dataAdapter.onSuccess.attach(function() { + _this.panel.setLoading(false); + _this.onRemove.notify(); + }); + _this.panel.setLoading("Removing PDB file"); + dataAdapter.removeStructure(record.data.structureId); + } + + } + }, + viewConfig : { + getRowClass : function(record, rowIdx, params, store) { + if (record.raw.isSubunit != null) { + return "blue-row"; + } + } + } + }); + + return this.panel; +}; + + + + +AprioriRigidBodyGrid.prototype.input = function() { + return { + proposal : DATADOC.getProposal_10(), + dewars : DATADOC.getDewars_10() + + }; +}; + +AprioriRigidBodyGrid.prototype.test = function(targetId) { + var AprioriRigidBodyGrid = new AprioriRigidBodyGrid({ + height : 150 + }); + BIOSAXS.proposal = new Proposal(AprioriRigidBodyGrid.input().proposal); + var panel = AprioriRigidBodyGrid.getPanel(AprioriRigidBodyGrid.input().dewars); + panel.render(targetId); + +}; /** * It shows buffer grid with a top bar with "Add" button @@ -16513,159 +16513,552 @@ function BufferGrid(args) { this.tbar = args.tbar; } - if (args.collapsed != null) { - this.collapsed = args.collapsed; - } + if (args.collapsed != null) { + this.collapsed = args.collapsed; + } + + if (args.width != null) { + this.width = args.width; + } + } +} + +BufferGrid.prototype._edit = function(bufferId) { + var _this = this; + var window = new BufferWindow(); + window.onSuccess.attach(function(sender, proposal) { + _this.store.loadData(BIOSAXS.proposal.getBuffers()); + }); + window.draw(BIOSAXS.proposal.getBufferById(bufferId)); +}; + +BufferGrid.prototype.refresh = function(buffers) { + this.store.loadData(this._prepareData(buffers), false); +}; + +BufferGrid.prototype._prepareData = function(buffers) { + return buffers; +}; + +BufferGrid.prototype._getTbar = function() { + var _this = this; + var actions = []; + + actions.push(Ext.create('Ext.Action', { + icon : '../images/add.png', + text : 'Add buffer', + disabled : false, + handler : function(widget, event) { + var window = new BufferWindow(); + window.onSuccess.attach(function(sender) { + _this.store.loadData(BIOSAXS.proposal.getBuffers()); + }); + window.draw({}); + } + })); + return actions; +}; + +BufferGrid.prototype.getPanel = function(buffers) { + var _this = this; + + this.store = Ext.create('Ext.data.Store', { + fields : [ 'bufferId', 'acronym', 'name', 'composition' ], + data : buffers + }); + + this.store.sort('acronym'); + + var type = 'Ext.grid.Panel'; + if (this.searchBar == true) { + type = 'Ext.ux.LiveSearchGridPanel'; + } + + this.grid = Ext.create(type, { + title : 'Buffers', + collapsible : true, + collapsed : this.collapsed, + store : this.store, + height : this.height, + width : this.width, + columns : [ + /*{ + text : '', + dataIndex : 'bufferId', + width : 20, + renderer : function(val, y, sample) { + return BUI.getRectangleColorDIV(BIOSAXS.proposal.bufferColors[val], 10, 10); + } + },*/ + { + text : 'Acronym', + dataIndex : 'acronym', + flex : 1 + }, { + text : 'Name', + dataIndex : 'name', + flex : 1, + hidden : true + }, { + text : 'Composition', + dataIndex : 'composition', + flex : 1, + hidden : true + }, { + id : _this.id + 'buttonEditBuffer', + width : 80, + sortable : false, + renderer : function(value, metaData, record, rowIndex, colIndex, store) { + return BUI.getGreenButton('EDIT'); + } + }, { + id : _this.id + 'buttonRemoveBuffer', + width : 85, + hidden : true, + sortable : false, + renderer : function(value, metaData, record, rowIndex, colIndex, store) { + return BUI.getRedButton('REMOVE'); + } + } ], + flex : 1, + viewConfig : { + stripeRows : true, + listeners : { + 'celldblclick' : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + _this._edit(record.data.bufferId); + }, + 'cellclick' : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonEditBuffer') { + _this._edit(record.data.bufferId); + } + + if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonRemoveBuffer') { + BUI.showBetaWarning(); + } + } + + } + } + }); + + /** Adding the tbar **/ + if (this.tbar) { + this.grid.addDocked({ + xtype : 'toolbar', + items : this._getTbar() + }); + } + return this.grid; +}; + +BufferGrid.prototype.input = function() { + return new MacromoleculeGrid().input(); +}; + +BufferGrid.prototype.test = function(targetId) { + var bufferGrid = new BufferGrid({ + width : 800, + height : 350, + collapsed : false, + tbar : true + }); + + BIOSAXS.proposal = new Proposal(bufferGrid.input().proposal); + var panel = bufferGrid.getPanel(BIOSAXS.proposal.macromolecules); + panel.render(targetId); +}; + +/** + * A shipment may contains one or more cases where stock solutions and sample plates are stored + * + * @height + * @btnEditVisible + * @btnRemoveVisible + * + * #onEditButtonClicked + * #onAddButtonClicked + * #onRemoveButtonClicked + * #onDuplicateButtonClicked + */ +function CaseGrid(args) { + + this.height = 100; + this.btnEditVisible = true; + this.btnRemoveVisible = true; + + if (args != null) { + if (args.height != null) { + this.height = args.height; + } + if (args.btnEditVisible != null) { + this.btnEditVisible = args.btnEditVisible; + } + if (args.btnRemoveVisible != null) { + this.btnRemoveVisible = args.btnRemoveVisible; + } + } + + /** Events **/ + this.onEditButtonClicked = new Event(this); + this.onAddButtonClicked = new Event(this); + this.onRemoveButtonClicked = new Event(this); + this.onDuplicateButtonClicked = new Event(this); +} + +CaseGrid.prototype._getColumns = function() { + var _this = this; + + function actionItemRenderer(value, meta, record, rowIx, ColIx, store) { + /*if (record.raw.specimen3VOs.length > 0){ + return 'x-hide-display'; + }*/ + } + + var columns = [ + { + header : 'Code', + dataIndex : 'code', + name : 'code', + type : 'string', + flex : 1 + }, + { + header : 'Bar Code', + dataIndex : 'barCode', + name : 'barCode', + type : 'string', + flex : 1, + hidden : true + }, + { + header : 'BeamLine', + dataIndex : 'barCode', + type : 'string', + flex : 1, + renderer : function(comp, val, record) { + if (record.raw.sessionVO != null) { + return "" + record.raw.sessionVO.beamlineName + ""; + } + } + }, + { + header : 'Session', + dataIndex : 'barCode', + type : 'string', + flex : 1, + renderer : function(comp, val, record) { + if (record.raw.sessionVO != null) { + return "" + moment(record.raw.sessionVO.startDate).format("MMM Do YY") + ""; + } + } + }, + { + header : 'Status', + dataIndex : 'dewarStatus', + name : 'dewarStatus', + type : 'string', + flex : 1, + renderer : function(comp, val, record) { + if (new String(record.raw.dewarStatus).toUpperCase() == 'OPENED') { + return "" + new String(record.raw.dewarStatus).toUpperCase() + ""; + } + return "" + new String(record.raw.dewarStatus).toUpperCase() + ""; + } + }, + { + header : 'Type', + dataIndex : 'type', + name : 'type', + type : 'string', + flex : 1, + hidden : true + }, + { + header : 'Sample Plates', + dataIndex : 'plates', + name : 'plates', + type : 'string', + flex : 1, + hidden : true + }, + { + header : 'Stock Solutions', + dataIndex : 'plates', + name : 'plates', + type : 'string', + width : 100, + renderer : function(comp, val, record) { + var html = "
"; + var stockSolutions = BIOSAXS.proposal.getStockSolutionsByDewarId(record.raw.dewarId); + html = html + "" + stockSolutions.length + " x"; + return html + "
"; + } + }, { + header : 'isStorageDewar', + dataIndex : 'isStorageDewar', + name : 'isStorageDewar', + type : 'string', + flex : 1, + hidden : true + }, { + header : 'Tracking Number From Synchrotron', + dataIndex : 'trackingNumberFromSynchrotron', + name : 'trackingNumberFromSynchrotron', + type : 'string', + flex : 1, + hidden : true + }, { + header : 'Tracking Number To Synchrotron', + dataIndex : 'trackingNumberToSynchrotron', + name : 'trackingNumberToSynchrotron', + type : 'string', + flex : 1, + hidden : true + }, { + header : 'Storage Location', + dataIndex : 'storageLocation', + name : 'storageLocation', + type : 'string', + flex : 1, + hidden : false + }, { + header : 'Comments', + dataIndex : 'comments', + name : 'comments', + type : 'string', + flex : 1, + hidden : false + } + ]; + + if (this.btnEditVisible) { + columns.push({ + id : _this.id + 'buttonEdit', + text : '', + hidden : !_this.btnEditVisible, + width : 85, + sortable : false, + renderer : function(value, metaData, record, rowIndex, colIndex, store) { + return BUI.getGreenButton('EDIT'); + } + }); + } - if (args.width != null) { - this.width = args.width; - } + if (this.btnRemoveVisible) { + columns.push({ + id : _this.id + 'buttonRemove', + width : 85, + sortable : false, + renderer : function(value, metaData, record, rowIndex, colIndex, store) { + if (_this.btnRemoveVisible) { + return BUI.getRedButton('REMOVE'); + } + } + }); } -} -BufferGrid.prototype._edit = function(bufferId) { - var _this = this; - var window = new BufferWindow(); - window.onSuccess.attach(function(sender, proposal) { - _this.store.loadData(BIOSAXS.proposal.getBuffers()); + columns.push({ + dataIndex : 'comments', + type : 'string', + width : 85, + hidden : false, + renderer : function(comp, val, record) { + return BUI.getBlueButton("LABELS", { + href : BUI.getPrintcomponentURL(record.raw.dewarId) + }); + } }); - window.draw(BIOSAXS.proposal.getBufferById(bufferId)); -}; - -BufferGrid.prototype.refresh = function(buffers) { - this.store.loadData(this._prepareData(buffers), false); -}; -BufferGrid.prototype._prepareData = function(buffers) { - return buffers; + return columns; }; -BufferGrid.prototype._getTbar = function() { +CaseGrid.prototype._getTopButtons = function() { var _this = this; + /** Actions buttons **/ var actions = []; + /** ADD BUTTON **/ actions.push(Ext.create('Ext.Action', { icon : '../images/add.png', - text : 'Add buffer', + text : 'Add', disabled : false, handler : function(widget, event) { - var window = new BufferWindow(); - window.onSuccess.attach(function(sender) { - _this.store.loadData(BIOSAXS.proposal.getBuffers()); - }); - window.draw({}); + _this.onAddButtonClicked.notify(); } })); + return actions; }; -BufferGrid.prototype.getPanel = function(buffers) { - var _this = this; +CaseGrid.prototype.refresh = function(dewars) { + this.features = dewars; + this.store.loadData(this._prepareData(dewars), false); +}; - this.store = Ext.create('Ext.data.Store', { - fields : [ 'bufferId', 'acronym', 'name', 'composition' ], - data : buffers - }); +CaseGrid.prototype._sort = function(store) { + store.sort('dewarId', 'DESC'); +}; - this.store.sort('acronym'); +CaseGrid.prototype._prepareData = function() { + var data = []; + for ( var i = 0; i < this.features.length; i++) { + data.push(this.features[i]); + } + return data; +}; - var type = 'Ext.grid.Panel'; - if (this.searchBar == true) { - type = 'Ext.ux.LiveSearchGridPanel'; +CaseGrid.prototype.getPanel = function(dewars, plates) { + this.features = dewars; + this.plates = plates; + return this._renderGrid(); +}; + +CaseGrid.prototype._edit = function(dewar) { + var _this = this; + var caseWindow = new CaseWindow(); + /**SAVED **/ + caseWindow.onSaved.attach(function(sender, dewar) { + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, shipment) { + _this.refresh(shipment.dewarVOs); + }); + adapter.saveCase(BIOSAXS.proposal.getShipmentByDewarId(dewar.dewarId).shippingId, dewar); + }); + caseWindow.draw(dewar); +}; + +CaseGrid.prototype._getStoreFields = function(data) { + return [ { + name : 'dewarId', + type : 'string' + }, { + name : 'barCode', + type : 'string' + }, { + name : 'code', + type : 'string' + }, { + name : 'comments', + type : 'string' + }, { + name : 'dewarStatus', + type : 'string' + }, { + name : 'isStorageDewar', + type : 'string' + }, { + name : 'plates', + type : 'string' + }, { + name : 'transportValue', + type : 'string' + }, { + name : 'trackingNumberFromSynchrotron', + type : 'string' + }, { + name : 'trackingNumberToSynchrotron', + type : 'string' + }, { + name : 'timeStamp', + type : 'string' + }, { + name : 'storageLocation', + type : 'string' + }, { + name : 'type', + type : 'string' } - this.grid = Ext.create(type, { - title : 'Buffers', - collapsible : true, - collapsed : this.collapsed, - store : this.store, + ]; +}; + +CaseGrid.prototype._renderGrid = function() { + var _this = this; + + /** Store **/ + var data = this._prepareData(); + this.store = Ext.create('Ext.data.Store', { + fields : this._getStoreFields(data), + autoload : true, + data : data + }); + this._sort(this.store); + + this.store.loadData(data, false); + + this.grid = Ext.create('Ext.grid.Panel', { + style : { + padding : 5 + }, height : this.height, - width : this.width, - columns : [ - /*{ - text : '', - dataIndex : 'bufferId', - width : 20, - renderer : function(val, y, sample) { - return BUI.getRectangleColorDIV(BIOSAXS.proposal.bufferColors[val], 10, 10); - } - },*/ - { - text : 'Acronym', - dataIndex : 'acronym', - flex : 1 - }, { - text : 'Name', - dataIndex : 'name', - flex : 1, - hidden : true - }, { - text : 'Composition', - dataIndex : 'composition', - flex : 1, - hidden : true - }, { - id : _this.id + 'buttonEditBuffer', - width : 80, - sortable : false, - renderer : function(value, metaData, record, rowIndex, colIndex, store) { - return BUI.getGreenButton('EDIT'); - } - }, { - id : _this.id + 'buttonRemoveBuffer', - width : 85, - hidden : true, - sortable : false, - renderer : function(value, metaData, record, rowIndex, colIndex, store) { - return BUI.getRedButton('REMOVE'); - } - } ], - flex : 1, + store : this.store, + columns : this._getColumns(), viewConfig : { stripeRows : true, listeners : { - 'celldblclick' : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - _this._edit(record.data.bufferId); + itemdblclick : function(dataview, record, item, e) { + _this._edit(record.raw); }, - 'cellclick' : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonEditBuffer') { - _this._edit(record.data.bufferId); + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonEdit') { + _this._edit(record.raw); } - if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonRemoveBuffer') { - BUI.showBetaWarning(); + if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonRemove') { + _this.onRemoveButtonClicked.notify(_this.store.getAt(rowIndex).raw.dewarId); } } - } + }, + selModel : { + mode : 'SINGLE' } }); - /** Adding the tbar **/ - if (this.tbar) { - this.grid.addDocked({ - xtype : 'toolbar', - items : this._getTbar() - }); - } + var actions = _this._getTopButtons(); + this.grid.addDocked({ + xtype : 'toolbar', + items : actions + }); + + this.grid.getSelectionModel().on({ + selectionchange : function(sm, selections) { + if (selections.length) { + for ( var i = 0; i < actions.length; i++) { + if (actions[i].enable) { + actions[i].enable(); + } + } + } else { + for ( var i = 0; i < actions.length; i++) { + if (actions[i].alwaysEnabled == false) { + if (actions[i].disable) { + actions[i].disable(); + } + } + } + } + } + }); return this.grid; }; -BufferGrid.prototype.input = function() { - return new MacromoleculeGrid().input(); +CaseGrid.prototype.input = function() { + return { + proposal : DATADOC.getProposal_10(), + dewars : DATADOC.getDewars_10() + + }; }; -BufferGrid.prototype.test = function(targetId) { - var bufferGrid = new BufferGrid({ - width : 800, - height : 350, - collapsed : false, - tbar : true +CaseGrid.prototype.test = function(targetId) { + var CaseGrid = new CaseGrid({ + height : 150 }); - - BIOSAXS.proposal = new Proposal(bufferGrid.input().proposal); - var panel = bufferGrid.getPanel(BIOSAXS.proposal.macromolecules); + BIOSAXS.proposal = new Proposal(CaseGrid.input().proposal); + var panel = CaseGrid.getPanel(CaseGrid.input().dewars); panel.render(targetId); + }; /** @@ -16680,7 +17073,7 @@ BufferGrid.prototype.test = function(targetId) { * #onRemoveButtonClicked * #onDuplicateButtonClicked */ -function CaseGrid(args) { +function ExampleGrid(args) { this.height = 100; this.btnEditVisible = true; @@ -16705,7 +17098,7 @@ function CaseGrid(args) { this.onDuplicateButtonClicked = new Event(this); } -CaseGrid.prototype._getColumns = function() { +ExampleGrid.prototype._getColumns = function() { var _this = this; function actionItemRenderer(value, meta, record, rowIx, ColIx, store) { @@ -16872,7 +17265,7 @@ CaseGrid.prototype._getColumns = function() { return columns; }; -CaseGrid.prototype._getTopButtons = function() { +ExampleGrid.prototype._getTopButtons = function() { var _this = this; /** Actions buttons **/ var actions = []; @@ -16890,16 +17283,16 @@ CaseGrid.prototype._getTopButtons = function() { return actions; }; -CaseGrid.prototype.refresh = function(dewars) { +ExampleGrid.prototype.refresh = function(dewars) { this.features = dewars; this.store.loadData(this._prepareData(dewars), false); }; -CaseGrid.prototype._sort = function(store) { +ExampleGrid.prototype._sort = function(store) { store.sort('dewarId', 'DESC'); }; -CaseGrid.prototype._prepareData = function() { +ExampleGrid.prototype._prepareData = function() { var data = []; for ( var i = 0; i < this.features.length; i++) { data.push(this.features[i]); @@ -16907,27 +17300,66 @@ CaseGrid.prototype._prepareData = function() { return data; }; -CaseGrid.prototype.getPanel = function(dewars, plates) { - this.features = dewars; - this.plates = plates; - return this._renderGrid(); -}; +ExampleGrid.prototype.getPanel = function() { + this.grid = Ext.create('Ext.grid.Panel', { + style : { + padding : 5 + }, + height : this.height, + store : this.store, + columns : this._getColumns(), + viewConfig : { + stripeRows : true, + listeners : { + itemdblclick : function(dataview, record, item, e) { + _this._edit(record.raw); + }, + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonEdit') { + _this._edit(record.raw); + } -CaseGrid.prototype._edit = function(dewar) { - var _this = this; - var caseWindow = new CaseWindow(); - /**SAVED **/ - caseWindow.onSaved.attach(function(sender, dewar) { - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, shipment) { - _this.refresh(shipment.dewarVOs); - }); - adapter.saveCase(BIOSAXS.proposal.getShipmentByDewarId(dewar.dewarId).shippingId, dewar); + if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonRemove') { + _this.onRemoveButtonClicked.notify(_this.store.getAt(rowIndex).raw.dewarId); + } + } + } + }, + selModel : { + mode : 'SINGLE' + } }); - caseWindow.draw(dewar); + + var actions = _this._getTopButtons(); + this.grid.addDocked({ + xtype : 'toolbar', + items : actions + }); + + this.grid.getSelectionModel().on({ + selectionchange : function(sm, selections) { + if (selections.length) { + for ( var i = 0; i < actions.length; i++) { + if (actions[i].enable) { + actions[i].enable(); + } + } + } else { + for ( var i = 0; i < actions.length; i++) { + if (actions[i].alwaysEnabled == false) { + if (actions[i].disable) { + actions[i].disable(); + } + } + } + } + } + }); + return this.grid; }; -CaseGrid.prototype._getStoreFields = function(data) { + +ExampleGrid.prototype._getStoreFields = function(data) { return [ { name : 'dewarId', type : 'string' @@ -16972,7 +17404,7 @@ CaseGrid.prototype._getStoreFields = function(data) { ]; }; -CaseGrid.prototype._renderGrid = function() { +ExampleGrid.prototype._renderGrid = function() { var _this = this; /** Store **/ @@ -17043,7 +17475,7 @@ CaseGrid.prototype._renderGrid = function() { return this.grid; }; -CaseGrid.prototype.input = function() { +ExampleGrid.prototype.input = function() { return { proposal : DATADOC.getProposal_10(), dewars : DATADOC.getDewars_10() @@ -17051,447 +17483,15 @@ CaseGrid.prototype.input = function() { }; }; -CaseGrid.prototype.test = function(targetId) { - var CaseGrid = new CaseGrid({ +ExampleGrid.prototype.test = function(targetId) { + var ExampleGrid = new ExampleGrid({ height : 150 }); - BIOSAXS.proposal = new Proposal(CaseGrid.input().proposal); - var panel = CaseGrid.getPanel(CaseGrid.input().dewars); - panel.render(targetId); - -}; - -/** - * A shipment may contains one or more cases where stock solutions and sample plates are stored - * - * @height - * @btnEditVisible - * @btnRemoveVisible - * - * #onEditButtonClicked - * #onAddButtonClicked - * #onRemoveButtonClicked - * #onDuplicateButtonClicked - */ -function ExampleGrid(args) { - - this.height = 100; - this.btnEditVisible = true; - this.btnRemoveVisible = true; - - if (args != null) { - if (args.height != null) { - this.height = args.height; - } - if (args.btnEditVisible != null) { - this.btnEditVisible = args.btnEditVisible; - } - if (args.btnRemoveVisible != null) { - this.btnRemoveVisible = args.btnRemoveVisible; - } - } - - /** Events **/ - this.onEditButtonClicked = new Event(this); - this.onAddButtonClicked = new Event(this); - this.onRemoveButtonClicked = new Event(this); - this.onDuplicateButtonClicked = new Event(this); -} - -ExampleGrid.prototype._getColumns = function() { - var _this = this; - - function actionItemRenderer(value, meta, record, rowIx, ColIx, store) { - /*if (record.raw.specimen3VOs.length > 0){ - return 'x-hide-display'; - }*/ - } - - var columns = [ - { - header : 'Code', - dataIndex : 'code', - name : 'code', - type : 'string', - flex : 1 - }, - { - header : 'Bar Code', - dataIndex : 'barCode', - name : 'barCode', - type : 'string', - flex : 1, - hidden : true - }, - { - header : 'BeamLine', - dataIndex : 'barCode', - type : 'string', - flex : 1, - renderer : function(comp, val, record) { - if (record.raw.sessionVO != null) { - return "" + record.raw.sessionVO.beamlineName + ""; - } - } - }, - { - header : 'Session', - dataIndex : 'barCode', - type : 'string', - flex : 1, - renderer : function(comp, val, record) { - if (record.raw.sessionVO != null) { - return "" + moment(record.raw.sessionVO.startDate).format("MMM Do YY") + ""; - } - } - }, - { - header : 'Status', - dataIndex : 'dewarStatus', - name : 'dewarStatus', - type : 'string', - flex : 1, - renderer : function(comp, val, record) { - if (new String(record.raw.dewarStatus).toUpperCase() == 'OPENED') { - return "" + new String(record.raw.dewarStatus).toUpperCase() + ""; - } - return "" + new String(record.raw.dewarStatus).toUpperCase() + ""; - } - }, - { - header : 'Type', - dataIndex : 'type', - name : 'type', - type : 'string', - flex : 1, - hidden : true - }, - { - header : 'Sample Plates', - dataIndex : 'plates', - name : 'plates', - type : 'string', - flex : 1, - hidden : true - }, - { - header : 'Stock Solutions', - dataIndex : 'plates', - name : 'plates', - type : 'string', - width : 100, - renderer : function(comp, val, record) { - var html = "
"; - var stockSolutions = BIOSAXS.proposal.getStockSolutionsByDewarId(record.raw.dewarId); - html = html + "" + stockSolutions.length + " x"; - return html + "
"; - } - }, { - header : 'isStorageDewar', - dataIndex : 'isStorageDewar', - name : 'isStorageDewar', - type : 'string', - flex : 1, - hidden : true - }, { - header : 'Tracking Number From Synchrotron', - dataIndex : 'trackingNumberFromSynchrotron', - name : 'trackingNumberFromSynchrotron', - type : 'string', - flex : 1, - hidden : true - }, { - header : 'Tracking Number To Synchrotron', - dataIndex : 'trackingNumberToSynchrotron', - name : 'trackingNumberToSynchrotron', - type : 'string', - flex : 1, - hidden : true - }, { - header : 'Storage Location', - dataIndex : 'storageLocation', - name : 'storageLocation', - type : 'string', - flex : 1, - hidden : false - }, { - header : 'Comments', - dataIndex : 'comments', - name : 'comments', - type : 'string', - flex : 1, - hidden : false - } - ]; - - if (this.btnEditVisible) { - columns.push({ - id : _this.id + 'buttonEdit', - text : '', - hidden : !_this.btnEditVisible, - width : 85, - sortable : false, - renderer : function(value, metaData, record, rowIndex, colIndex, store) { - return BUI.getGreenButton('EDIT'); - } - }); - } - - if (this.btnRemoveVisible) { - columns.push({ - id : _this.id + 'buttonRemove', - width : 85, - sortable : false, - renderer : function(value, metaData, record, rowIndex, colIndex, store) { - if (_this.btnRemoveVisible) { - return BUI.getRedButton('REMOVE'); - } - } - }); - } - - columns.push({ - dataIndex : 'comments', - type : 'string', - width : 85, - hidden : false, - renderer : function(comp, val, record) { - return BUI.getBlueButton("LABELS", { - href : BUI.getPrintcomponentURL(record.raw.dewarId) - }); - } - }); - - return columns; -}; - -ExampleGrid.prototype._getTopButtons = function() { - var _this = this; - /** Actions buttons **/ - var actions = []; - - /** ADD BUTTON **/ - actions.push(Ext.create('Ext.Action', { - icon : '../images/add.png', - text : 'Add', - disabled : false, - handler : function(widget, event) { - _this.onAddButtonClicked.notify(); - } - })); - - return actions; -}; - -ExampleGrid.prototype.refresh = function(dewars) { - this.features = dewars; - this.store.loadData(this._prepareData(dewars), false); -}; - -ExampleGrid.prototype._sort = function(store) { - store.sort('dewarId', 'DESC'); -}; - -ExampleGrid.prototype._prepareData = function() { - var data = []; - for ( var i = 0; i < this.features.length; i++) { - data.push(this.features[i]); - } - return data; -}; - -ExampleGrid.prototype.getPanel = function() { - this.grid = Ext.create('Ext.grid.Panel', { - style : { - padding : 5 - }, - height : this.height, - store : this.store, - columns : this._getColumns(), - viewConfig : { - stripeRows : true, - listeners : { - itemdblclick : function(dataview, record, item, e) { - _this._edit(record.raw); - }, - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonEdit') { - _this._edit(record.raw); - } - - if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonRemove') { - _this.onRemoveButtonClicked.notify(_this.store.getAt(rowIndex).raw.dewarId); - } - } - } - }, - selModel : { - mode : 'SINGLE' - } - }); - - var actions = _this._getTopButtons(); - this.grid.addDocked({ - xtype : 'toolbar', - items : actions - }); - - this.grid.getSelectionModel().on({ - selectionchange : function(sm, selections) { - if (selections.length) { - for ( var i = 0; i < actions.length; i++) { - if (actions[i].enable) { - actions[i].enable(); - } - } - } else { - for ( var i = 0; i < actions.length; i++) { - if (actions[i].alwaysEnabled == false) { - if (actions[i].disable) { - actions[i].disable(); - } - } - } - } - } - }); - return this.grid; -}; - - -ExampleGrid.prototype._getStoreFields = function(data) { - return [ { - name : 'dewarId', - type : 'string' - }, { - name : 'barCode', - type : 'string' - }, { - name : 'code', - type : 'string' - }, { - name : 'comments', - type : 'string' - }, { - name : 'dewarStatus', - type : 'string' - }, { - name : 'isStorageDewar', - type : 'string' - }, { - name : 'plates', - type : 'string' - }, { - name : 'transportValue', - type : 'string' - }, { - name : 'trackingNumberFromSynchrotron', - type : 'string' - }, { - name : 'trackingNumberToSynchrotron', - type : 'string' - }, { - name : 'timeStamp', - type : 'string' - }, { - name : 'storageLocation', - type : 'string' - }, { - name : 'type', - type : 'string' - } - - ]; -}; - -ExampleGrid.prototype._renderGrid = function() { - var _this = this; - - /** Store **/ - var data = this._prepareData(); - this.store = Ext.create('Ext.data.Store', { - fields : this._getStoreFields(data), - autoload : true, - data : data - }); - this._sort(this.store); - - this.store.loadData(data, false); - - this.grid = Ext.create('Ext.grid.Panel', { - style : { - padding : 5 - }, - height : this.height, - store : this.store, - columns : this._getColumns(), - viewConfig : { - stripeRows : true, - listeners : { - itemdblclick : function(dataview, record, item, e) { - _this._edit(record.raw); - }, - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonEdit') { - _this._edit(record.raw); - } - - if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'buttonRemove') { - _this.onRemoveButtonClicked.notify(_this.store.getAt(rowIndex).raw.dewarId); - } - } - } - }, - selModel : { - mode : 'SINGLE' - } - }); - - var actions = _this._getTopButtons(); - this.grid.addDocked({ - xtype : 'toolbar', - items : actions - }); - - this.grid.getSelectionModel().on({ - selectionchange : function(sm, selections) { - if (selections.length) { - for ( var i = 0; i < actions.length; i++) { - if (actions[i].enable) { - actions[i].enable(); - } - } - } else { - for ( var i = 0; i < actions.length; i++) { - if (actions[i].alwaysEnabled == false) { - if (actions[i].disable) { - actions[i].disable(); - } - } - } - } - } - }); - return this.grid; -}; - -ExampleGrid.prototype.input = function() { - return { - proposal : DATADOC.getProposal_10(), - dewars : DATADOC.getDewars_10() - - }; -}; - -ExampleGrid.prototype.test = function(targetId) { - var ExampleGrid = new ExampleGrid({ - height : 150 - }); - BIOSAXS.proposal = new Proposal(ExampleGrid.input().proposal); - var panel = ExampleGrid.getPanel(ExampleGrid.input().dewars); - panel.render(targetId); - -}; + BIOSAXS.proposal = new Proposal(ExampleGrid.input().proposal); + var panel = ExampleGrid.getPanel(ExampleGrid.input().dewars); + panel.render(targetId); + +}; /** @@ -18106,188 +18106,188 @@ ExperimentGrid.prototype.test = function(targetId) { panel.render(targetId); }; - -function FitStructureToExperimentDataGrid(args) { - this.height = null; - this.width = null; - this.id = BUI.id(); - - if (args != null) { - if (args.height != null) { - this.height = args.height; - - if (args.width != null) { - this.width = args.width; - } - } - } - - this.onSelected = new Event(this); -} - -FitStructureToExperimentDataGrid.prototype.getStructuresByMacromolecule = function(macromolecule) { - var structures = []; - if (macromolecule.structure3VOs != null) { - if (macromolecule.structure3VOs.length > 0) { - for (var i = 0; i < macromolecule.structure3VOs.length; i++) { - structures.push(macromolecule.structure3VOs[i]); - } - } - } - return structures; -}; - -FitStructureToExperimentDataGrid.prototype._prepareData = function(subtractions) { - var data = []; - for (var i = 0; i < subtractions.length; i++) { - - for (var j = 0; j < subtractions[i].fitStructureToExperimentalData3VOs.length; j++) { - var fit = subtractions[i].fitStructureToExperimentalData3VOs[j]; - data.push({ - fit : fit.fitFilePath, - fitStructureToExperimentalDataId : fit.fitStructureToExperimentalDataId, - mixtureToStructure3VOs : fit.mixtureToStructure3VOs, - subtractedFile : subtractions[i].substractedFilePath - }); - } - } - return data; - -}; - -FitStructureToExperimentDataGrid.prototype.refresh = function(subtractions) { - this.store.loadData(this._prepareData(subtractions), false); -}; - -FitStructureToExperimentDataGrid.prototype.getPanel = function() { - var _this = this; - this.store = Ext.create('Ext.data.Store', { - fields : [ 'fit', 'subtractedFile', 'structureId', 'fitFilePath', 'mixtureToStructure3VOs' ], - data : [] - }); - - this.store.sort([ { - property : 'name', - direction : 'ASC' - } ]); - - this.selModel = Ext.create('Ext.selection.RowModel', { - allowDeselect : true, - mode : 'MULTI', - listeners : { - selectionchange : function(sm, selections) { - var selected = []; - for (var i = 0; i < selections.length; i++) { - selected.push(selections[i].raw); - } - _this.onSelected.notify(selected); - } - } - }); - - this.panel = Ext.create('Ext.grid.Panel', { - store : this.store, - deferredRender : false, - width : this.width, - height : this.height, - margin : 10, - selModel : this.selModel, - columns : [ { - text : 'Name', - dataIndex : 'fit', - flex : 1, - renderer : function(val, b, record) { - return BUI.getFileName(val); - } - }, { - text : 'PDB', - dataIndex : 'mixtureToStructure3VOs', - flex : 1, - renderer : function(values, b, record) { - var html = ""; - for (var i = 0; i < values.length; i++) { - var structure = BIOSAXS.proposal.getStructuresById(values[i].structureId); - html = html + ""; - if (structure != null){ - html = html + ""; - } - html = html + ""; - } - return html + "
" + structure.name + "
"; - } - }, { - text : 'Volume Fraction', - dataIndex : 'mixtureToStructure3VOs', - flex : 1, - renderer : function(values, b, record) { - var html = ""; - for (var i = 0; i < values.length; i++) { - html = html + ""; - html = html + ""; - html = html + ""; - } - - return html + "
" + values[i].volumeFraction + "
"; - } - },{ - text : 'Subtraction', - dataIndex : 'subtractedFile', - flex : 1, - renderer : function(values, b, record) { - return values.split("/")[values.split("/").length - 1]; - } - },], - - viewConfig : { - enableTextSelection : true, - preserveScrollOnRefresh : true - }, - listeners : { - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - }, - afterrender : function() { - } - } - }); - return this.panel; -}; - -/** Static method **/ -FitStructureToExperimentDataGrid.prototype.RUNFitScattering = function(subtractionId, structureId) { - var _this = this; - /** Add to Workflow **/ - var adapter = new BiosaxsDataAdapter(); - var workflow = { - 'workflowTitle' : 'FitExperimentalDatatoStructure', - 'comments' : 'FitExperimentalDatatoStructure run from ISPyB for subtractionId: ' + subtractionId + ' and structureId ' + structureId - } - - var inputs = [ { - name : 'subtractionId', - value : subtractionId - }, { - name : 'structureId', - value : structureId - } ]; - - adapter.onSuccess.attach(function(sender, data) { - /** Add to Fit **/ - var adapter2 = new BiosaxsDataAdapter(); - var fit = { - 'workflowId' : data.workflowId, - 'subtractionId' : subtractionId, - 'structureId' : structureId, - 'comments' : 'Sent to workflow engine' - } - adapter2.onSuccess.attach(function(sender, fit) { - _this.refresh(_this.subtractionId, _this.macromolecule); - }); - adapter2.addFitStructureData(fit); - - }); - adapter.addWorkflow(workflow, inputs); - -}; + +function FitStructureToExperimentDataGrid(args) { + this.height = null; + this.width = null; + this.id = BUI.id(); + + if (args != null) { + if (args.height != null) { + this.height = args.height; + + if (args.width != null) { + this.width = args.width; + } + } + } + + this.onSelected = new Event(this); +} + +FitStructureToExperimentDataGrid.prototype.getStructuresByMacromolecule = function(macromolecule) { + var structures = []; + if (macromolecule.structure3VOs != null) { + if (macromolecule.structure3VOs.length > 0) { + for (var i = 0; i < macromolecule.structure3VOs.length; i++) { + structures.push(macromolecule.structure3VOs[i]); + } + } + } + return structures; +}; + +FitStructureToExperimentDataGrid.prototype._prepareData = function(subtractions) { + var data = []; + for (var i = 0; i < subtractions.length; i++) { + + for (var j = 0; j < subtractions[i].fitStructureToExperimentalData3VOs.length; j++) { + var fit = subtractions[i].fitStructureToExperimentalData3VOs[j]; + data.push({ + fit : fit.fitFilePath, + fitStructureToExperimentalDataId : fit.fitStructureToExperimentalDataId, + mixtureToStructure3VOs : fit.mixtureToStructure3VOs, + subtractedFile : subtractions[i].substractedFilePath + }); + } + } + return data; + +}; + +FitStructureToExperimentDataGrid.prototype.refresh = function(subtractions) { + this.store.loadData(this._prepareData(subtractions), false); +}; + +FitStructureToExperimentDataGrid.prototype.getPanel = function() { + var _this = this; + this.store = Ext.create('Ext.data.Store', { + fields : [ 'fit', 'subtractedFile', 'structureId', 'fitFilePath', 'mixtureToStructure3VOs' ], + data : [] + }); + + this.store.sort([ { + property : 'name', + direction : 'ASC' + } ]); + + this.selModel = Ext.create('Ext.selection.RowModel', { + allowDeselect : true, + mode : 'MULTI', + listeners : { + selectionchange : function(sm, selections) { + var selected = []; + for (var i = 0; i < selections.length; i++) { + selected.push(selections[i].raw); + } + _this.onSelected.notify(selected); + } + } + }); + + this.panel = Ext.create('Ext.grid.Panel', { + store : this.store, + deferredRender : false, + width : this.width, + height : this.height, + margin : 10, + selModel : this.selModel, + columns : [ { + text : 'Name', + dataIndex : 'fit', + flex : 1, + renderer : function(val, b, record) { + return BUI.getFileName(val); + } + }, { + text : 'PDB', + dataIndex : 'mixtureToStructure3VOs', + flex : 1, + renderer : function(values, b, record) { + var html = ""; + for (var i = 0; i < values.length; i++) { + var structure = BIOSAXS.proposal.getStructuresById(values[i].structureId); + html = html + ""; + if (structure != null){ + html = html + ""; + } + html = html + ""; + } + return html + "
" + structure.name + "
"; + } + }, { + text : 'Volume Fraction', + dataIndex : 'mixtureToStructure3VOs', + flex : 1, + renderer : function(values, b, record) { + var html = ""; + for (var i = 0; i < values.length; i++) { + html = html + ""; + html = html + ""; + html = html + ""; + } + + return html + "
" + values[i].volumeFraction + "
"; + } + },{ + text : 'Subtraction', + dataIndex : 'subtractedFile', + flex : 1, + renderer : function(values, b, record) { + return values.split("/")[values.split("/").length - 1]; + } + },], + + viewConfig : { + enableTextSelection : true, + preserveScrollOnRefresh : true + }, + listeners : { + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + }, + afterrender : function() { + } + } + }); + return this.panel; +}; + +/** Static method **/ +FitStructureToExperimentDataGrid.prototype.RUNFitScattering = function(subtractionId, structureId) { + var _this = this; + /** Add to Workflow **/ + var adapter = new BiosaxsDataAdapter(); + var workflow = { + 'workflowTitle' : 'FitExperimentalDatatoStructure', + 'comments' : 'FitExperimentalDatatoStructure run from ISPyB for subtractionId: ' + subtractionId + ' and structureId ' + structureId + } + + var inputs = [ { + name : 'subtractionId', + value : subtractionId + }, { + name : 'structureId', + value : structureId + } ]; + + adapter.onSuccess.attach(function(sender, data) { + /** Add to Fit **/ + var adapter2 = new BiosaxsDataAdapter(); + var fit = { + 'workflowId' : data.workflowId, + 'subtractionId' : subtractionId, + 'structureId' : structureId, + 'comments' : 'Sent to workflow engine' + } + adapter2.onSuccess.attach(function(sender, fit) { + _this.refresh(_this.subtractionId, _this.macromolecule); + }); + adapter2.addFitStructureData(fit); + + }); + adapter.addWorkflow(workflow, inputs); + +}; /** * It shows buffer grid with a top bar with "Add" button @@ -19893,244 +19893,244 @@ MeasurementGrid.prototype.getPanel = function(measurements, experiments) { }, 1000); } - } catch (e) { - } + } catch (e) { + } + } + } + } + }); + + return this.grid; +}; + +/** Method for testing * */ +MeasurementGrid.prototype.input = function() { + var experiment = DATADOC.getExperiment_10(); + var measurements = DATADOC.getMeasurements_10(); + var proposal = DATADOC.getProposal_10(); + return { + experiment : experiment, + measurements : measurements, + proposal : proposal + }; +}; + +MeasurementGrid.prototype.test = function(targetId) { + var measurementGrid = new MeasurementGrid({ + tbar : true + + }); + BIOSAXS.proposal = new Proposal(measurementGrid.input().proposal); + var panel = measurementGrid.getPanel(measurementGrid.input().measurements, new ExperimentList([ new Experiment(measurementGrid.input().experiment) ])); + panel.render(targetId); +}; + +/** + * A shipment may contains one or more cases where stock solutions and sample + * plates are stored + * + * @height + * @btnEditVisible + * @btnRemoveVisible + * + * #onEditButtonClicked + */ +function MolarityGrid(args) { + this.height = 100; + this.width = 100; + + if (args != null) { + if (args.height != null) { + this.height = args.height; + } + if (args.width != null) { + this.width = args.width; + } + } + + var _this = this; + + this.molarityForm = new MolarityForm({height : 180, width : 455}); + + this.molarityForm.onSave.attach(function(sender){ + _this.molarityWindow.destroy(); + _this.updateProposal(); + + }); + + this.molarityForm.onClose.attach(function(sender){ + _this.molarityWindow.destroy(); + + }); + + /** Events * */ + this.onEditButtonClicked = new Event(this); +} + +MolarityGrid.prototype._getColumns = function() { + return [ { + text : 'Subunit', + columns : [ { + text : "Acronym", + width : 100, + hidden : false, + dataIndex : 'acronym', + sortable : true + }, { + text : "Name", + width : 125, + hidden : false, + dataIndex : 'name', + sortable : true + }, { + text : "MM Est.", + width : 100, + dataIndex : 'molecularMass', + sortable : true, + renderer : function(grid, cls, record){ + return BUI.formatValuesUnits(record.data.molecularMass , "Da", 10, 2); + + } + } ] + }, { +// text : "Number
in assymmetric units", + text : "Ratio", + width : 100, + dataIndex : 'ratio', + tooltip : 'Number of times the subunit is present in the macromolecule', + sortable : true + }, { + id : this.id + 'MOLARITY_REMOVE', + flex : 0.1, + sortable : false, + renderer : function(value, metaData, record, rowIndex, colIndex, store) { + return BUI.getRedButton('REMOVE'); + } + } ]; +}; + +MolarityGrid.prototype._openMolarityWindow = function() { + this.molarityWindow = Ext.create('Ext.window.Window', { + title : 'Molarity', + height : 220, + width : 500, + modal : true, + items : [this.molarityForm.getPanel() ] + }).show(); +}; + +MolarityGrid.prototype._getButtons = function() { + var _this = this; + return [ { + text : 'Add subunit', + icon : '../images/add.png', + handler : function() { + _this._openMolarityWindow(); + } + }]; +}; + + +MolarityGrid.prototype.updateProposal = function() { + var _this = this; + this.panel.setLoading(); + BIOSAXS.proposal.onInitialized.attach(function() { + if (BIOSAXS.proposal != null) { + var macromolecules = BIOSAXS.proposal.macromolecules; + for (var i = 0; i < macromolecules.length; i++) { + + if (macromolecules[i].macromoleculeId == _this.macromolecule.macromoleculeId) { + _this.refresh(macromolecules[i]); + _this.panel.setLoading(false); + } + } + } + }); + BIOSAXS.proposal.init(); +}; + + +MolarityGrid.prototype.getPanel = function() { + var _this = this; + + this.molarityStore = Ext.create('Ext.data.Store', { + fields : [ 'acronym', 'ratio', 'comments', 'stoichiometryId', 'name', 'molecularMass' ], + sorters : { + property : 'ratio', + direction : 'DESC' + } + }); + + this.panel = Ext.create('Ext.grid.Panel', { + store : this.molarityStore, + height : this.height, + padding : 5, + columns : this._getColumns(), + listeners : { + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + + /** Remove entry * */ + if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'MOLARITY_REMOVE') { + var dataAdapter = new BiosaxsDataAdapter(); + dataAdapter.onSuccess.attach(function(sender) { + _this.updateProposal(); + + }); + dataAdapter.removeStoichiometry(record.data.stoichiometryId); + _this.panel.setLoading("Removing Structure"); } } - } + }, + tbar : this._getButtons() }); + return this.panel; +}; - return this.grid; +MolarityGrid.prototype._prepareData = function(macromolecule) { + /** Return an array of [{ratio,acronym, stoichiometryId, name}] **/ + var data = []; + if (macromolecule.stoichiometry != null) { + for (var i = 0; i < macromolecule.stoichiometry.length; i++) { + var hostMacromolecule = BIOSAXS.proposal.getMacromoleculeById(macromolecule.stoichiometry[i].macromoleculeId); + data.push({ + ratio : macromolecule.stoichiometry[i].ratio, + acronym : hostMacromolecule.acronym, + comments : hostMacromolecule.comments, + molecularMass : hostMacromolecule.molecularMass, + stoichiometryId : macromolecule.stoichiometry[i].stoichiometryId, + name : hostMacromolecule.name + }); + } + } + return data; }; -/** Method for testing * */ -MeasurementGrid.prototype.input = function() { - var experiment = DATADOC.getExperiment_10(); - var measurements = DATADOC.getMeasurements_10(); - var proposal = DATADOC.getProposal_10(); +MolarityGrid.prototype.refresh = function(macromolecule) { + if (macromolecule != null){ + this.molarityStore.loadData(this._prepareData(macromolecule)); + this.molarityForm.refresh(macromolecule); + this.macromolecule = macromolecule; + } +}; + +MolarityGrid.prototype.input = function() { return { - experiment : experiment, - measurements : measurements, - proposal : proposal + proposal : DATADOC.getProposal_10(), + dewars : DATADOC.getDewars_10() + }; }; -MeasurementGrid.prototype.test = function(targetId) { - var measurementGrid = new MeasurementGrid({ - tbar : true - +MolarityGrid.prototype.test = function(targetId) { + var MolarityGrid = new MolarityGrid({ + height : 150 }); - BIOSAXS.proposal = new Proposal(measurementGrid.input().proposal); - var panel = measurementGrid.getPanel(measurementGrid.input().measurements, new ExperimentList([ new Experiment(measurementGrid.input().experiment) ])); + BIOSAXS.proposal = new Proposal(MolarityGrid.input().proposal); + var panel = MolarityGrid.getPanel(MolarityGrid.input().dewars); panel.render(targetId); + }; -/** - * A shipment may contains one or more cases where stock solutions and sample - * plates are stored - * - * @height - * @btnEditVisible - * @btnRemoveVisible - * - * #onEditButtonClicked - */ -function MolarityGrid(args) { - this.height = 100; - this.width = 100; - - if (args != null) { - if (args.height != null) { - this.height = args.height; - } - if (args.width != null) { - this.width = args.width; - } - } - - var _this = this; - - this.molarityForm = new MolarityForm({height : 180, width : 455}); - - this.molarityForm.onSave.attach(function(sender){ - _this.molarityWindow.destroy(); - _this.updateProposal(); - - }); - - this.molarityForm.onClose.attach(function(sender){ - _this.molarityWindow.destroy(); - - }); - - /** Events * */ - this.onEditButtonClicked = new Event(this); -} - -MolarityGrid.prototype._getColumns = function() { - return [ { - text : 'Subunit', - columns : [ { - text : "Acronym", - width : 100, - hidden : false, - dataIndex : 'acronym', - sortable : true - }, { - text : "Name", - width : 125, - hidden : false, - dataIndex : 'name', - sortable : true - }, { - text : "MM Est.", - width : 100, - dataIndex : 'molecularMass', - sortable : true, - renderer : function(grid, cls, record){ - return BUI.formatValuesUnits(record.data.molecularMass , "Da", 10, 2); - - } - } ] - }, { -// text : "Number
in assymmetric units", - text : "Ratio", - width : 100, - dataIndex : 'ratio', - tooltip : 'Number of times the subunit is present in the macromolecule', - sortable : true - }, { - id : this.id + 'MOLARITY_REMOVE', - flex : 0.1, - sortable : false, - renderer : function(value, metaData, record, rowIndex, colIndex, store) { - return BUI.getRedButton('REMOVE'); - } - } ]; -}; - -MolarityGrid.prototype._openMolarityWindow = function() { - this.molarityWindow = Ext.create('Ext.window.Window', { - title : 'Molarity', - height : 220, - width : 500, - modal : true, - items : [this.molarityForm.getPanel() ] - }).show(); -}; - -MolarityGrid.prototype._getButtons = function() { - var _this = this; - return [ { - text : 'Add subunit', - icon : '../images/add.png', - handler : function() { - _this._openMolarityWindow(); - } - }]; -}; - - -MolarityGrid.prototype.updateProposal = function() { - var _this = this; - this.panel.setLoading(); - BIOSAXS.proposal.onInitialized.attach(function() { - if (BIOSAXS.proposal != null) { - var macromolecules = BIOSAXS.proposal.macromolecules; - for (var i = 0; i < macromolecules.length; i++) { - - if (macromolecules[i].macromoleculeId == _this.macromolecule.macromoleculeId) { - _this.refresh(macromolecules[i]); - _this.panel.setLoading(false); - } - } - } - }); - BIOSAXS.proposal.init(); -}; - - -MolarityGrid.prototype.getPanel = function() { - var _this = this; - - this.molarityStore = Ext.create('Ext.data.Store', { - fields : [ 'acronym', 'ratio', 'comments', 'stoichiometryId', 'name', 'molecularMass' ], - sorters : { - property : 'ratio', - direction : 'DESC' - } - }); - - this.panel = Ext.create('Ext.grid.Panel', { - store : this.molarityStore, - height : this.height, - padding : 5, - columns : this._getColumns(), - listeners : { - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - - /** Remove entry * */ - if (grid.getGridColumns()[cellIndex].getId() == _this.id + 'MOLARITY_REMOVE') { - var dataAdapter = new BiosaxsDataAdapter(); - dataAdapter.onSuccess.attach(function(sender) { - _this.updateProposal(); - - }); - dataAdapter.removeStoichiometry(record.data.stoichiometryId); - _this.panel.setLoading("Removing Structure"); - } - } - }, - tbar : this._getButtons() - }); - return this.panel; -}; - -MolarityGrid.prototype._prepareData = function(macromolecule) { - /** Return an array of [{ratio,acronym, stoichiometryId, name}] **/ - var data = []; - if (macromolecule.stoichiometry != null) { - for (var i = 0; i < macromolecule.stoichiometry.length; i++) { - var hostMacromolecule = BIOSAXS.proposal.getMacromoleculeById(macromolecule.stoichiometry[i].macromoleculeId); - data.push({ - ratio : macromolecule.stoichiometry[i].ratio, - acronym : hostMacromolecule.acronym, - comments : hostMacromolecule.comments, - molecularMass : hostMacromolecule.molecularMass, - stoichiometryId : macromolecule.stoichiometry[i].stoichiometryId, - name : hostMacromolecule.name - }); - } - } - return data; -}; - -MolarityGrid.prototype.refresh = function(macromolecule) { - if (macromolecule != null){ - this.molarityStore.loadData(this._prepareData(macromolecule)); - this.molarityForm.refresh(macromolecule); - this.macromolecule = macromolecule; - } -}; - -MolarityGrid.prototype.input = function() { - return { - proposal : DATADOC.getProposal_10(), - dewars : DATADOC.getDewars_10() - - }; -}; - -MolarityGrid.prototype.test = function(targetId) { - var MolarityGrid = new MolarityGrid({ - height : 150 - }); - BIOSAXS.proposal = new Proposal(MolarityGrid.input().proposal); - var panel = MolarityGrid.getPanel(MolarityGrid.input().dewars); - panel.render(targetId); - -}; - /** * Given data analysis parsed with ResultsAssemblyWidget makes a selector grid with buffer/protein @@ -20815,135 +20815,135 @@ ResultsAssemblyGrid.prototype.test = function(targetId) { }; - -function RigidModelGrid(args) { - this.height = null; - this.width = null; - this.id = BUI.id(); - - if (args != null) { - if (args.height != null) { - this.height = args.height; - - if (args.width != null) { - this.width = args.width; - } - } - } - - this.onSelected = new Event(this); -} - - -RigidModelGrid.prototype.refresh = function(subtractions) { - var data = []; - if (subtractions != null){ - if (subtractions.length > 0){ - for (j in subtractions){ - var subtraction = subtractions[j]; - if (subtraction.rigidBodyModeling3VOs != null){ - for (i in subtraction.rigidBodyModeling3VOs){ - data.push(subtraction.rigidBodyModeling3VOs[i]); - } - } - } - } - } - this.store.loadData(data); -}; - -RigidModelGrid.prototype.getPanel = function() { - var _this = this; - this.store = Ext.create('Ext.data.Store', { - fields : [ 'symmetry', 'subtractionId', 'subUnitConfigFilePath', 'rigidBodyModelingId', 'rigidBodyModelFilePath', 'logFilePath', 'fitFilePath', 'curveConfigFilePath', - 'crossCorrConfigFilePath', 'contactDescriptionFilePath' ], - data : [] - }); - - this.store.sort([ { - property : 'name', - direction : 'ASC' - } ]); - - this.panel = Ext.create('Ext.grid.Panel', { - store : this.store, - width : this.width, - height : this.height, - margin : 10, - deferredRender : false, - columns : [ { - text : 'RBM', - dataIndex : 'rigidBodyModelFilePath', - hidden : false, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - }, { - text : 'Sub Unit Conf.', - dataIndex : 'subUnitConfigFilePath', - hidden : true, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - }, { - text : 'Log', - dataIndex : 'logFilePath', - hidden : true, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - }, { - text : 'Fit', - dataIndex : 'fitFilePath', - hidden : false, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - }, { - text : 'Curve Conf.', - dataIndex : 'curveConfigFilePath', - hidden : false, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - }, { - text : 'Cross Corr.', - dataIndex : 'crossCorrConfigFilePath', - hidden : false, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - }, { - text : 'Contact Desc.', - dataIndex : 'contactDescriptionFilePath', - hidden : true, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - } ], - - viewConfig : { - enableTextSelection : true, - preserveScrollOnRefresh : true - }, - listeners : { - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - - }, - afterrender : function() { - } - } - }); - return this.panel; -}; - + +function RigidModelGrid(args) { + this.height = null; + this.width = null; + this.id = BUI.id(); + + if (args != null) { + if (args.height != null) { + this.height = args.height; + + if (args.width != null) { + this.width = args.width; + } + } + } + + this.onSelected = new Event(this); +} + + +RigidModelGrid.prototype.refresh = function(subtractions) { + var data = []; + if (subtractions != null){ + if (subtractions.length > 0){ + for (j in subtractions){ + var subtraction = subtractions[j]; + if (subtraction.rigidBodyModeling3VOs != null){ + for (i in subtraction.rigidBodyModeling3VOs){ + data.push(subtraction.rigidBodyModeling3VOs[i]); + } + } + } + } + } + this.store.loadData(data); +}; + +RigidModelGrid.prototype.getPanel = function() { + var _this = this; + this.store = Ext.create('Ext.data.Store', { + fields : [ 'symmetry', 'subtractionId', 'subUnitConfigFilePath', 'rigidBodyModelingId', 'rigidBodyModelFilePath', 'logFilePath', 'fitFilePath', 'curveConfigFilePath', + 'crossCorrConfigFilePath', 'contactDescriptionFilePath' ], + data : [] + }); + + this.store.sort([ { + property : 'name', + direction : 'ASC' + } ]); + + this.panel = Ext.create('Ext.grid.Panel', { + store : this.store, + width : this.width, + height : this.height, + margin : 10, + deferredRender : false, + columns : [ { + text : 'RBM', + dataIndex : 'rigidBodyModelFilePath', + hidden : false, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + }, { + text : 'Sub Unit Conf.', + dataIndex : 'subUnitConfigFilePath', + hidden : true, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + }, { + text : 'Log', + dataIndex : 'logFilePath', + hidden : true, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + }, { + text : 'Fit', + dataIndex : 'fitFilePath', + hidden : false, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + }, { + text : 'Curve Conf.', + dataIndex : 'curveConfigFilePath', + hidden : false, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + }, { + text : 'Cross Corr.', + dataIndex : 'crossCorrConfigFilePath', + hidden : false, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + }, { + text : 'Contact Desc.', + dataIndex : 'contactDescriptionFilePath', + hidden : true, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + } ], + + viewConfig : { + enableTextSelection : true, + preserveScrollOnRefresh : true + }, + listeners : { + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + + }, + afterrender : function() { + } + } + }); + return this.panel; +}; + /** * shows shipments @@ -22309,119 +22309,119 @@ StockSolutionGrid.prototype.test = function(targetId) { panel.render(targetId); }; - -function SuperpositionGrid(args) { - this.height = null; - this.width = null; - this.id = BUI.id(); - - if (args != null) { - if (args.height != null) { - this.height = args.height; - - if (args.width != null) { - this.width = args.width; - } - } - } - - this.onSelected = new Event(this); -} - -SuperpositionGrid.prototype._prepareData = function(data) { - return data; -}; - -SuperpositionGrid.prototype.refresh = function(subtractions) { - var data = []; - if (subtractions != null){ - if (subtractions.length > 0){ - for (j in subtractions){ - var subtraction = subtractions[j]; - if (subtraction.superposition3VOs != null){ - for (i in subtraction.superposition3VOs){ - data.push(subtraction.superposition3VOs[i]); - } - } - } - } - } - this.store.loadData(data); -}; - -SuperpositionGrid.prototype.getPanel = function() { - var _this = this; - this.store = Ext.create('Ext.data.Store', { - fields : [ 'abinitioModelPdbFilePath', 'aprioriPdbFilePath', 'alignedPdbFilePath' ], - data : [] - }); - - this.selModel = Ext.create('Ext.selection.RowModel', { - allowDeselect : true, - mode : 'MULTI', - listeners : { - selectionchange : function(sm, selections) { - var selected = []; - for (var i = 0; i < selections.length; i++) { - selected.push(selections[i].raw); - } - _this.onSelected.notify(selected); - } - } - }); - - this.store.sort([ { - property : 'name', - direction : 'ASC' - } ]); - - this.panel = Ext.create('Ext.grid.Panel', { - store : this.store, - selModel : this.selModel, - width : this.width, - height : this.height, - margin : 10, - deferredRender : false, - columns : [ { - text : 'Abinitio', - dataIndex : 'abinitioModelPdbFilePath', - hidden : false, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - }, { - text : 'Apriori', - dataIndex : 'aprioriPdbFilePath', - hidden : false, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - }, { - text : 'Aligned', - dataIndex : 'alignedPdbFilePath', - hidden : false, - flex : 1, - renderer : function(val){ - return BUI.getFileName(val); - } - } ], - - viewConfig : { - enableTextSelection : true, - preserveScrollOnRefresh : true - }, - listeners : { - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - - }, - afterrender : function() { - } - } - }); - return this.panel; -}; + +function SuperpositionGrid(args) { + this.height = null; + this.width = null; + this.id = BUI.id(); + + if (args != null) { + if (args.height != null) { + this.height = args.height; + + if (args.width != null) { + this.width = args.width; + } + } + } + + this.onSelected = new Event(this); +} + +SuperpositionGrid.prototype._prepareData = function(data) { + return data; +}; + +SuperpositionGrid.prototype.refresh = function(subtractions) { + var data = []; + if (subtractions != null){ + if (subtractions.length > 0){ + for (j in subtractions){ + var subtraction = subtractions[j]; + if (subtraction.superposition3VOs != null){ + for (i in subtraction.superposition3VOs){ + data.push(subtraction.superposition3VOs[i]); + } + } + } + } + } + this.store.loadData(data); +}; + +SuperpositionGrid.prototype.getPanel = function() { + var _this = this; + this.store = Ext.create('Ext.data.Store', { + fields : [ 'abinitioModelPdbFilePath', 'aprioriPdbFilePath', 'alignedPdbFilePath' ], + data : [] + }); + + this.selModel = Ext.create('Ext.selection.RowModel', { + allowDeselect : true, + mode : 'MULTI', + listeners : { + selectionchange : function(sm, selections) { + var selected = []; + for (var i = 0; i < selections.length; i++) { + selected.push(selections[i].raw); + } + _this.onSelected.notify(selected); + } + } + }); + + this.store.sort([ { + property : 'name', + direction : 'ASC' + } ]); + + this.panel = Ext.create('Ext.grid.Panel', { + store : this.store, + selModel : this.selModel, + width : this.width, + height : this.height, + margin : 10, + deferredRender : false, + columns : [ { + text : 'Abinitio', + dataIndex : 'abinitioModelPdbFilePath', + hidden : false, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + }, { + text : 'Apriori', + dataIndex : 'aprioriPdbFilePath', + hidden : false, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + }, { + text : 'Aligned', + dataIndex : 'alignedPdbFilePath', + hidden : false, + flex : 1, + renderer : function(val){ + return BUI.getFileName(val); + } + } ], + + viewConfig : { + enableTextSelection : true, + preserveScrollOnRefresh : true + }, + listeners : { + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + + }, + afterrender : function() { + } + } + }); + return this.panel; +}; /** * See ExperimentGrid @@ -26158,502 +26158,502 @@ ConcentrationHTMLTableWidget.prototype.input = function() { "values" : [] } } - } ] - }, - "concentrationLabel" : "7.17 mg/ml ,3.53 mg/ml ,1.75 mg/ml ,0.91 mg/ml " + } ] + }, + "concentrationLabel" : "7.17 mg/ml ,3.53 mg/ml ,1.75 mg/ml ,0.91 mg/ml " + } + }; +}; + +ConcentrationHTMLTableWidget.prototype.test = function(targetId) { + var concentrationHTMLTableWidget = new ConcentrationHTMLTableWidget(); + document.getElementById(targetId).innerHTML = concentrationHTMLTableWidget.getPanel(concentrationHTMLTableWidget.input().data); +}; + +function DataCollectionWidget() { + +}; + +DataCollectionWidget.prototype.refresh = function(subtractionId) { + +}; + +DataCollectionWidget.prototype.getMacromolecule = function(data) { + for (var i = 0; i < data.length; i++) { + if (data[i].macromoleculeId != null) { + return BIOSAXS.proposal.getMacromoleculeById(data[i].macromoleculeId); + } + } + return null; +}; + +DataCollectionWidget.prototype.getMacromoleculeContainer = function(data) { + var macromolecule = this.getMacromolecule(data); + + var disabled = false; + if (macromolecule == null) { + disabled = true; + } + + var acronym = (macromolecule == null ? "" : macromolecule.acronym); + var mm = (macromolecule == null ? "" : macromolecule.molecularMass); + var comments = (macromolecule == null ? "" : macromolecule.comments); + + return Ext.create('Ext.Panel', { + width : 500, + height : 200, + disabled : disabled, + title : "Macromolecule", + layout : 'form', + bodyPadding : 5, + defaultType : 'textfield', + tbar : { + defaultButtonUI : 'default', + items : [ { + xtype : 'button', + text : 'Edit', + cls : 'btn-with-border', + handler : function() { + var macromoleculeWindow = new MacromoleculeWindow(); + macromoleculeWindow.draw(macromolecule); + /** TODO: update when save **/ + } + } ] + }, + items : [ { + fieldLabel : 'Acronym', + name : 'first', + readOnly : true, + value : acronym + }, { + fieldLabel : 'Molecular Mass', + name : 'last', + readOnly : true, + value : mm + }, { + xtype : 'textareafield', + fieldLabel : 'Comments', + value : '', + name : 'last', + readOnly : true, + value : comments + } ] + }); +}; + +DataCollectionWidget.prototype.getBufferContainer = function(data) { + var _this = this; + var buffer = BIOSAXS.proposal.getBufferById(data[0].bufferId); + + return Ext.create('Ext.Panel', { + width : 500, + height : 200, + title : "Buffer", + layout : 'form', + // collapsed : true, + // collapsible : true, + bodyPadding : 5, + defaultType : 'textfield', + style : { + padding : '0px 0px 0px 2px' + }, + tbar : { + defaultButtonUI : 'default', + items : [ { + xtype : 'button', + text : 'Edit', + cls : 'btn-with-border', + handler : function() { + var bufferWindow = new BufferWindow(); + bufferWindow.draw(BIOSAXS.proposal.getBufferById(data[0].bufferId)); + /** TODO: update when save **/ + } + + } ] + }, + items : [ { + fieldLabel : 'Buffer', + name : 'acronym', + readOnly : true, + value : buffer.acronym + }, { + fieldLabel : 'Composition', + name : 'last', + readOnly : true, + value : buffer.composition + }, { + xtype : 'textareafield', + fieldLabel : 'Comments', + value : buffer.comments, + name : 'last', + readOnly : true + + } ] + }); +}; + +DataCollectionWidget.prototype.getSpecimenContainer = function(data) { + return Ext.create('Ext.container.Container', { + layout : { + type : 'hbox' + }, + style : { + margin : '10px 10px 10px 10px' + }, + border : 0, + style : { + borderColor : '#000000', + borderStyle : 'solid', + borderWidth : '1px' + }, + defaults : { + labelWidth : 80, + // implicitly create Container by specifying xtype + xtype : 'datefield', + flex : 1, + + }, + items : [ this.getMacromoleculeContainer(data), this.getBufferContainer(data) ] + }); +}; + +DataCollectionWidget.prototype.getSeparator = function() { + return { + html : "
", + border : 0 + } +}; + +DataCollectionWidget.prototype.getFitStructurePanel = function(data) { + var _this = this; + + return Ext.create('Ext.container.Container', { + layout : { + type : 'hbox' + }, + style : { + margin : '10px 10px 10px 10px' + }, + border : 0, + style : { + borderColor : '#000000', + borderStyle : 'solid', + borderWidth : '1px' + }, + defaults : { + labelWidth : 80, + xtype : 'datefield', + flex : 1 + }, + items : [ + + ] + }); +}; + +DataCollectionWidget.prototype.getFitStructurePanelWorkflow = function(data) { + var _this = this; + var macromolecule = this.getMacromolecule(data); + + var items = []; + + /** Adding all the pdb files linked to the macromolecule **/ + // if (macromolecule.structure3VOs != null) { + // if (macromolecule.structure3VOs.length > 0) { + // + // items.push(); + // } + // } else { + // items.push({ + // html : "No apriori information added to this macromolecule. Apriori information needed for further analysis", + // margin : "5 5 5 5" + // }); + // } + var fitStructureToExperimentDataGrid = new FitStructureToExperimentDataGrid(); + + fitStructureToExperimentDataGrid.refresh(_this.data[0].subtractionId, _this.getMacromolecule(data)); + return Ext.create('Ext.container.Container', { + style : { + margin : '10px 10px 10px 10px' + }, + border : 0, + + style : { + borderColor : '#000000', + borderStyle : 'solid', + borderWidth : '1px' + }, + defaults : { + labelWidth : 80, + xtype : 'datefield', + flex : 1 + }, + items : [ fitStructureToExperimentDataGrid.getPanel() ], + listeners : { + afterrender : function() { + } + } + }); +}; +/** Static method **/ +DataCollectionWidget.prototype.RUNFitScattering = function(subtractionId, structureId) { + var _this = this; + /** Add to Workflow **/ + var adapter = new BiosaxsDataAdapter(); + var workflow = { + 'workflowTitle' : 'FitExperimentalDatatoStructure', + 'comments' : 'FitExperimentalDatatoStructure run from ISPyB for subtractionId: ' + subtractionId + ' and structureId ' + structureId + } + + var inputs = [ { + name : 'subtractionId', + value : subtractionId + }, { + name : 'structureId', + value : structureId + } ]; + + adapter.onSuccess.attach(function(sender, data) { + /** Add to Fit **/ + var adapter2 = new BiosaxsDataAdapter(); + var fit = { + 'workflowId' : data.workflowId, + 'subtractionId' : subtractionId, + 'structureId' : structureId, + 'comments' : 'Sent to workflow engine' + } + adapter2.onSuccess.attach(function(sender, fit) { + + }); + adapter2.addFitStructureData(fit); + + }); + adapter.addWorkflow(workflow, inputs); + +}; + +DataCollectionWidget.prototype.getSuperpositionTab = function(data) { + var _this = this; + + this.superpositionGrid = new SuperpositionGrid(); + + return Ext.create('Ext.container.Container', { + style : { + margin : '10px 10px 10px 10px' + }, + border : 0, + style : { + borderColor : '#000000', + borderStyle : 'solid', + borderWidth : '1px' + }, + items : [ _this.superpositionGrid.getPanel() ], + listeners : { + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + + }, + afterrender : function() { + /** Getting Rigid bodies **/ + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, result) { + _this.superpositionGrid.refresh(result); + }); + adapter.getSuperpositionBySubtractionId(data[1].subtractionId); + } + } + }); +}; + +DataCollectionWidget.prototype.getAdvancedTab = function(data) { + var _this = this; + return Ext.create('Ext.container.Container', { + style : { + margin : '10px 10px 10px 10px' + }, + border : 0, + style : { + borderColor : '#000000', + borderStyle : 'solid', + borderWidth : '1px' + }, + items : [ _this.getFitStructurePanel(data), _this.getFitStructurePanelWorkflow(data) ] + }); +}; + +DataCollectionWidget.prototype.getRigiBodyForm = function(data) { + var _this = this; + _this.rigiBodyGrid = new RigidModelGrid(); + return _this.rigiBodyGrid.getPanel(); + +}; + +DataCollectionWidget.prototype.getRigidBodyModelingTab = function(data) { + var _this = this; + return Ext.create('Ext.container.Container', { + style : { + margin : '10px 10px 10px 10px' + }, + border : 0, + style : { + borderColor : '#000000', + borderStyle : 'solid', + borderWidth : '1px' + }, + items : [ _this.getRigiBodyForm(data) ], + listeners : { + cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { + + }, + afterrender : function() { + /** Getting Rigid bodies **/ + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, result) { + _this.rigiBodyGrid.refresh(result); + }); + adapter.getRigidBodyModelingBySubtractionId(data[1].subtractionId); + } + } + }); +}; + +DataCollectionWidget.prototype.getTabs = function(data) { + var _this = this; + + this.subtractionCurveVisualizer = new SubtractionCurveVisualizer(); + + this.tabs = Ext.createWidget('tabpanel', { + activeTab : 1, + plain : true, + defaults : { + autoScroll : true, + bodyPadding : 10 + }, + items : [ { + title : 'Solution', + items : [ _this.getSpecimenContainer(data) ] + }, { + title : 'Primary Data Reduction', + active : true, + tabConfig : { + xtype : 'tab', + margins : '0 0 0 20', + }, + items : [ _this.subtractionCurveVisualizer.getPanel() ] + }, { + title : 'Abinitio', + items : [ _this.getAbinitioModellingContainer(data), _this.getSeparator(), _this.getModelViz(data) ] + }, { + title : 'Mixtures', + items : [ _this.getAdvancedTab(data) ] + }, { + title : 'Superpositions', + items : [ _this.getSuperpositionTab(data) ] + }, { + title : 'Rigid Body Modeling', + items : [ _this.getRigidBodyModelingTab(data) ] + } ] + }); + return this.tabs; +}; + +DataCollectionWidget.prototype.getPanel = function(data) { + var _this = this; + _this.data = data; + this.panel = Ext.create('Ext.container.Container', { + width : 1000, + layout : { + type : 'vbox', + align : 'stretch', + padding : 5 + }, + items : [ _this.getTabs(data) + + ] + }); + + this.panel.on("afterrender", function() { + _this.subtractionCurveVisualizer.refresh([ _this.data[1].mergeId ], [ _this.data[1].subtractionId ]); + }); + return this.panel; +}; + +DataCollectionWidget.prototype.getModelViz = function(data) { + this.modelViz = new ModelVisualizerForm({ + height : 800, + width : 1000 + }); + return this.modelViz.getPanel(); +}; + +/** + * PRIMARY DATA PROCESSING + */ +DataCollectionWidget.prototype.getPrimaryDataProcessingContainer = function(data) { + var _this = this; + this.primaryDataProcessingGrid = new PrimaryDataProcessingGrid({ + height : 250, + width : 1000, + title : 'Primary Data Processing' + }); + + this.primaryDataProcessingGrid.onSelected.attach(function(sender, selected) { + /** Refresh tabs **/ + var averagesId = []; + var subtractionIds = []; + + var subtractionKeys = {}; + for (var i = 0; i < selected.length; i++) { + if (selected[i].mergeId != null) { + averagesId.push(selected[i].mergeId); + } + + if (selected[i].subtractionId != null) { + if (selected[i].macromoleculeId != null) { + if (subtractionKeys[selected[i].subtractionId] == null) { + subtractionIds.push(selected[i].subtractionId); + } + subtractionKeys[selected[i].subtractionId] = true; + } + } } - }; + + /** Refreshing Primary Data Reduction **/ + _this.subtractionCurveVisualizer.refresh(averagesId, subtractionIds); + + }); + return this.primaryDataProcessingGrid.getPanel(data); }; +/** + * getAbinitioModellingContainer + */ +DataCollectionWidget.prototype.getAbinitioModellingContainer = function(data) { + var _this = this; -ConcentrationHTMLTableWidget.prototype.test = function(targetId) { - var concentrationHTMLTableWidget = new ConcentrationHTMLTableWidget(); - document.getElementById(targetId).innerHTML = concentrationHTMLTableWidget.getPanel(concentrationHTMLTableWidget.input().data); + this.abinitioGrid = new AbinitioGrid(); + this.abinitioGrid.onSelected.attach(function(sender, models) { + _this.modelViz.refresh(models); + + }); + /** It may be abinitio models linked to the buffers **/ + var abinitioIdList = []; + for (var i = 0; i < data.length; i++) { + abinitioIdList.push(data[i].abInitioId); + } + + var uniqueIds = []; + $.each(abinitioIdList, function(i, el) { + if ($.inArray(el, uniqueIds) === -1) + uniqueIds.push(el); + }); + + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, data) { + _this.abinitioGrid.refresh(data); + }); + adapter.getAbinitioByIdsList(uniqueIds); + return this.abinitioGrid.getPanel([]); }; -function DataCollectionWidget() { - -}; - -DataCollectionWidget.prototype.refresh = function(subtractionId) { - -}; - -DataCollectionWidget.prototype.getMacromolecule = function(data) { - for (var i = 0; i < data.length; i++) { - if (data[i].macromoleculeId != null) { - return BIOSAXS.proposal.getMacromoleculeById(data[i].macromoleculeId); - } - } - return null; -}; - -DataCollectionWidget.prototype.getMacromoleculeContainer = function(data) { - var macromolecule = this.getMacromolecule(data); - - var disabled = false; - if (macromolecule == null) { - disabled = true; - } - - var acronym = (macromolecule == null ? "" : macromolecule.acronym); - var mm = (macromolecule == null ? "" : macromolecule.molecularMass); - var comments = (macromolecule == null ? "" : macromolecule.comments); - - return Ext.create('Ext.Panel', { - width : 500, - height : 200, - disabled : disabled, - title : "Macromolecule", - layout : 'form', - bodyPadding : 5, - defaultType : 'textfield', - tbar : { - defaultButtonUI : 'default', - items : [ { - xtype : 'button', - text : 'Edit', - cls : 'btn-with-border', - handler : function() { - var macromoleculeWindow = new MacromoleculeWindow(); - macromoleculeWindow.draw(macromolecule); - /** TODO: update when save **/ - } - } ] - }, - items : [ { - fieldLabel : 'Acronym', - name : 'first', - readOnly : true, - value : acronym - }, { - fieldLabel : 'Molecular Mass', - name : 'last', - readOnly : true, - value : mm - }, { - xtype : 'textareafield', - fieldLabel : 'Comments', - value : '', - name : 'last', - readOnly : true, - value : comments - } ] - }); -}; - -DataCollectionWidget.prototype.getBufferContainer = function(data) { - var _this = this; - var buffer = BIOSAXS.proposal.getBufferById(data[0].bufferId); - - return Ext.create('Ext.Panel', { - width : 500, - height : 200, - title : "Buffer", - layout : 'form', - // collapsed : true, - // collapsible : true, - bodyPadding : 5, - defaultType : 'textfield', - style : { - padding : '0px 0px 0px 2px' - }, - tbar : { - defaultButtonUI : 'default', - items : [ { - xtype : 'button', - text : 'Edit', - cls : 'btn-with-border', - handler : function() { - var bufferWindow = new BufferWindow(); - bufferWindow.draw(BIOSAXS.proposal.getBufferById(data[0].bufferId)); - /** TODO: update when save **/ - } - - } ] - }, - items : [ { - fieldLabel : 'Buffer', - name : 'acronym', - readOnly : true, - value : buffer.acronym - }, { - fieldLabel : 'Composition', - name : 'last', - readOnly : true, - value : buffer.composition - }, { - xtype : 'textareafield', - fieldLabel : 'Comments', - value : buffer.comments, - name : 'last', - readOnly : true - - } ] - }); -}; - -DataCollectionWidget.prototype.getSpecimenContainer = function(data) { - return Ext.create('Ext.container.Container', { - layout : { - type : 'hbox' - }, - style : { - margin : '10px 10px 10px 10px' - }, - border : 0, - style : { - borderColor : '#000000', - borderStyle : 'solid', - borderWidth : '1px' - }, - defaults : { - labelWidth : 80, - // implicitly create Container by specifying xtype - xtype : 'datefield', - flex : 1, - - }, - items : [ this.getMacromoleculeContainer(data), this.getBufferContainer(data) ] - }); -}; - -DataCollectionWidget.prototype.getSeparator = function() { - return { - html : "
", - border : 0 - } -}; - -DataCollectionWidget.prototype.getFitStructurePanel = function(data) { - var _this = this; - - return Ext.create('Ext.container.Container', { - layout : { - type : 'hbox' - }, - style : { - margin : '10px 10px 10px 10px' - }, - border : 0, - style : { - borderColor : '#000000', - borderStyle : 'solid', - borderWidth : '1px' - }, - defaults : { - labelWidth : 80, - xtype : 'datefield', - flex : 1 - }, - items : [ - - ] - }); -}; - -DataCollectionWidget.prototype.getFitStructurePanelWorkflow = function(data) { - var _this = this; - var macromolecule = this.getMacromolecule(data); - - var items = []; - - /** Adding all the pdb files linked to the macromolecule **/ - // if (macromolecule.structure3VOs != null) { - // if (macromolecule.structure3VOs.length > 0) { - // - // items.push(); - // } - // } else { - // items.push({ - // html : "No apriori information added to this macromolecule. Apriori information needed for further analysis", - // margin : "5 5 5 5" - // }); - // } - var fitStructureToExperimentDataGrid = new FitStructureToExperimentDataGrid(); - - fitStructureToExperimentDataGrid.refresh(_this.data[0].subtractionId, _this.getMacromolecule(data)); - return Ext.create('Ext.container.Container', { - style : { - margin : '10px 10px 10px 10px' - }, - border : 0, - - style : { - borderColor : '#000000', - borderStyle : 'solid', - borderWidth : '1px' - }, - defaults : { - labelWidth : 80, - xtype : 'datefield', - flex : 1 - }, - items : [ fitStructureToExperimentDataGrid.getPanel() ], - listeners : { - afterrender : function() { - } - } - }); -}; -/** Static method **/ -DataCollectionWidget.prototype.RUNFitScattering = function(subtractionId, structureId) { - var _this = this; - /** Add to Workflow **/ - var adapter = new BiosaxsDataAdapter(); - var workflow = { - 'workflowTitle' : 'FitExperimentalDatatoStructure', - 'comments' : 'FitExperimentalDatatoStructure run from ISPyB for subtractionId: ' + subtractionId + ' and structureId ' + structureId - } - - var inputs = [ { - name : 'subtractionId', - value : subtractionId - }, { - name : 'structureId', - value : structureId - } ]; - - adapter.onSuccess.attach(function(sender, data) { - /** Add to Fit **/ - var adapter2 = new BiosaxsDataAdapter(); - var fit = { - 'workflowId' : data.workflowId, - 'subtractionId' : subtractionId, - 'structureId' : structureId, - 'comments' : 'Sent to workflow engine' - } - adapter2.onSuccess.attach(function(sender, fit) { - - }); - adapter2.addFitStructureData(fit); - - }); - adapter.addWorkflow(workflow, inputs); - -}; - -DataCollectionWidget.prototype.getSuperpositionTab = function(data) { - var _this = this; - - this.superpositionGrid = new SuperpositionGrid(); - - return Ext.create('Ext.container.Container', { - style : { - margin : '10px 10px 10px 10px' - }, - border : 0, - style : { - borderColor : '#000000', - borderStyle : 'solid', - borderWidth : '1px' - }, - items : [ _this.superpositionGrid.getPanel() ], - listeners : { - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - - }, - afterrender : function() { - /** Getting Rigid bodies **/ - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, result) { - _this.superpositionGrid.refresh(result); - }); - adapter.getSuperpositionBySubtractionId(data[1].subtractionId); - } - } - }); -}; - -DataCollectionWidget.prototype.getAdvancedTab = function(data) { - var _this = this; - return Ext.create('Ext.container.Container', { - style : { - margin : '10px 10px 10px 10px' - }, - border : 0, - style : { - borderColor : '#000000', - borderStyle : 'solid', - borderWidth : '1px' - }, - items : [ _this.getFitStructurePanel(data), _this.getFitStructurePanelWorkflow(data) ] - }); -}; - -DataCollectionWidget.prototype.getRigiBodyForm = function(data) { - var _this = this; - _this.rigiBodyGrid = new RigidModelGrid(); - return _this.rigiBodyGrid.getPanel(); - -}; - -DataCollectionWidget.prototype.getRigidBodyModelingTab = function(data) { - var _this = this; - return Ext.create('Ext.container.Container', { - style : { - margin : '10px 10px 10px 10px' - }, - border : 0, - style : { - borderColor : '#000000', - borderStyle : 'solid', - borderWidth : '1px' - }, - items : [ _this.getRigiBodyForm(data) ], - listeners : { - cellclick : function(grid, td, cellIndex, record, tr, rowIndex, e, eOpts) { - - }, - afterrender : function() { - /** Getting Rigid bodies **/ - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, result) { - _this.rigiBodyGrid.refresh(result); - }); - adapter.getRigidBodyModelingBySubtractionId(data[1].subtractionId); - } - } - }); -}; - -DataCollectionWidget.prototype.getTabs = function(data) { - var _this = this; - - this.subtractionCurveVisualizer = new SubtractionCurveVisualizer(); - - this.tabs = Ext.createWidget('tabpanel', { - activeTab : 1, - plain : true, - defaults : { - autoScroll : true, - bodyPadding : 10 - }, - items : [ { - title : 'Solution', - items : [ _this.getSpecimenContainer(data) ] - }, { - title : 'Primary Data Reduction', - active : true, - tabConfig : { - xtype : 'tab', - margins : '0 0 0 20', - }, - items : [ _this.subtractionCurveVisualizer.getPanel() ] - }, { - title : 'Abinitio', - items : [ _this.getAbinitioModellingContainer(data), _this.getSeparator(), _this.getModelViz(data) ] - }, { - title : 'Mixtures', - items : [ _this.getAdvancedTab(data) ] - }, { - title : 'Superpositions', - items : [ _this.getSuperpositionTab(data) ] - }, { - title : 'Rigid Body Modeling', - items : [ _this.getRigidBodyModelingTab(data) ] - } ] - }); - return this.tabs; -}; - -DataCollectionWidget.prototype.getPanel = function(data) { - var _this = this; - _this.data = data; - this.panel = Ext.create('Ext.container.Container', { - width : 1000, - layout : { - type : 'vbox', - align : 'stretch', - padding : 5 - }, - items : [ _this.getTabs(data) - - ] - }); - - this.panel.on("afterrender", function() { - _this.subtractionCurveVisualizer.refresh([ _this.data[1].mergeId ], [ _this.data[1].subtractionId ]); - }); - return this.panel; -}; - -DataCollectionWidget.prototype.getModelViz = function(data) { - this.modelViz = new ModelVisualizerForm({ - height : 800, - width : 1000 - }); - return this.modelViz.getPanel(); -}; - -/** - * PRIMARY DATA PROCESSING - */ -DataCollectionWidget.prototype.getPrimaryDataProcessingContainer = function(data) { - var _this = this; - this.primaryDataProcessingGrid = new PrimaryDataProcessingGrid({ - height : 250, - width : 1000, - title : 'Primary Data Processing' - }); - - this.primaryDataProcessingGrid.onSelected.attach(function(sender, selected) { - /** Refresh tabs **/ - var averagesId = []; - var subtractionIds = []; - - var subtractionKeys = {}; - for (var i = 0; i < selected.length; i++) { - if (selected[i].mergeId != null) { - averagesId.push(selected[i].mergeId); - } - - if (selected[i].subtractionId != null) { - if (selected[i].macromoleculeId != null) { - if (subtractionKeys[selected[i].subtractionId] == null) { - subtractionIds.push(selected[i].subtractionId); - } - subtractionKeys[selected[i].subtractionId] = true; - } - } - } - - /** Refreshing Primary Data Reduction **/ - _this.subtractionCurveVisualizer.refresh(averagesId, subtractionIds); - - }); - return this.primaryDataProcessingGrid.getPanel(data); -}; -/** - * getAbinitioModellingContainer - */ -DataCollectionWidget.prototype.getAbinitioModellingContainer = function(data) { - var _this = this; - - this.abinitioGrid = new AbinitioGrid(); - this.abinitioGrid.onSelected.attach(function(sender, models) { - _this.modelViz.refresh(models); - - }); - /** It may be abinitio models linked to the buffers **/ - var abinitioIdList = []; - for (var i = 0; i < data.length; i++) { - abinitioIdList.push(data[i].abInitioId); - } - - var uniqueIds = []; - $.each(abinitioIdList, function(i, el) { - if ($.inArray(el, uniqueIds) === -1) - uniqueIds.push(el); - }); - - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, data) { - _this.abinitioGrid.refresh(data); - }); - adapter.getAbinitioByIdsList(uniqueIds); - return this.abinitioGrid.getPanel([]); -}; - /** * Edit the information of a buffer * @@ -29163,258 +29163,258 @@ ShippingWidget.prototype.refresh = function() { }; -/** - * Widget container of Specimen grid and samplePlate widget - * Depending of the sample changer layout it may be displayed vertically or horizontally - * - * @param args - * - * #onExperimentChanged It happens when specimen are modified - */ -function SpecimenWidget(args){ - - this.width = 1000; - this.height = 600; - - if (args != null){ - if (args.width != null){ - this.width = args.width; - } - if (args.height != null){ - this.height = args.height; - } - } - - var _this = this; - - /** Specimen Grid **/ - this.specimenGrid = new SpecimenGrid({ - minHeight : 425, - selectionMode : "SINGLE", - editEnabled : false, - updateRowEnabled : true, - width : 900, - showTitle : false - }); - - - this.specimenGrid.onSpecimenChanged.attach(function(sender, specimen) { - _this.experiment.setSpecimenById(specimen); - _this.refresh(_this.experiment); - }); - - this.specimenGrid.onSelected.attach(function(sender, specimens) { - if (specimens.length > 0) { - _this.specimenSelected = specimens[0]; - } else { - _this.specimenSelected = null; - } - _this.samplePlateGroupWidget.selectSpecimens(specimens); - }); - - - /** Sample plate Widget **/ - this.samplePlateGroupWidget = new SamplePlateGroupWidget({ - showTitle : false, - height : 250, - margin : 5, - bbar : true - }); - - - this.samplePlateGroupWidget.onExperimentChanged.attach(function(sender, json) { - _this.refresh(new Experiment(json)); - }); - - this.samplePlateGroupWidget.onClick.attach(function(sender, args) { - /** Clicking on a plate * */ - var row = args.row; - var column = args.column; - var samplePlateId = args.samplePlate.samplePlateId; - - /** is specimen selected on the grid? * */ - if (_this.specimenSelected != null) { - /** Is position target empty * */ - if (_this.experiment.getSampleByPosition(args.samplePlate.samplePlateId, args.row, args.column).length == 0) { - var specimen = _this.experiment.getSampleById(_this.specimenSelected.specimenId); - if (specimen.sampleplateposition3VO == null) { - specimen.sampleplateposition3VO = {}; - } - - specimen.sampleplateposition3VO = { - columnNumber : column, - rowNumber : row, - samplePlateId : samplePlateId - }; - - _this.samplePlateGroupWidget.panel.setLoading("ISPyB: Saving specimen"); - var adapter = new BiosaxsDataAdapter(); - /** If success * */ - adapter.onSuccess.attach(function(sender, experiment) { - _this.samplePlateGroupWidget.panel.setLoading(false); - }); - - adapter.onError.attach(function(sender, error) { - _this.samplePlateGroupWidget.panel.setLoading(false); - showError(error); - }); - - adapter.saveSpecimen(specimen, _this.experiment); - - _this.samplePlateGroupWidget.refresh(_this.experiment); - _this.specimenGrid.refresh(_this.experiment); - //_this.refresh(_this.experiment); - _this.specimenGrid.deselectAll(); - - } else { - /** - * Can we merge? We can merge when specimen are the - * same. So, same buffer, macromolecule, concentration * - */ - var target = _this.experiment.getSampleByPosition(args.samplePlate.samplePlateId, args.row, args.column)[0]; - var specimen = _this.experiment.getSampleById(_this.specimenSelected.specimenId); - - if ((specimen.bufferId == target.bufferId) && (specimen.concentration == target.concentration)) { - if (((specimen.macromolecule3VO != null) && (target.macromolecule3VO != null) && (specimen.macromolecule3VO.macromoleculeId == target.macromolecule3VO.macromoleculeId)) || - ((specimen.macromolecule3VO == null) && (target.macromolecule3VO == null))) { - var adapter = new BiosaxsDataAdapter(); - adapter.onSuccess.attach(function(sender, data) { - _this.refresh(new Experiment(data)); - _this.samplePlateGroupWidget.panel.setLoading(false); - - _this.onExperimentChanged.notify(experiment); - }); - adapter.onError.attach(function(sender, error) { - _this.samplePlateGroupWidget.panel.setLoading(false); - showError(error); - }); - _this.samplePlateGroupWidget.panel.setLoading("ISPyB: Merging specimens"); - adapter.mergeSpecimens(specimen.specimenId, target.specimenId); - } - } else { - alert("Well is not empty. Select another well!"); - } - } - } else { - var specimen = _this.experiment.getSampleByPosition(args.samplePlate.samplePlateId, args.row, args.column)[0]; - if (specimen != null) { - _this.specimenGrid.selectById(specimen.specimenId); - } - } - }); - - /** Events **/ - this.onExperimentChanged = new Event(this); -}; - -/** - * Return vbox or hbox depending on the slot positions of the plates - */ -SpecimenWidget.prototype.getContainerLayoutConfiguration = function(experiment){ - var dimensions = this.samplePlateGroupWidget.getDimensions(experiment.getSamplePlates()); - if (dimensions.maxSlotPositionRow < dimensions.maxSlotPositionColumn){ - return { - layout : "vbox", - specimenGridWidth : this.width - 10, - specimenGridHeight : this.height - 260, - samplePlateGroupWidth : this.width - 10, - samplePlateGroupHeight : 250 - }; - } - return { - layout : "hbox", - samplePlateGroupWidth : this.width*1/3 -10, - samplePlateGroupHeight : this.height - 10, - specimenGridWidth : this.width*2/3, - specimenGridHeight : this.height - 10 - }; - -}; - - -SpecimenWidget.prototype.refresh = function(experiment){ - this.experiment = experiment; - - /** Removing all components **/ - this.panel.removeAll(); - - var layoutConfiguration = this.getContainerLayoutConfiguration(experiment); - - /** Setting new width and height for layout vbox and hbox **/ - this.specimenGrid.width = layoutConfiguration.specimenGridWidth; - this.specimenGrid.height = layoutConfiguration.specimenGridHeight; - - this.samplePlateGroupWidget.width = layoutConfiguration.samplePlateGroupWidth; - this.samplePlateGroupWidget.height = layoutConfiguration.samplePlateGroupHeight; - - if (layoutConfiguration.layout == "hbox"){ - this.specimenGrid.margin = "0 0 0 5"; - this.specimenGrid.width =this.specimenGrid.width - 5; - } - /** Insert container depending on layout [vertical|horizontal] */ - var container = Ext.create('Ext.container.Container', { - layout : layoutConfiguration.layout, - height : this.height, - width : this.width, - padding : '2px', - items : [ ] - }); - if (layoutConfiguration.layout == "vbox"){ - container.insert(this.specimenGrid.getPanel()); - container.insert(this.samplePlateGroupWidget.getPanel()); - } - else{ - container.insert(this.samplePlateGroupWidget.getPanel()); - container.insert(this.specimenGrid.getPanel()); - } - - /** Insert Widget **/ - this.panel.insert(container); - - /** Load data **/ - this.specimenGrid.refresh(experiment); - this.samplePlateGroupWidget.refresh(experiment); - - -}; - -/** It creates a dummy container to be inserted the plates once the method refresh has been called - * This is necessay because we can not know the sample changer layout before hand - * **/ -SpecimenWidget.prototype.getPanel = function(){ - this.panel = Ext.create('Ext.container.Container', { - layout : 'vbox', - height : this.height, - border : 0, - margin : 5, - width : this.width, - items : [] - }); - return this.panel; -}; - - -SpecimenWidget.prototype.input = function() { - return { - experiment : DATADOC.getExperiment_10(), - proposal : DATADOC.getProposal_10() - }; -}; - -SpecimenWidget.prototype.test = function(targetId) { - var specimenWidget = new SpecimenWidget({ - height : 500, - width : 1000 - }); - BIOSAXS.proposal = new Proposal(specimenWidget.input().proposal); - var experiment = new Experiment(specimenWidget.input().experiment); - var panel = specimenWidget.getPanel(); - panel.render(targetId); - specimenWidget.refresh(experiment); - -}; - - +/** + * Widget container of Specimen grid and samplePlate widget + * Depending of the sample changer layout it may be displayed vertically or horizontally + * + * @param args + * + * #onExperimentChanged It happens when specimen are modified + */ +function SpecimenWidget(args){ + + this.width = 1000; + this.height = 600; + + if (args != null){ + if (args.width != null){ + this.width = args.width; + } + if (args.height != null){ + this.height = args.height; + } + } + + var _this = this; + + /** Specimen Grid **/ + this.specimenGrid = new SpecimenGrid({ + minHeight : 425, + selectionMode : "SINGLE", + editEnabled : false, + updateRowEnabled : true, + width : 900, + showTitle : false + }); + + + this.specimenGrid.onSpecimenChanged.attach(function(sender, specimen) { + _this.experiment.setSpecimenById(specimen); + _this.refresh(_this.experiment); + }); + + this.specimenGrid.onSelected.attach(function(sender, specimens) { + if (specimens.length > 0) { + _this.specimenSelected = specimens[0]; + } else { + _this.specimenSelected = null; + } + _this.samplePlateGroupWidget.selectSpecimens(specimens); + }); + + + /** Sample plate Widget **/ + this.samplePlateGroupWidget = new SamplePlateGroupWidget({ + showTitle : false, + height : 250, + margin : 5, + bbar : true + }); + + + this.samplePlateGroupWidget.onExperimentChanged.attach(function(sender, json) { + _this.refresh(new Experiment(json)); + }); + + this.samplePlateGroupWidget.onClick.attach(function(sender, args) { + /** Clicking on a plate * */ + var row = args.row; + var column = args.column; + var samplePlateId = args.samplePlate.samplePlateId; + + /** is specimen selected on the grid? * */ + if (_this.specimenSelected != null) { + /** Is position target empty * */ + if (_this.experiment.getSampleByPosition(args.samplePlate.samplePlateId, args.row, args.column).length == 0) { + var specimen = _this.experiment.getSampleById(_this.specimenSelected.specimenId); + if (specimen.sampleplateposition3VO == null) { + specimen.sampleplateposition3VO = {}; + } + + specimen.sampleplateposition3VO = { + columnNumber : column, + rowNumber : row, + samplePlateId : samplePlateId + }; + + _this.samplePlateGroupWidget.panel.setLoading("ISPyB: Saving specimen"); + var adapter = new BiosaxsDataAdapter(); + /** If success * */ + adapter.onSuccess.attach(function(sender, experiment) { + _this.samplePlateGroupWidget.panel.setLoading(false); + }); + + adapter.onError.attach(function(sender, error) { + _this.samplePlateGroupWidget.panel.setLoading(false); + showError(error); + }); + + adapter.saveSpecimen(specimen, _this.experiment); + + _this.samplePlateGroupWidget.refresh(_this.experiment); + _this.specimenGrid.refresh(_this.experiment); + //_this.refresh(_this.experiment); + _this.specimenGrid.deselectAll(); + + } else { + /** + * Can we merge? We can merge when specimen are the + * same. So, same buffer, macromolecule, concentration * + */ + var target = _this.experiment.getSampleByPosition(args.samplePlate.samplePlateId, args.row, args.column)[0]; + var specimen = _this.experiment.getSampleById(_this.specimenSelected.specimenId); + + if ((specimen.bufferId == target.bufferId) && (specimen.concentration == target.concentration)) { + if (((specimen.macromolecule3VO != null) && (target.macromolecule3VO != null) && (specimen.macromolecule3VO.macromoleculeId == target.macromolecule3VO.macromoleculeId)) || + ((specimen.macromolecule3VO == null) && (target.macromolecule3VO == null))) { + var adapter = new BiosaxsDataAdapter(); + adapter.onSuccess.attach(function(sender, data) { + _this.refresh(new Experiment(data)); + _this.samplePlateGroupWidget.panel.setLoading(false); + + _this.onExperimentChanged.notify(experiment); + }); + adapter.onError.attach(function(sender, error) { + _this.samplePlateGroupWidget.panel.setLoading(false); + showError(error); + }); + _this.samplePlateGroupWidget.panel.setLoading("ISPyB: Merging specimens"); + adapter.mergeSpecimens(specimen.specimenId, target.specimenId); + } + } else { + alert("Well is not empty. Select another well!"); + } + } + } else { + var specimen = _this.experiment.getSampleByPosition(args.samplePlate.samplePlateId, args.row, args.column)[0]; + if (specimen != null) { + _this.specimenGrid.selectById(specimen.specimenId); + } + } + }); + + /** Events **/ + this.onExperimentChanged = new Event(this); +}; + +/** + * Return vbox or hbox depending on the slot positions of the plates + */ +SpecimenWidget.prototype.getContainerLayoutConfiguration = function(experiment){ + var dimensions = this.samplePlateGroupWidget.getDimensions(experiment.getSamplePlates()); + if (dimensions.maxSlotPositionRow < dimensions.maxSlotPositionColumn){ + return { + layout : "vbox", + specimenGridWidth : this.width - 10, + specimenGridHeight : this.height - 260, + samplePlateGroupWidth : this.width - 10, + samplePlateGroupHeight : 250 + }; + } + return { + layout : "hbox", + samplePlateGroupWidth : this.width*1/3 -10, + samplePlateGroupHeight : this.height - 10, + specimenGridWidth : this.width*2/3, + specimenGridHeight : this.height - 10 + }; + +}; + + +SpecimenWidget.prototype.refresh = function(experiment){ + this.experiment = experiment; + + /** Removing all components **/ + this.panel.removeAll(); + + var layoutConfiguration = this.getContainerLayoutConfiguration(experiment); + + /** Setting new width and height for layout vbox and hbox **/ + this.specimenGrid.width = layoutConfiguration.specimenGridWidth; + this.specimenGrid.height = layoutConfiguration.specimenGridHeight; + + this.samplePlateGroupWidget.width = layoutConfiguration.samplePlateGroupWidth; + this.samplePlateGroupWidget.height = layoutConfiguration.samplePlateGroupHeight; + + if (layoutConfiguration.layout == "hbox"){ + this.specimenGrid.margin = "0 0 0 5"; + this.specimenGrid.width =this.specimenGrid.width - 5; + } + /** Insert container depending on layout [vertical|horizontal] */ + var container = Ext.create('Ext.container.Container', { + layout : layoutConfiguration.layout, + height : this.height, + width : this.width, + padding : '2px', + items : [ ] + }); + if (layoutConfiguration.layout == "vbox"){ + container.insert(this.specimenGrid.getPanel()); + container.insert(this.samplePlateGroupWidget.getPanel()); + } + else{ + container.insert(this.samplePlateGroupWidget.getPanel()); + container.insert(this.specimenGrid.getPanel()); + } + + /** Insert Widget **/ + this.panel.insert(container); + + /** Load data **/ + this.specimenGrid.refresh(experiment); + this.samplePlateGroupWidget.refresh(experiment); + + +}; + +/** It creates a dummy container to be inserted the plates once the method refresh has been called + * This is necessay because we can not know the sample changer layout before hand + * **/ +SpecimenWidget.prototype.getPanel = function(){ + this.panel = Ext.create('Ext.container.Container', { + layout : 'vbox', + height : this.height, + border : 0, + margin : 5, + width : this.width, + items : [] + }); + return this.panel; +}; + + +SpecimenWidget.prototype.input = function() { + return { + experiment : DATADOC.getExperiment_10(), + proposal : DATADOC.getProposal_10() + }; +}; + +SpecimenWidget.prototype.test = function(targetId) { + var specimenWidget = new SpecimenWidget({ + height : 500, + width : 1000 + }); + BIOSAXS.proposal = new Proposal(specimenWidget.input().proposal); + var experiment = new Experiment(specimenWidget.input().experiment); + var panel = specimenWidget.getPanel(); + panel.render(targetId); + specimenWidget.refresh(experiment); + +}; + + function WarningWidget(args) { this.actions = []; diff --git a/ispyb-ws/src/main/java/ispyb/ws/rest/mx/AutoprocintegrationRestWebService.java b/ispyb-ws/src/main/java/ispyb/ws/rest/mx/AutoprocintegrationRestWebService.java index cdfe38b5e..4de80758b 100644 --- a/ispyb-ws/src/main/java/ispyb/ws/rest/mx/AutoprocintegrationRestWebService.java +++ b/ispyb-ws/src/main/java/ispyb/ws/rest/mx/AutoprocintegrationRestWebService.java @@ -8,6 +8,8 @@ import ispyb.server.mx.vos.autoproc.AutoProcIntegration3VO; import ispyb.server.mx.vos.autoproc.AutoProcProgram3VO; import ispyb.server.mx.vos.autoproc.AutoProcProgramAttachment3VO; +import ispyb.server.mx.vos.collections.DataCollection3VO; +import ispyb.server.mx.vos.collections.Session3VO; import java.io.File; import java.util.ArrayList; @@ -32,6 +34,7 @@ public class AutoprocintegrationRestWebService extends MXRestWebService { private final static Logger logger = Logger.getLogger(AutoprocintegrationRestWebService.class); + private static final String NOT_ALLOWED = "You don't have access to this resource"; @RolesAllowed({ "User", "Manager", "Industrial", "Localcontact" }) @GET @@ -126,6 +129,13 @@ public Response getAttachments(@PathParam("token") String token, @PathParam("pro } + + + private boolean checkProposalByAutoProcProgramId(int proposalId, int autoProcProgramId) throws NamingException, Exception{ + return this.getSession3Service().findByAutoProcProgramId(autoProcProgramId).getProposalVOId().equals(proposalId); + } + + /** * AutoProcProgramAttachment has not AutoProcProgramId mapped in the EJB object * so it is necessary to keep separately the possible list of ids in order @@ -147,13 +157,19 @@ public Response downloadAttachments( String methodName = "downloadAttachments"; long start = this.logInit(methodName, logger, token, proposal); try { - List ids = this.parseToInteger(autoprocattachmentids); + List autoProcProgramIds = this.parseToInteger(autoprocattachmentids); List> list = new ArrayList>(); HashMap filePaths = new HashMap(); String filename = "download.zip"; - for (Integer id : ids) { - AutoProcProgram3VO autoProcProgram3VO = this.getAutoProcProgram3Service().findByPk(id, true); + for (Integer autoProcProgramId : autoProcProgramIds) { + /** Check that id correspond to the proposal **/ + if (!this.checkProposalByAutoProcProgramId(this.getProposalId(proposal), autoProcProgramId)){ + throw new Exception(NOT_ALLOWED); + } + + + AutoProcProgram3VO autoProcProgram3VO = this.getAutoProcProgram3Service().findByPk(autoProcProgramId, true); /** Prefix for the name of the file and the internal structure if many results are retrieved **/ String prefix = String.format("%s_%s", autoProcProgram3VO.getProcessingPrograms(), autoProcProgram3VO.getAutoProcProgramId()); @@ -164,7 +180,7 @@ public Response downloadAttachments( String filePath = auto.getFilePath() + "/" + auto.getFileName(); if (new File(filePath).exists()){ if (new File(filePath).isFile()){ - if (ids.size() > 1){ + if (autoProcProgramIds.size() > 1){ String zipNameFile = prefix + "/" + auto.getFileName(); filePaths.put(zipNameFile, filePath); } @@ -176,7 +192,7 @@ public Response downloadAttachments( } /** If it is a single result then filename is the name of the program and the ID **/ - if (ids.size() == 1){ + if (autoProcProgramIds.size() == 1){ filename = prefix + ".zip"; } @@ -333,6 +349,10 @@ public Response getXScaleWilson(@PathParam("token") String token, @PathParam("pr } } + private boolean checkProposalByAutoProcProgramAttachmentId(int proposalId, int autoProcProgramAttachmentId) throws NamingException, Exception{ + return this.getSession3Service().findByAutoProcProgramAttachmentId(autoProcProgramAttachmentId).getProposalVOId().equals(proposalId); + } + @RolesAllowed({ "User", "Manager", "Industrial", "Localcontact" }) @GET @Path("{token}/proposal/{proposal}/mx/autoprocintegration/autoprocattachmentid/{autoProcAttachmentId}/download") @@ -343,11 +363,17 @@ public Response downloadAutoProcAttachment(@PathParam("token") String token, @Pa String methodName = "downloadAutoProcAttachment"; long start = this.logInit(methodName, logger, token, proposal); try { - AutoProcProgramAttachment3VO attachment = this.getAutoProcProgramAttachment3Service().findByPk(autoProcAttachmentId); - this.logFinish(methodName, start, logger); - File file = new File(attachment.getFilePath() + "/" + attachment.getFileName()); - this.logFinish(methodName, start, logger); - return this.downloadFileAsAttachment(file.getAbsolutePath()); + /** Checking that attachment is linked to the proposal **/ + if (this.checkProposalByAutoProcProgramAttachmentId(this.getProposalId(proposal), autoProcAttachmentId)){ + AutoProcProgramAttachment3VO attachment = this.getAutoProcProgramAttachment3Service().findByPk(autoProcAttachmentId); + this.logFinish(methodName, start, logger); + File file = new File(attachment.getFilePath() + "/" + attachment.getFileName()); + this.logFinish(methodName, start, logger); + return this.downloadFileAsAttachment(file.getAbsolutePath()); + } + else{ + throw new Exception(NOT_ALLOWED); + } } catch (Exception e) { return this.logError(methodName, e, start, logger); } @@ -360,13 +386,19 @@ public Response downloadAutoProcAttachment(@PathParam("token") String token, @Pa public Response getAutoProcAttachment(@PathParam("token") String token, @PathParam("proposal") String proposal, @PathParam("autoProcAttachmentId") int autoProcAttachmentId) { - String methodName = "downloadAutoProcAttachment"; + String methodName = "getAutoProcAttachment"; long start = this.logInit(methodName, logger, token, proposal); try { - AutoProcProgramAttachment3VO attachment = this.getAutoProcProgramAttachment3Service().findByPk(autoProcAttachmentId); - File file = new File(attachment.getFilePath() + "/" + attachment.getFileName()); - this.logFinish(methodName, start, logger); - return this.downloadFile(file.getAbsolutePath()); + /** Checking that attachment is linked to the proposal **/ + if (this.checkProposalByAutoProcProgramAttachmentId(this.getProposalId(proposal), autoProcAttachmentId)){ + AutoProcProgramAttachment3VO attachment = this.getAutoProcProgramAttachment3Service().findByPk(autoProcAttachmentId); + File file = new File(attachment.getFilePath() + "/" + attachment.getFileName()); + this.logFinish(methodName, start, logger); + return this.downloadFile(file.getAbsolutePath()); + } + else{ + throw new Exception(NOT_ALLOWED); + } } catch (Exception e) { return this.logError(methodName, e, start, logger); }